从任务管理器中删除应用程序时调用哪个函数

Which function is called when application is removed from task manager

我需要将用户状态设为离线。当我按下主页按钮时 onStop() 被调用,没关系。当我按下后退按钮时 onDestroy() 被调用。但是,当我通过滑动从最近的应用程序中关闭该应用程序时,不会调用 onStop()onDestroy()

我需要知道应用程序何时从最近的应用程序中关闭以执行某些操作(例如让用户离线)。

But when I close the app from recent apps by swiping it, onStop() or onDestroy() isn't called.

Activity不再可见时要调用的Activity lifecycle方法不保证在从最近的任务中删除时调用(将其视为"soft"内存不足导致系统杀掉应用的版本).

I need to know when the app is closed from recent apps to do something (e.g make user offline)

我建议以下之一:

  • (如果适用)使用ActivityonResume()/onPause()"make user online/offline";
  • 对应用程序使用 Service that sticks 意味着如果应用程序在 ServiceonStartCommand() returns 之后被终止,将重新创建服务onStartCommand() 将再次被调用。此时你可以"make user offline"。生命周期方法调用链将是:

    1. ActivityonStop() -> onDestroy()* ->
    2. ServiceonTaskRemoved()* ->
    3. ApplicationonCreate() -> ServiceonCreate() ->
    4. ServiceonStartCommand()

传递给方法的 Intent 将帮助您识别哪个组件触发了启动请求:

  • Intent != null,表示已从 运行 Activity 实例
  • 收到请求
  • Intent = null,表示请求已由(新创建的)Application实例发送

* 不保证一定会被调用

不,没有干净的方法来获取应用程序终止时间。但我可以建议你一个卑鄙的把戏,即每隔 n 分钟使用一项服务更新你的应用程序(离线功能)。

当 OS 终止您的应用程序时,它将删除所有关联的服务和广播接收器。

  1. 制作服务:

    public class MyService extends Service {
    private DefaultBinder mBinder;
    private AlarmManager  alarmManager ;
    private PendingIntent alarmIntent;
    
    private void setAlarmIntent(PendingIntent alarmIntent){
    this.alarmIntent=alarmIntent;
    }
    
    public void onCreate() {
    alarmManager (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    mBinder = new DefaultBinder(this);
    }
    
     @Override
     public IBinder onBind(Intent intent) {
      return mBinder;
     }
    
     public void onTaskRemoved (Intent rootIntent){
     alarmManager.cancel(alarmIntent);
     this.stopSelf();
    }
    }
    
  2. 自定义 class :

    public class DefaultBinder extends Binder {
        MyService s;
    
        public DefaultBinder( MyService s) {
            this.s = s;
        }
    
        public MyService getService() {
            return s;
        }
    }
    
  3. 添加到您的 activity :

    MyService service;
    protected ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder binder) {
    service = ((DefaultBinder) binder).getService();
    service.setAlarmIntent(pIntent);
        }
    
        public void onServiceDisconnected(ComponentName className) {
            service = null;
        }
            };
    
    protected void onResume() {
        super.onResume();
        bindService(new Intent(this, MainService.class), mConnection,
                Context.BIND_AUTO_CREATE);
    }
    
    @Override
    protected void onStop() {
        super.onStop();
    
        if (mConnection != null) {
            try {
                unbindService(mConnection);
            } catch (Exception e) {}
        }
    }