Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
701 views
in Technique[技术] by (71.8m points)

android - Which function is called when application is removed from task manager

I need to make status of user offline. When I press home button onStop() is called, that's fine. When I press back button onDestroy() is invoked. But when I close the app from recent apps by swiping it, onStop() or onDestroy() isn't called.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  1. Make a service :

    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. Make a custom class :

    public class DefaultBinder extends Binder {
        MyService s;
    
        public DefaultBinder( MyService s) {
            this.s = s;
        }
    
        public MyService getService() {
            return s;
        }
    }
    
  3. Add to your 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) {}
        }
    }
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...