2016-03-01 50 views
1

我需要使用戶脫機狀態。當我按主頁按鈕onStop()被調用時,沒關係。當我按下後退按鈕onDestroy()被調用。但是,當我通過刷新最近的應用程序關閉應用程序時,不會調用onStop()onDestroy()當應用程序從任務管理器中刪除時調用Whiсh函數

我需要知道應用程序何時從最近的應用程序關閉以執行某些操作(例如,使用戶脫機)。

回答

1
  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

但是,當我通過刷新關閉最近的應用程序的應用程序時,onStop()或onDestroy()不會被調用。的Activity lifecycle

方法,這些方法被調用時Activity不再可見,不能保證從最近的任務取出時調用(把它當作由系統因殺死一個應用程序的「軟」版本低內存)。

我需要知道什麼時候該應用程序從最近關閉應用程序做一些事情(例如,讓用戶離線)

我建議下列之一:

  • 如果適用)使用ActivityonResume()/onPause()「使用戶在線/離線」;
  • 使用Servicesticks到應用這意味着如果應用程序被殺害後ServiceonStartCommand()回報,該服務將被重建和onStartCommand()將會再次調用。在這一點上,你可以「使用戶離線」。的生命週期方法調用的鏈將是:

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

Intent傳遞給方法會幫助你認識哪個組件觸發了啓動請求:

  • Intent!= null,表示該請求已經從運行Activity實例
  • Intent = null,表示該請求已經由(新創建)發送Application實例接收

*,但不保證稱爲

+0

沒有@Onik,你甚至不能使用粘性服務,因爲這個服務將被Android操作系統 –

+0

@Attiq ur Rehman殘酷地終止,並且之後服務將被重新創建。請參閱[START_STICKY](http://developer.android.com/reference/android/app/Service.html#START_STICKY)。 – Onik

0

不,沒有乾淨的方式來獲取應用程序終止時間。但是我可能會建議你一個骯髒的竅門,使用一項服務在n分鐘後更新你的應用程序(離線功能)。

當操作系統殺死您的應用程序時,它將刪除所有關聯的服務並將其與廣播接收器一起刪除。

相關問題