如何在 android 中获取摘要 activity 的生命周期

how to get lifecycle of abstract activity in android

我有一个视频播放器应用程序,我需要从 Android 中的另一个 class 访问摘要 activity 的生命周期。在我的摘要 activity 中,我尝试使用 LifecycleRegistry,但这让我成为了生命周期所有者,而不是摘要 class 的实际生命周期。如何从另一个 class 访问抽象 activity 的生命周期?

这是我的摘要activity:

abstract public class MainActivity extends AppCompatActivity {

    private LifecycleRegistry lifecycleRegistry;
    VideoPlayer videoPlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        lifecycleRegistry = new LifecycleRegistry(this);
        lifecycleRegistry.setCurrentState(Lifecycle.State.CREATED);
        setContentView(R.layout.activity_main);
        videoPlayer = new VideoPlayer();
        playVideo();
    }

    public void playVideo(){
        videoPlayer.init();
        //calls function in VideoPlayer class
    }

    @Override
    protected void onResume() {
        super.onResume();
        lifecycleRegistry.setCurrentState(Lifecycle.State.RESUMED);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        lifecycleRegistry.setCurrentState(Lifecycle.State.DESTROYED);
    }
}

这是 class 我需要获取抽象 MainActivity 生命周期的地方:

public class VideoPlayer {
    public void init() {
        playVideo();
    }

    public void playVideo() {
        //async call happens here, I need getLifeCycle() from MainActivity
    }
}

不知道你未来的背景,但你可以做某事

public class VideoPlayer {

    private Lifecycle mLifecycle;
    
    public VideoPlayer(Lifecycle lifecycle) {
       mLifecycle = lifecycle;
    }

    public void init() {
        playVideo();
    }

    public void playVideo() {
        //you have mLifecycle now
    }
}

在Activity

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...
        videoPlayer = new VideoPlayer(getLifecycle());
    }