手动启动FireBase服务

时间:2018-12-16 11:47:38

标签: android firebase service firebase-cloud-messaging

我正在创建一个包含FireBase Messaging Service的应用程序。
我添加了服务以显示:

 <service android:name="xxx.xxx.MyFirebaseInstanceIdService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
            </intent-filter>
        </service>

 <service android:name="xxx.xxx.MyFireBaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

我有两个类来获取令牌和firebase消息:

public class MyFirebaseInstanceIdService extends FirebaseInstanceIdService {

    @Override
    public void onTokenRefresh() {
        super.onTokenRefresh();
        String recent_token = FirebaseInstanceId.getInstance().getToken();
        SharedPreferences sp = getSharedPreferences("mypref", 0);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("token", recent_token);
        editor.apply();
    }
}

和消息传递类:

public class MyFireBaseMessagingService extends FirebaseMessagingService {


    @Override
    public void onMessageReceived(final RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
        Intent intent = new Intent(MyFireBaseMessagingService.this, AdvCreateActivity.class);
        intent.putExtra("mode","notification");
        intent.putExtra("text",remoteMessage.getNotification().getBody());
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(MyFireBaseMessagingService.this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(MyFireBaseMessagingService.this);
        notificationBuilder.setContentTitle(remoteMessage.getNotification().getTitle());
        notificationBuilder.setContentText(remoteMessage.getNotification().getBody());
        notificationBuilder.setAutoCancel(true);
        notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
        notificationBuilder.setContentIntent(pendingIntent);
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0,notificationBuilder.build());
    }
}

应用启动时,firebase服务会自动启动。如果设备没有互联网连接,那么我将无法收到令牌。如果我打开数据或wifi,firebase将不会发送令牌!
我的问题是:应用程序启动后,如何手动启动Firebase服务? (我不希望Firebase服务从启动应用程序开始!!!)

1 个答案:

答案 0 :(得分:0)

无论您要获取fcm ID的何处,请调用以下方法。

try {
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d("Firbase id login", "Refreshed token: " + refreshedToken);
    } catch (Exception e) {
        e.printStackTrace();
    }