在Android中关闭应用程序时如何获得通知

编程入门 行业动态 更新时间:2024-10-26 00:18:32
本文介绍了在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.

来自文档:

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中关闭应用程序时如何获得通知

本文发布于:2023-11-27 03:26:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1636377.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何获得   应用程序   通知   Android

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!