Я создаю приложение, содержащее 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 запускалась при запуске приложения !!!)
Пожалуйста, вызовите следующий метод везде, где вы хотите получить свой идентификатор fcm.
try {
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d("Firbase id login", "Refreshed token: " + refreshedToken);
} catch (Exception e) {
e.printStackTrace();
}