javaandroidactivity-lifecycle

how to get lifecycle of abstract activity in android


I have a video player app where I need to access the lifecycle of an abstract activity from another class in Android. In my abstract activity, I've tried using LifecycleRegistry, but this is getting me the lifecycle owner not the actually lifecycle of the abstract class. How can I access the lifecycle of an abstract activity from another class?

Here is my abstract 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);
    }
}

Here is the class where I need to get the lifecycle of my abstract MainActivity:

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

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

Solution

  • Don't know a know about the context of you feature, but you You can do smth

    public class VideoPlayer {
    
        private Lifecycle mLifecycle;
        
        public VideoPlayer(Lifecycle lifecycle) {
           mLifecycle = lifecycle;
        }
    
        public void init() {
            playVideo();
        }
    
        public void playVideo() {
            //you have mLifecycle now
        }
    }
    

    In Activity

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