从最近的应用列表中删除应用时,请避免取消通知

VSB*_*VSB 10 notifications android android-service

我正在使用以下代码段显示来自我的应用内的服务的通知:

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());
Run Code Online (Sandbox Code Playgroud)

我的服务在清单中声明如下:

<service
android:name="com.myapp.services.NotificationService"
android:stopWithTask="false">
</service>
Run Code Online (Sandbox Code Playgroud)

但是,当从最近的应用列表关闭我的应用时,通知将消失并从通知栏中删除.另一件事是我不会使用从通知栏中删除的粘贴通知.

我怎么能避免这个?

Jam*_*mim 5

在Manifest文件中,将service stopWithTask标记为true.喜欢:

<service
    android:name="com.myapp.MyService"
    android:stopWithTask="true" />
Run Code Online (Sandbox Code Playgroud)

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

如果通过从"最近的应用程序列表"轻扫应用程序而终止服务时,您可以执行此操作.

  1. 在Manifest文件中,将service stopWithTask标记为true.喜欢:

但正如你所说,你想取消注册听众并停止通知等,我会建议这种方法:

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

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

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

希望它会对你有所帮助.


Raf*_*fal -1

 .setAutoCancel(true);
Run Code Online (Sandbox Code Playgroud)

我们将其设置为 false,这样通知就不会被取消或删除。你也可以把

.setOngoing(true)
Run Code Online (Sandbox Code Playgroud)

更新: 如果上述不起作用并且当从服务发送通知时,您需要致电

 startForeground(int, Notification) 
Run Code Online (Sandbox Code Playgroud)

为了在应用程序被终止时不终止服务。

来自 Android 文档:

已启动的服务可以使用 startForeground(int, Notification) API 将服务置于前台状态,系统认为该服务是用户主动感知的内容,因此在内存不足时不会被终止。

更多内容可以在这里找到: Android Service startForeground

  • 好的。你如何开始你的服务?也许 startForeground 会有所帮助。 (2认同)