gpt4 book ai didi

java - getCurrentState() 仅返回 "INITIALIZED"

转载 作者:行者123 更新时间:2023-12-02 11:09:38 24 4
gpt4 key购买 nike

我对下面的代码 fragment 有疑问。

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() 方法调用它时,它给出了正确的答案。

最佳答案

lifeCycleComponant=new MainActivity();

将创建一个新的 Activity,该 Activity 将处于初始化状态,并且不会链接到在前台运行的 Activity

您不需要访问观察者中的当前状态,因为它将根据适当的 Lifecycle.Event 触发

关于java - getCurrentState() 仅返回 "INITIALIZED",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50692976/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com