2017-08-26 59 views
4

大家好, 我在服务中实现了一个通知,当它出现时单击通知 - 它会打开一个活动。 我有我的服务类的代码运行不间断每隔几秒钟一个可运行的内部:Android通知返回到错误的活动

NotificationCompat.Builder builder = new NotificationCompat.Builder(this) 
      .setSmallIcon(android.R.drawable.ic_dialog_email) 
      .setContentTitle(notificationTitle) 
      .setContentText(notificationMessage); 

    NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle(); 

    builder.setStyle(bigText); 

    Intent resultIntent = new Intent(this, openemailactivity.class); 

    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT); 

    builder.setContentIntent(pendingIntent); 

    Notification notification = builder.build(); 
    notification.flags = Notification.FLAG_AUTO_CANCEL; 

    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this); 
    notificationManager.notify(0, notification); 

在我通知活动命名为“openemailactivity”我有一个按钮,其中有一个代码,它向用户返回家庭活动称为“MainActivity”:直到我重新启动我的Android手机,在启动服务负载(如预期)

btnReturnToMainScreen.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 

      Intent intent = new Intent(getApplicationContext(), MainActivity.class); 
      intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
      startActivity(intent); 
     } 
    }); 

一切正常,然后生成一个通知,然后我点击它。 然后,当我点击它时,“openemailactivity”活动也按预期打开,然后点击打开“MainActivity”(上面的代码)的按钮,它就这样做了。

现在问题开始了!

在此其他活动打开后(“MainActivity”),然后服务再次弹出通知(通知计时器\检查运行在定时处理程序\ Runnable中运行不间断) - 然后单击通知本身被创建 - 它应该调用的活动(“openemailactivity”)不再被调用!改为 - 最后一次调用的活动弹出(“MainActivity”),这是错误的!

只有当我重新启动手机,启动时会加载服务,生成通知,点击它,打开正确的活动,然后从按钮(OnClickListener)调用代码时,问题才会启动。

我对如何解决这个问题没有线索。

您认为可以是什么问题? 我在做什么错,我该如何解决?

感谢您的回复。

+0

尝试将Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED添加到pendingIntent并在此处更新 –

+0

您好,非常感谢您的快速回答。我试图将该标志添加到pendingIntent。它不能完成,因为它根据我上面的代码不接受它,所以我将该标志添加到resultIntent中。经过测试 - 它什么都没做。问题依然存在。 – DevTester

+0

我认为我找到了答案。你当然给了我一个很好的线索 - 太多的意图添加某种标志。请在此页面上进一步查看我的以下答案。再次感谢提示! – DevTester

回答

0

奇怪,但它看起来像我找到了答案(希望 - 它需要得到更全面的测试,因为惊喜总是存在于这个环境中)。

我试图设置:

resultIntent.addFlags(FLAG_ACTIVITY_CLEAR_TOP); 

在存在于该服务的通知代码,声明该变量(resultIntent)之后。

至于现在它看起来像它的作品! 通过查看此标志的Android文档,它看起来可能会解释我遇到的问题: https://developer.android.com/reference/android/content/Intent.html (搜索“FLAG_ACTIVITY_CLEAR_TOP”的说明)。