【问题标题】:Prevent creating new activities from notification click防止从通知点击创建新活动
【发布时间】:2020-05-29 09:10:30
【问题描述】:

我有一个使用 IntentService 在后台工作的应用程序,即使它已关闭。

有一个按钮可以启动后台进程并出现通知。在用户按下另一个停止 IntentService 的按钮之前,此通知不会消失。

但这里我遇到了另一个问题。我第一次启动一个应用程序。然后按下初始化 IntentService 的按钮,出现通知。在那之后,当应用程序仍在屏幕上时,我按下通知,看起来应用程序创建了它的副本。我可以多次单击通知,并创建了许多应用程序副本。

刚刚发现了一些技巧,例如向 PendingIntent 添加标志并在清单中插入一些字符串,但到目前为止没有任何帮助。

也许我需要更改通知或待处理意图?

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
    createNotificationChannel()

    val notificationIntent = Intent(this, MainActivity::class.java)
    val pendingIntent = PendingIntent.getActivity(
        this,
        0, notificationIntent,  PendingIntent.FLAG_CANCEL_CURRENT
    )
    val notification = NotificationCompat.Builder(this, CHANNEL_ID)
        .setContentTitle("Foreground Service Kotlin Example")
        .setContentText("kylsha")
        .setSmallIcon(R.drawable.ic_notification)
        .setContentIntent(pendingIntent)
        .build()

    startForeground(1, notification)

    return super.onStartCommand(intent, flags, startId)
}

这是它的样子

我希望仅在应用程序关闭或最小化时通知启动活动,而不是创建它的多个副本。是不是应该对pendingIntent做点什么?

【问题讨论】:

  • 你试过了吗? developer.android.com/training/notify-user/navigation。您必须对活动的未决意图使用 UPDATE_CURRENT flat。您将在活动中使用更新的意图获得回调 onNewIntent 方法。我曾经遇到过类似的问题,我特别记得使用 onNewIntent 回调来获取带有 UPDATE_CURRENT 标志的新意图以用于挂起的意图。
  • @JudeOsbertK 谢谢,你是对的。除此之外,我还必须在 Manifes 的 acritivity sectiont 中添加一些字符串:android:launchMode="singleTask" android:taskAffinity="" android:excludeFromRecents="true"

标签: android kotlin android-intent android-activity notifications


【解决方案1】:

试试这个代码可能对你有帮助

notification = new NotificationCompat.Builder(context);
        notification.setAutoCancel(true);
        notification.setSmallIcon(R.mipmap.ic_launcher);
        notification.setWhen(System.currentTimeMillis());
        notification.setTicker("Transferring data...");
        notification.setContentTitle(context.getResources().getString(R.string.app_name));
        notification.setContentTitle("Transferring data...");
        notification.setOngoing(true);
        notification.setDefaults(Notification.FLAG_ONGOING_EVENT);
        notification.setContentIntent(pendingIntent);
        NotificationManager nm = (NotificationManager)context.getApplicationContext().getSystemService(context.getApplicationContext().NOTIFICATION_SERVICE);
        nm.notify(1,notification.build());

您可以手动“关闭”通知

nm.cancel(1);

【讨论】:

    猜你喜欢
    • 2020-12-31
    • 1970-01-01
    • 1970-01-01
    • 2011-03-07
    • 1970-01-01
    • 1970-01-01
    • 2012-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多