我有一个包含两个选项卡的 Activity 。单击两个选项卡将更改选项卡下方的 fragment 。当该 Activity 在前面时,我会发出通知,然后我将应用程序最小化并终止该 Activity (不是强制停止)。
我的问题是,当 Activity 被用户终止时,我没有在 onDestroy
中收到回调。现在,如果我单击通知,应用程序将强制关闭,那是因为未决 Intent 的 Activity 丢失了。为什么在 onDestroy 中没有收到回电?
最佳答案
我找到了解决方案:
创建服务:
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/