gpt4 book ai didi

android - 如何在 Android 应用程序关闭时收到通知

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:01:09 25 4
gpt4 key购买 nike

当我的应用程序从最近使用的应用程序列表中删除时,我想显示一个通知

我已经尝试将相关代码放入 onStop()onDestroy() 中,但都不起作用。 onStop() 在应用关闭时立即调用(尽管它仍在最近的应用列表中)。

任何人都可以告诉当应用程序从最近的应用程序列表中删除时调用哪个方法或可以实现此需求的任何方式吗?

最佳答案

由于 background service limitations,此答案已过时并且很可能不适用于 API 级别 26+ 的设备在 Oreo 中引入。

原始答案:

当您将某个应用从“最近”中滑出时,它的任务会立即被终止。不会调用任何生命周期方法。

要在发生这种情况时得到通知,您可以启动一个粘性 Service 并覆盖其 onTaskRemoved() 方法。

来自documentation onTaskRemoved() 的:

This is called if the service is currently running and the user has removed a task that comes from the service's application.

例如:

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);

关于android - 如何在 Android 应用程序关闭时收到通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38281590/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com