android - onDestroy() 在 Activity 被用户杀死时没有被调用?

标签 android callback notifications ondestroy

我有一个包含两个选项卡的 Activity 。单击两个选项卡将更改选项卡下方的 fragment 。当该 Activity 在前面时,我会发出通知,然后我将应用程序最小化并终止该 Activity (不是强制停止)。

我的问题是,当 Activity 被用户终止时,我没有在 onDestroy 中收到回调。现在,如果我单击通知,应用程序将强制关闭,那是因为未决 Intent 的 Activity 丢失了。为什么在 onDestroy 中没有收到回电?

最佳答案

我找到了解决方案:

  1. 创建服务:

    public class MyService extends Service {
    
        @Override
        public final int onStartCommand(Intent intent, int flags, int startId) {
            return START_STICKY;
        }
    
        @Override
        public final IBinder onBind(Intent intent) {
            return null;
        }
    
        @Override
        public void onTaskRemoved(Intent rootIntent) {
            Toast.makeText(getApplicationContext(), "APP KILLED", Toast.LENGTH_LONG).show(); // here your app is killed by user
    
            try {
                stopService(new Intent(this, this.getClass()));
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                super.onTaskRemoved(rootIntent);
            } else{}
        }
    }
    

然后在应用启动时启动您的服务:

startService(new Intent(this, MyService.class));

确保在 AndroidManifest.xml 中注册服务

<service
            android:enabled="true"
            android:name="yourPackageName.MyService"
            android:stopWithTask="false" />

关于android - onDestroy() 在 Activity 被用户杀死时没有被调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20943636/

相关文章:

android - 如何读取 firebase 中的纬度和经度以在 google maps android 中显示

c++ - Gstreamer appsrc : odd behaviour of need-data callback

javascript - 用于管理多个异步 JavaScript 操作的设计模式

来自命令提示符的 Windows 8 通知服务通知

Android:在 linux 应用程序和 Android 应用程序之间共享一个公共(public)文件夹

android - 如何为多个屏幕分辨率定义可绘制文件夹名称(Nexus 10 和 Galaxy Tab 10 之间的冲突)?

javascript - Node.js 从回调函数中提取值

php - 无法上传文件 - php & mysql

notifications - 当有人在 Yammer 中的帖子中标记我时,如何收到通知?

java - 如何找到多个点的中心?安卓