当我的应用程序从最近的应用列表中删除时,我想显示一个Notification
。
我尝试过在onStop()
和onDestroy()
中添加代码,但两者都不起作用。一旦应用程序关闭,onStop()
就会被调用(尽管它仍然在最近的应用程序列表中)。
当app从最近的app列表中删除时,有人能知道调用哪种方法吗?或者可以用什么方法来完成这一需求?
发布于 2016-07-09 04:09:24
这个答案已经过时了,而且由于奥利奥引入的 背景服务限制 ,很可能无法在API级别的设备上工作。
原来的答案:
当你把一个应用程序从最近的程序中删除时,它的任务马上就会被杀死。不会调用生命周期方法。
要在发生这种情况时得到通知,您可以启动一个粘性Service
并覆盖它的onTaskRemoved()
方法。
来自文档 of onTaskRemoved()
如果服务当前正在运行,并且用户已经删除了来自服务应用程序的任务,则调用该任务。
例如:
public class StickyService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onTaskRemoved(Intent rootIntent) {
Log.d(getClass().getName(), "App just got removed from Recents!");
}
}
在AndroidManifest.xml中注册
<service android:name=".StickyService" />
并启动它(例如在onCreate()
中):
Intent stickyService = new Intent(this, StickyService.class);
startService(stickyService);
https://stackoverflow.com/questions/38281590
复制