не получать токен и уведомление FCM на устройстве - PullRequest
0 голосов
/ 11 июля 2019

Я интегрировал FCM в свое приложение. Отправил fcm из Firebase, но не отображал на устройстве. Я пытаюсь отобразить уведомление, когда мое приложение передний план и фон.

1-: подключить приложение к Firebase и добавить FCM в мое приложение. (Android Studio -> Инструменты -> Firebase -> Облачные сообщения)

2-: создать класс MyFirebaseMessageingService1 и расширить его с помощью FirebaseMessagingService и реализовать метод (onNewToken и onMessageReceived)

3-: создать метод genrateNotification в onMessageReceived

4-: добавьте эту услугу в файл манифеста и добавьте действие com.google.firebase.MESSAGING_EVENT

 private void genrateNotification(String body, String title) {
     Intent intent = new Intent(this,MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
       PendingIntent pendingIntent=PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT);
         Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
         NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                 .setSmallIcon(R.drawable.app_icon)
                 .setContentTitle(title)
                 .setContentText(body)
                 .setAutoCancel(true)
                 .setSound(soundUri)
                 .setContentIntent(pendingIntent);

         NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

         if(NOTIFICATION_ID > 1073741824){
             NOTIFICATION_ID =0;
                     }
                     notificationManager.notify(NOTIFICATION_ID++,notificationBuilder.build());
     }

не получить токен и уведомление после реализации кода выше

1 Ответ

0 голосов
/ 11 июля 2019

Перед извлечением токена убедитесь, что:

  • Ваше устройство подключено к Интернету.
  • Приложение успешно подключено к firebase.
  • На устройстве установлена ​​последняя версия GooglePlayServices.

Теперь, чтобы получить токен в любое время:

FirebaseInstanceId.getInstance().getInstanceId()
    .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
        @Override
        public void onComplete(@NonNull Task<InstanceIdResult> task) {
            if (!task.isSuccessful()) {
                Log.w(TAG, "getInstanceId failed", task.getException());
                return;
            }

            // Get new Instance ID token
            String token = task.getResult().getToken();

            // Log and toast
            String msg = getString(R.string.msg_token_fmt, token);
            Log.d(TAG, msg);
            Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
        }
    });

Ваш MyNotificationService класс:

    public class MyNotificationService extends FirebaseMessagingService {

        @Override
        public void onMessageReceived(RemoteMessage remoteMessage) {
            super.onMessageReceived(remoteMessage);

            Intent intent = new Intent(this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
            String channelId = "Default";

            NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle(remoteMessage.getNotification().getTitle())
                    .setContentText(remoteMessage.getNotification().getBody())
                    .setAutoCancel(true)
                    .setContentIntent(pendingIntent);


            NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                NotificationChannel channel = new NotificationChannel(channelId, "Default channel", NotificationManager.IMPORTANCE_DEFAULT);
                manager.createNotificationChannel(channel);
            }
            manager.notify(0, builder.build());
        }

        @Override
        public void onNewToken(String s) {
            super.onNewToken(s);
            Log.d(TAG, "NewToken: " + s);
        }
}

В вашем манифесте:

<service
        android:name=".MyNotificationService"
        android:exported="false">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
</service>
...