首页 > 解决方案 > 带有 PendingIntent 和 putExtra 的 Java 通知不起作用

问题描述

我有一条 FireBase 消息。如果它进来,我会显示一个通知(作品)。当我单击通知时,它应该打开我的应用程序(工作)。现在我想使用 putExtra() 将一些信息交给我的应用程序(仅有时有效 - 如果应用程序位于前台)。那是我的问题。

   private void sendMyNotification(String message) {

    int rndNo4Intent = Math.round((float)(Math.random()*100000000));
    int rndNo4Msg = Math.round((float)(Math.random()*100000000));

    //On click of notification it redirect to this Activity
    Intent intent = new Intent(this, MainActivity.class);
    intent.putExtra("action","openWiki"+rndNo4Msg); // My Test-Data

    PendingIntent pendingIntent = PendingIntent.getActivity(this, rndNo4Intent , intent, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    String channelId = getString(R.string.default_notification_channel_id);
    Uri soundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("CodingSpace")
            .setContentText(message)
            .setAutoCancel(true)
            .setSound(soundUri)
            .setContentIntent(pendingIntent);

    // Since android Oreo notification channel is needed. Sonst kommt nichts an.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel(channelId,
                "CodingSpaceChannel",
                NotificationManager.IMPORTANCE_HIGH);               // in Oreo ist High so, dass es einen Ton gibt
        notificationManager.createNotificationChannel(channel);
    }


   notificationManager.notify(rndNo4Msg, notificationBuilder.build());
}

在 .MainActivity 类中:

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

    ...        


    Intent iin= getIntent();
    String msg = iin.getStringExtra("action");
    Toast.makeText(MainActivity.this,"get: "+ msg,Toast.LENGTH_SHORT).show();

标签: androidnotifications

解决方案


推荐阅读