我需要使用戶脫機狀態。當我按主頁按鈕onStop()
被調用時,沒關係。當我按下後退按鈕onDestroy()
被調用。但是,當我通過刷新最近的應用程序關閉應用程序時,不會調用onStop()
或onDestroy()
。當應用程序從任務管理器中刪除時調用Whiсh函數
我需要知道應用程序何時從最近的應用程序關閉以執行某些操作(例如,使用戶脫機)。
我需要使用戶脫機狀態。當我按主頁按鈕onStop()
被調用時,沒關係。當我按下後退按鈕onDestroy()
被調用。但是,當我通過刷新最近的應用程序關閉應用程序時,不會調用onStop()
或onDestroy()
。當應用程序從任務管理器中刪除時調用Whiсh函數
我需要知道應用程序何時從最近的應用程序關閉以執行某些操作(例如,使用戶脫機)。
撥打服務:
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
lifecycle
方法,這些方法被調用時Activity
不再可見,不能保證從最近的任務取出時調用(把它當作由系統因殺死一個應用程序的「軟」版本低內存)。
我需要知道什麼時候該應用程序從最近關閉應用程序做一些事情(例如,讓用戶離線)
我建議下列之一:
Activity
的onResume()
/onPause()
至「使用戶在線/離線」;使用Service
是sticks到應用這意味着如果應用程序被殺害後Service
的onStartCommand()
回報,該服務將被重建和onStartCommand()
將會再次調用。在這一點上,你可以「使用戶離線」。的生命週期方法調用的鏈將是:
Activity
的onStop()
- >onDestroy()
* - >Service
的onTaskRemoved()
* - >Application
的onCreate()
- >Service
的onCreate()
- >Service
的onStartCommand()
的Intent
傳遞給方法會幫助你認識哪個組件觸發了啓動請求:
Intent
!= null,表示該請求已經從運行Activity
實例Intent
= null,表示該請求已經由(新創建)發送Application
實例接收*,但不保證稱爲
不,沒有乾淨的方式來獲取應用程序終止時間。但是我可能會建議你一個骯髒的竅門,使用一項服務在n分鐘後更新你的應用程序(離線功能)。
當操作系統殺死您的應用程序時,它將刪除所有關聯的服務並將其與廣播接收器一起刪除。
沒有@Onik,你甚至不能使用粘性服務,因爲這個服務將被Android操作系統 –
@Attiq ur Rehman殘酷地終止,並且之後服務將被重新創建。請參閱[START_STICKY](http://developer.android.com/reference/android/app/Service.html#START_STICKY)。 – Onik