2012-01-13 73 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

相关问题