android - 避免取消从最近的应用程序列表中删除应用程序的通知

标签 android notifications android-service

我正在使用下面的代码 fragment 来显示来 self 的应用内服务的通知:

NotificationCompat.Builder mBuilder =
        new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle(currentNotificaion.getMessageTitle())
                .setContentIntent(contentIntent)
                .setContentText(currentNotificaion.getMessageText())
                .setAutoCancel(true);
int mNotificationId = (int) currentNotificaion.getMessageServerID();
// Gets an instance of the NotificationManager service
NotificationManager mNotifyMgr =
        (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Builds the notification and issues it.
mNotifyMgr.notify(mNotificationId, mBuilder.build());

我的服务在 list 中是这样声明的:

<service
android:name="com.myapp.services.NotificationService"
android:stopWithTask="false">
</service>

但是当从最近的应用程序列表中关闭我的应用程序时,通知会消失并从通知栏中删除。另一件事是我不会使用永远不会从通知栏中删除的棒通知。

我怎样才能避免这种情况?

最佳答案

在您的 list 文件中,将服务的 stopWithTask 标志保持为 true。喜欢:

<service
    android:name="com.myapp.MyService"
    android:stopWithTask="true" />

我刚刚解决了类似的问题。

如果只是在通过从最近的应用程序列表中滑动而终止应用程序时停止服务,您可以执行以下操作。

  1. 在您的 list 文件中,将 Service 的 stopWithTask 标记保持为 true。喜欢:

但是正如您所说,您想要注销监听器并停止通知等,我建议采用这种方法:

Inside your Manifest file, keep flag stopWithTask as false for Service. Like:

    <service
        android:name="com.myapp.MyService"
        android:stopWithTask="false" />
  1. 现在在您的 MyService 服务中,覆盖方法 onTaskRemoved。 (仅当 stopWithTask 设置为 false 时才会触发)。

    public void onTaskRemoved(Intent rootIntent) {
    
    //unregister listeners
    //do any other cleanup if required
    
    //stop service
        stopSelf();  
    }
    

希望对你有所帮助。

关于android - 避免取消从最近的应用程序列表中删除应用程序的通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40172693/

相关文章:

android - 如何以编程方式设置评分栏样式?

android - 更改通知上的操作按钮

android - 从最近的应用程序中刷出应用程序后服务代码未运行

android - 如何防止 Android 操作系统关闭内存后台应用程序?

android - 解决 AdMob 的 35 个字符 URL 限制?

java - Android:AdapterView 不支持 addView(View)

android - 无法运行安卓应用

ios - 随附的应用程序通知

winapi - 如何巧妙地通知用户他的输入已收到

android - 如何检查我的应用程序是否仍在 Android 服务中运行?