如何在Android中检查活动生命周期状态

时间:2018-04-02 22:47:53

标签: android android-lifecycle

我想根据我的生命周期状态来处理我的数据。

例如,我想在应用程序恢复时执行某些操作。 我怎样才能找到我的应用程序现在的状态? 谢谢你的帮助。

3 个答案:

答案 0 :(得分:1)

正在活动:if (getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) ...,我认为。如果您要询问异步任务。

答案 1 :(得分:0)

对于自定义类,您可以使用体系结构组件的生命周期,首先添加库

annotationProcessor "android.arch.lifecycle:compiler:1.1.1"

然后是您的自定义类,例如

public class MyObserver implements LifecycleObserver {
    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    public void connectListener() {
        ...
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    public void disconnectListener() {
        ...
    }
}

最后来自你的生命周期容器(活动/片段)

myActivity.getLifecycle().addObserver(new MyObserver());

此处有更多信息https://developer.android.com/topic/libraries/architecture/lifecycle.html

答案 2 :(得分:0)

有预定义的Activity方法。 请查看Android中活动的生命周期。

示例代码

public class LifeCycleActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main); 
        Toast.makeText(LifeCycleActivity.this,"ON CREATE", Toast.LENGTH_SHORT).show(); 
    } 
    @Override
    protected void onStart() {
       // TODO Auto-generated method stub
       super.onStart(); 
        Toast.makeText(LifeCycleActivity.this,"ON START", Toast.LENGTH_SHORT).show();
    } 
    @Override
    protected void onResume() {
       // TODO Auto-generated method stub
       super.onResume(); 
        Toast.makeText(LifeCycleActivity.this,"ON RESUME", Toast.LENGTH_SHORT).show(); 
    } 
    @Override
    protected void onPause() {
       // TODO Auto-generated method stub
       super.onPause(); 
        Toast.makeText(LifeCycleActivity.this,"ON PAUSE", Toast.LENGTH_SHORT).show(); 
    } 
    @Override
    protected void onRestart() {
       // TODO Auto-generated method stub
       super.onRestart(); 
        Toast.makeText(LifeCycleActivity.this,"ON RESTART", Toast.LENGTH_SHORT).show(); 
    } 
    @Override
    protected void onStop() {
       // TODO Auto-generated method stub
       super.onStop(); 
        Toast.makeText(LifeCycleActivity.this,"ON STOP", Toast.LENGTH_SHORT).show(); 
    } 
    @Override
    protected void onDestroy() {
       // TODO Auto-generated method stub
       super.onDestroy(); 
        Toast.makeText(LifeCycleActivity.this,"ON DESTROY", Toast.LENGTH_SHORT).show();
    } 
}  

另请阅读: - https://developer.android.com/guide/components/activities/activity-lifecycle.html