gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 14:27:39 28 4
gpt4 key购买 nike

我有一个包含两个选项卡的 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/

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