Как сделать тост в заголовке уведомления FCM pu sh при нажатии в активности spla sh или основной активности? - PullRequest
0 голосов
/ 10 апреля 2020

Я занимаюсь разработкой приложения, в которое встроено уведомление pu sh. Я хочу открыть различные действия моего приложения на основе заголовка уведомления. Проблема в том, что я могу получить заголовок уведомления только тогда, когда приложение находится на переднем плане. Но когда am находится в фоновом режиме уничтожения, приложение не отображает и не отображает заголовок уведомления FCM. Вот мой код для моей службы сообщений Firebase. '' 'publi c class MyFirebaseMessagingService extends FirebaseMessagingService {

private final String ADMIN_CHANNEL_ID ="admin_channel";
private static final String TAG = "mFirebaseIIDService";
private static final String SUBSCRIBE_TO = "userABCd";


@Override
public void onNewToken(String token) {

    FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(new OnSuccessListener<InstanceIdResult>() {
        @Override
        public void onSuccess(InstanceIdResult instanceIdResult) {
            String token = instanceIdResult.getToken();
            FirebaseMessaging.getInstance().subscribeToTopic(SUBSCRIBE_TO);
            Log.i(TAG, "onTokenRefresh completed with token: " + token);

        }
    });


}
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    String title = remoteMessage.getNotification().getTitle();

    Intent intent = new Intent(this, splashactivity.class);
    intent.putExtra("title", title);
   NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    int notificationID = new Random().nextInt(3000);

  /*
    Apps targeting SDK 26 or above (Android O) must implement notification channels and add its notifications
    to at least one of them. Therefore, confirm if version is Oreo or higher, then setup notification channel
  */
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        setupChannels(notificationManager);
    }

    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this , 0, intent,
            PendingIntent.FLAG_ONE_SHOT);


    Bitmap largeIcon = BitmapFactory.decodeResource(getResources(),
            R.mipmap.ic_launcher_round);

    Uri notificationSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, ADMIN_CHANNEL_ID)
            .setSmallIcon(R.mipmap.ic_launcher_round)
            .setLargeIcon(largeIcon)
            .setContentTitle(remoteMessage.getData().get("title"))
            .setContentText(remoteMessage.getData().get("message"))
            .setAutoCancel(true)
            .setSound(notificationSoundUri)
            .setContentIntent(pendingIntent);

    //Set notification color to match your app color template
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
        notificationBuilder.setColor(getResources().getColor(R.color.colorPrimaryDark));
    }
    notificationManager.notify(notificationID, notificationBuilder.build());
}


@RequiresApi(api = Build.VERSION_CODES.O)
private void setupChannels(NotificationManager notificationManager){
    CharSequence adminChannelName = "New notification";
    String adminChannelDescription = "Device to device notification";

    NotificationChannel adminChannel;
    adminChannel = new NotificationChannel(ADMIN_CHANNEL_ID, adminChannelName, NotificationManager.IMPORTANCE_HIGH);
    adminChannel.setDescription(adminChannelDescription);
    adminChannel.enableLights(true);
    adminChannel.setLightColor(Color.RED);
    adminChannel.enableVibration(true);
    if (notificationManager != null) {
        notificationManager.createNotificationChannel(adminChannel);
    }

}

}' '' А вот код для моей деятельности spla sh, которую я хочу получить в заголовке моего pu sh Уведомление '' 'Publi c класс Splashactivity расширяет AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    requestWindowFeature(getWindow().FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_splashactivity);
    onNewIntent(getIntent());
}



@Override
public void onNewIntent(Intent intent){

    super.onNewIntent(intent);
    Bundle extras = intent.getExtras();
    if(extras != null){
        if(extras.containsKey("title"))
        {

            String notificationtitle = extras.getString("title");

            Toast.makeText(splashactivity.this, notificationtitle, Toast.LENGTH_LONG).show();

        }
    }

    /****** Create Thread that will sleep for 5 seconds****/
    Thread background = new Thread() {
        public void run() {
            try {
                // Thread will sleep for 5 seconds
                sleep(4* 1000);

                // After 4 seconds redirect to another intent
                Intent i = new Intent(getBaseContext(), MainActivity.class);
                startActivity(i);

                //Remove activity
                finish();
            } catch (Exception e) {
            }
        }
    };
    // start thread
    background.start();

}

}

' ''

...