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

时间:2016-03-01 17:39:29

标签: android android-activity android-lifecycle

我需要让用户离线状态。当我按下主页按钮onStop()时,这很好。当我按下后退按钮onDestroy()被调用。但是,当我通过滑动关闭最新应用中的应用时,不会调用onStop()onDestroy()

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

3 个答案:

答案 0 :(得分:3)

  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. 制作自定义课程:

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

    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) {}
        }
    }
    

答案 1 :(得分:1)

  

但是,当我通过滑动来关闭最近的应用程序中的应用程序时,不会调用onStop()或onDestroy()。

Activity不再可见时要调用的Activity lifecycle方法在从最近的任务中删除时不能保证被调用(将其视为“软”版本的查杀由于内存不足而导致的系统应用程序

  

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

我建议使用以下方法之一:

  • ,如果适用)使用Activity的{​​{1}} / onResume() “让用户在线/离线”; < / LI>
  • Service sticks用于应用程序,这意味着如果应用程序在onPause()的{​​{1}}返回后被终止,则会重新创建该服务并{ {1}}将再次被调用。此时,您可以“让用户离线”。生命周期方法调用链将是:

    1. Service的{​​{1}} - &gt; onStartCommand() * - &gt;
    2. onStartCommand()的{​​{1}} * - &gt;
    3. Activity的{​​{1}} - &gt; onStop()的{​​{1}} - &gt;
    4. onDestroy()的{​​{1}}

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

  • onTaskRemoved()!= null,表示已从正在运行的Application实例收到请求
  • onCreate() = null,表示请求已由(新创建的)Service实例发送

*不保证被称为

答案 2 :(得分:0)

不,没有干净的方法来获得应用程序终止时间。但是我可以建议你使用服务在每n分钟后更新你的应用程序(离线功能)的肮脏技巧。

当操作系统终止您的应用程序时,它将删除所有相关服务和广播接收器。

相关问题