在Android中关闭应用程序时如何获得通知 [英] How to get notified when the application is closed in Android

查看:236
本文介绍了在Android中关闭应用程序时如何获得通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从最近的应用程序列表中删除我的应用程序时,我想显示一个Notification.

I want to show up a Notification when my app is removed from the recent apps list.

我曾尝试将代码放置在onStop()onDestroy()中,但均无效.关闭应用程序后,就会立即调用onStop()(尽管它仍在最近的应用程序列表中).

I've tried putting code for that in onStop() and onDestroy() but neither works . onStop() is called as soon as the app is closed (though it is still in the recent app list).

从最近的应用程序列表中删除应用程序时,谁能说出调用哪种方法?

Can anyone tell which method is called when app is removed from recent app list or any way in which this need can be accomplished ?

推荐答案

此答案已过时,由于

This answer is outdated and most likely will not work on devices with API level 26+ because of the background service limitations introduced in Oreo.

原始答案:

当您从最新记录"中滑动某个应用程序时,其任务会立即被杀死.没有生命周期方法将被调用.

When you swipe an app out of Recents, its task get killed instantly. No lifecycle methods will be called.

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

To get notified when this happens, you could start a sticky Service and override its onTaskRemoved() method.

来自文档onTaskRemoved()中的>:

From the documentation of 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()中):

And starting it (e.g. in onCreate()):

Intent stickyService = new Intent(this, StickyService.class);
startService(stickyService);

这篇关于在Android中关闭应用程序时如何获得通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆