我遇到的问题是,单击通知会使我陷入错误的片段中。
这是详细的问题-
点击通知-> intent.getStringExtra("id")
被困在我的onCreate()
的MainActivity中。
在这里,我说转到具有2个传呼机(子片段)的片段B,分别说C和D。
所以B处理了所需的片段D的打开,我可以看到片段D打开了1秒钟,但它跳回到了片段A,这是我的家庭片段。
这是我的MainActivity.java代码-
if (getIntent().getStringExtra("id") != null) {
String id = getIntent().getStringExtra("id");
if (id == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.frag, new FragA()).addToBackStack(null).commit();
} else {
Fragment fragment = new FragB();
Bundle bundle = new Bundle();
bundle.putString("id", id);
fragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment).addToBackStack(null).commit();
}
}
这是我的通知代码-
Notification buildNotification(final String id) {
Intent notificationIntent = new Intent(this.context, MainActivity.class);
notificationIntent.putExtra("id", id);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(notificationIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(100, PendingIntent.FLAG_UPDATE_CURRENT);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
return new NotificationCompat.Builder(this.context, "channel_id")
.setContentTitle("Title")
.setContentText("Message")
.setSmallIcon(R.drawable.icon)
.setAutoCancel(true)
.setContentIntent(resultPendingIntent)
.build();
}
private class NotificationReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context ctx, Intent intent) {
NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
String id = intent.getStringExtra("id");
if (notificationManager != null) {
Notification notification = buildNotification(id);
if (notification != null) {
notificationManager.notify(100, notification);
}
}
}
}