我对以下代码段有疑问。
MainActivity.Java
public class MainActivity extends AppCompatActivity implements LifecycleOwner,LifeCycleComponant {
private static final String TAG =MainActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getLifecycle().addObserver(new MyObserver());
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
getState();
}
@Override
public void getState() {
Log.d(TAG, "getState: "+getLifecycle().getCurrentState());
}
}
MyObserver.Java
public class MyObserver implements LifecycleObserver {
private static String TAG=MainActivity.class.getSimpleName();
private LifeCycleComponant lifeCycleComponant;
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
public void myOnCreate(){
Log.d(TAG, "myOncreate: ");
lifeCycleComponant=new MainActivity();
lifeCycleComponant.getState();
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void myOnDestroy(){
Log.d(TAG, "myOnDestroy: ");
lifeCycleComponant.getState();
lifeCycleComponant=null;
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void myOnResume(){
Log.d(TAG, "myOnResume: ");
lifeCycleComponant.getState();
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void myOnPause(){
Log.d(TAG, "myOnPause: ");
lifeCycleComponant.getState();
}
}
每当我调用lifeCycleComponant.getState()时,它只返回INITIALIZED。 但是当我从MainActivit.onPause()方法调用它时,它给出了正确的答案。
答案 0 :(得分:1)
lifeCycleComponant=new MainActivity();
将创建一个新的Activity,它将处于初始化状态,并且不会链接到前台运行的Activity
。
您无需访问Observer中的当前状态,因为它将根据相应的Lifecycle.Event