Android点击通知后如何使用getExtras()方法获取附加信息

3

我有一个严重的问题。在我的Android应用程序中,我有以下代码:

类:MessagingService.class

public void onMessageReceived(RemoteMessage remoteMessage) {
String title = remoteMessage.getNotification().getTitle();
String messaggio  =remoteMessage.getNotification().getBody();
String data = remoteMessage.getData().get("json");

JSON json = new JSON();
String fragment = json.getNotificaFragment(data);

Log.d("MessagingService","Fragment Ricevuto: " + fragment);


int requestID = (int) System.currentTimeMillis();


Intent intent = new Intent(this, LoginActivity.class);
intent.putExtra("fragment", fragment); //Put your id to your next Intent
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, requestID, intent, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
notificationBuilder.setContentTitle(title);
notificationBuilder.setContentText(messaggio);
notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
notificationBuilder.setVibrate(new long[] { 500, 500 });
notificationBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI);
notificationBuilder.setAutoCancel(true);
notificationBuilder.setContentIntent(pendingIntent);
notificationBuilder.setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND | Notification.FLAG_SHOW_LIGHTS);


NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());

super.onMessageReceived(remoteMessage);

}

类名: LoginActivity.class

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    Log.d("APP", "AVVIO APPLICAZIONE");

    String fragmentDaAprire = getIntent().getStringExtra("fragment");
    Log.e("Bundle","Fragment da Aprire: " + fragmentDaAprire);

问题是:
当我收到通知并且我的应用程序处于打开状态时,结果是正确的:
    01-15 15:09:12.301 11419-11419/livio.***E/Bundle: Fragment da Aprire: messaggi
但是当我收到通知并且我的应用程序处于关闭状态时,当我点击通知时结果是不正确的 :(
   01-15 15:09:12.301 11419-11419/livio.*** E/Bundle: Fragment da Aprire: null
感谢您的帮助。

使用getIntent().getExtras()。 - Nas
对不起,但是不起作用。 - Livio Macchia
2个回答

0
你应该检查一下这条语句 String fragment = json.getNotificaFragment(data);。它没有正确地获取到数据。

0
尝试这个:
  Intent iin = getIntent();
        Bundle b = iin.getExtras();
        if (b != null) {
            fragmentDaAprire= (String) b.get("fragment");
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接