【问题标题】:Notification Intent - How to resume the activity in a notification without resetting?通知意图 - 如何在不重置的情况下恢复通知中的活动?
【发布时间】:2019-08-22 21:53:31
【问题描述】:

我正在制作一个计时器应用程序。因此,当点击开始按钮时,通知会显示出来,而当用户点击通知时,计时器应该会恢复,而不是显示一个 新活动 从头开始​​。

我已经尝试TaskStackbuilder 仍然存在问题。

Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class);

TaskStackBuilder stackBuilder = TaskStackBuilder.create(getApplicationContext());
stackBuilder.addNextIntentWithParentStack(resultIntent);

PendingIntent res = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);

Notification not = new NotificationCompat.Builder(this,CHANNEL_ID)
            .setSmallIcon(R.drawable.ic_timer)
            .setContentTitle("Productivity Timer")
            .setContentText("Your Timer is Running")
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setCategory(NotificationCompat.CATEGORY_PROGRESS)
            .setOngoing(true)
            .setContentIntent(res)
            .build();

notificationManager.notify(1,not);

【问题讨论】:

    标签: java android android-intent timer android-notifications


    【解决方案1】:

    我用它来恢复活动

    清单

    <activity
        android:name=".MainActivity"
        android:launchMode="singleTask" />
    

    您也可以在需要将活动放在前面时使用它

    private void bringAppFront() {
        try {
            Intent i = new Intent(this, MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(i);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
    

    【讨论】:

      【解决方案2】:

      我对您的代码进行了一些更改。请查看相同内容,如果您仍有任何疑问,请告诉我。

       Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class);
      
      
      PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
      
      
      Notification not = new NotificationCompat.Builder(this,CHANNEL_ID)
              .setSmallIcon(R.drawable.ic_timer)
              .setContentTitle("Productivity Timer")
              .setContentText("Your Timer is Running")
              .setPriority(NotificationCompat.PRIORITY_HIGH)
              .setCategory(NotificationCompat.CATEGORY_PROGRESS)
              .setOngoing(true)
              .setContentIntent(pendingIntent)
              .build();
           notificationManager.notify(1,not);
      

      谢谢。

      【讨论】:

      • 请说明您所做的更改将如何解决问题。
      • 请将您的代码与我的代码进行比较。如果您的问题的解决方案是这样,那么您可以对此有所了解。
      • 主要是,我更改了挂起的意图初始化并删除了 taskstackbuilder.according to me,这造成了问题。
      • 这不是我的代码。作为 Stack Overflow 的一员,我建议您提高答案的质量,以便对未来的访问者有用。
      • '@PoojaShukla 非常感谢!它醒了!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-24
      • 1970-01-01
      • 1970-01-01
      • 2011-03-19
      相关资源
      最近更新 更多