0

我正在尝试创建一个通知,单击该通知会在我的应用程序中显示一条消息,然后当用户单击后退按钮时,我希望它返回到我的主屏幕。

问题是现在它创建了一个全新的实例,并且所有以前的数据都丢失了。我究竟做错了什么?

 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());
4

2 回答 2

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>
于 2013-05-02T03:16:07.323 回答
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();
于 2013-05-02T03:43:24.517 回答