【发布时间】:2016-03-01 17:39:29
【问题描述】:
我需要使用户处于离线状态。当我按下主页按钮 onStop() 时,这很好。当我按下返回按钮时,onDestroy() 被调用。但是当我通过滑动从最近的应用中关闭应用时,onStop() 或 onDestroy() 不会被调用。
我需要知道应用何时从最近的应用中关闭以执行某些操作(例如,使用户离线)。
【问题讨论】:
标签: android android-activity android-lifecycle
我需要使用户处于离线状态。当我按下主页按钮 onStop() 时,这很好。当我按下返回按钮时,onDestroy() 被调用。但是当我通过滑动从最近的应用中关闭应用时,onStop() 或 onDestroy() 不会被调用。
我需要知道应用何时从最近的应用中关闭以执行某些操作(例如,使用户离线)。
【问题讨论】:
标签: android android-activity android-lifecycle
提供服务:
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();
}
}
制作一个自定义类:
public class DefaultBinder extends Binder {
MyService s;
public DefaultBinder( MyService s) {
this.s = s;
}
public MyService getService() {
return s;
}
}
添加到您的活动中:
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) {}
}
}
【讨论】:
但是当我通过滑动从最近的应用中关闭应用时,不会调用 onStop() 或 onDestroy()。
Activity 不再可见时调用的Activity lifecycle 方法不能保证在从最近的任务中删除时被调用(将其视为由系统由于内存不足)。
我需要知道应用何时从最近的应用中关闭以执行某项操作(例如让用户离线)
我建议以下之一:
Activity 的onResume()/onPause() 来“使用户在线/离线”;在应用程序中使用Service 即sticks 意味着如果应用程序在Service 的onStartCommand() 返回后被杀死,将重新创建服务并再次调用onStartCommand()。此时您可以“使用户离线”。生命周期方法调用链将是:
Activity's onStop() -> onDestroy()* ->Service的onTaskRemoved()* ->Application's onCreate() -> Service's onCreate() ->Service's onStartCommand()
传递给方法的Intent将帮助您识别哪个组件触发了启动请求:
Intent != null,表示已从正在运行的 Activity 实例收到请求Intent = null,表示请求已由(新创建的)Application 实例发送* 不保证会被调用
【讨论】:
不,没有干净的方法来获取应用程序终止时间。但我可以建议你一个肮脏的技巧,使用服务每隔 n 分钟更新一次应用程序(离线功能)。
当操作系统杀死你的应用程序时,它会删除所有相关的服务和广播接收器。
【讨论】: