我正在尝试创建一个通知,当点击时会在我的应用程序中显示一条消息,然后当用户单击后退按钮时,我希望它返回到我的主屏幕。
问题是现在它创建了一个全新的实例,所有以前的数据都丢失了。我做错了什么?
NotificationManager nm = (NotificationManager) getSystemService("notification");
Intent intent = new Intent(this, beerwarn.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(beerwarn.class);
stackBuilder.addNextIntent(intent);
PendingIntent pIntent = stackBuilder.getPendingIntent
(0, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentIntent(pIntent)
//Notification noti = new Notification.Builder(this)
.setContentTitle("BAC Level Notice")
.setContentText("Your BAC has dropped below Max Legal BAC")
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pIntent)
.setSmallIcon(R.drawable.beerwarn);
//builder.flags |= Notification.FLAG_AUTO_CANCEL;
nm.notify(1, builder.build());
答案 0 :(得分:0)
在androidmanifest.xml中的活动中添加android: launchMode = singleTask
或singleInstance
<activity
android:name="yourmainscreenActivity"
android:exported="false"
android:launchMode="singleTask" >
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
答案 1 :(得分:0)
这是我的建议,当你打开消息屏幕时,清除所有其他活动。
NotificationManager nm = (NotificationManager) getSystemService("notification");
Intent intent = new Intent(this, beerwarn.class);
intent .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent , PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentIntent(pIntent)
.setContentTitle("BAC Level Notice")
.setContentText("Your BAC has dropped below Max Legal BAC")
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pIntent)
.setSmallIcon(R.drawable.beerwarn);
nm.notify(1, builder.build());
在beerwarn.class上,覆盖onBackPressed函数,检查你的主屏幕活动是否正在运行,假设它名为MainScreen.class,如果没有,则启动它。
ActivityManager mngr = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> taskList = mngr.getRunningTasks(10);
for (ActivityManager.RunningTaskInfo rti : taskList) {
if (rti.topActivity.getClassName().equals(this.getClass().getName())) {
if (!rti.baseActivity.getClassName().equals(MainScreen.class.getName())) {
Intent i = new Intent(this, MainScreen.class);
i.putExtra("currentTab", getIntent().getIntExtra("currentTab", 1));
startActivity(i);
break;
}
}
}
super.onBackPressed();