2012-01-13 76 views
5

我希望它存在。Android等價於applicationDidBecomeActive和applicationWillResignActive(來自iOS)

我想存儲應用程序失去焦點的時間,然後檢查它是否失去了焦點超過n分鐘才能調出鎖定。

看到一個應用程序如何組成活動,我認爲不會有直接的等價物。我將如何能夠實現類似的結果?

編輯
我試圖將應用程序類擴展到registerActivityLifecycleCallbacks()和意識到我將不能使用這種方法,因爲它只有在API級別提供14+

回答

4

請允許我分享我是如何製作向後兼容的解決方案的。

如果存在與帳戶關聯的密碼,我已經在啓動時實施了我的應用鎖定。爲了完整,我需要處理其他應用程序(包括家庭活動)接管n分鐘的情況。

我最終創造了一個我所有活動擴展的BaseActivity。

// DataOperations is a singleton class I have been using for other purposes. 
/* It is exists the entire run time of the app 
    and knows which activity was last displayed on screen. 
    This base class will set triggeredOnPause to true if the activity before 
    "pausing" because of actions triggered within my activity. Then when the 
    activity is paused and triggeredOnPause is false, I know the application 
    is losing focus. 

    There are situations where an activity will start a different application 
    with an intent. In these situations (very few of them) I went into those 
    activities and hard-coded these lines right before leaving my application 

    DataOperations datao = DataOperations.sharedDataOperations(); 
    datao.lostFocusDate = new Date(); 
*/ 

import java.util.Date; 

import android.app.Activity; 
import android.content.Intent; 
import android.util.Log; 

public class BaseActivity extends Activity { 
    public boolean triggeredOnPause; 

    @Override 
    public void onResume(){ 
     super.onResume(); 
     DataOperations datao = DataOperations.sharedDataOperations(); 
     if (datao.lostFocusDate != null) { 
      Date now = new Date(); 
      long now_ms = now.getTime(); 
      long lost_focus_ms = datao.lostFocusDate.getTime(); 
      int minutesPassed = (int) (now_ms-lost_focus_ms)/(60000); 
      if (minutesPassed >= 1) { 
       datao.displayLock(); 
      } 
        datao.lostFocusDate = null; 
     } 
     triggeredOnPause = false; 
    } 

    @Override 
    public void onPause(){ 
     if (triggeredOnPause == false){ 
      DataOperations datao = DataOperations.sharedDataOperations(); 
      datao.lostFocusDate = new Date(); 
     } 
     super.onPause(); 
    } 
    @Override 
    public void startActivity(Intent intent) 
    { 
     triggeredOnPause = true; 
     super.startActivity(intent); 
    } 
    @Override 
    public void startActivityForResult(Intent intent, int requestCode) { 
     triggeredOnPause = true; 
     super.startActivityForResult(intent, requestCode); 
    } 

} 

如果你要使用此解決方案,並有實現我的DataOperations類的等價問題,請發表評論,我可以張貼必要的代碼。

2

參考Application class在android系統。延長這堂課。

希望這可以幫到你

+0

謝謝,現在我有一個地方開始。 – 2012-01-13 06:44:00

相關問題