Search code examples
androidandroid-activityandroid-contextback-stack

How to get reference of currently visible activity without passing it as parameter to other class


As the title says, I want to get the reference of currently visible activity or you can say activity which is at the top of backstack from a class, I don't want to send activity reference to that class, because I am using that class from many activities and if I do, I have to pass activity reference from every activity which is a long process.

I already have seen many answers which are typecasting context reference to activity but it is not working.

If anyone has the idea of how to do that in a short way, then please share.


Solution

  • I have found a way via we can do this, In your application class add: registerActivityLifecycleCallbacks(this will listen to all activity lifecycle methods), like this:

    public class MyApplication extends Application {
    
        public static Activity currentActivity=null;
    
        @Override
        public void onCreate() {
            super.onCreate();
    
            registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
                @Override
                public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle bundle) {
    
                }
    
                @Override
                public void onActivityStarted(@NonNull Activity activity) {
                    currentActivity=activity;
                }
    
                @Override
                public void onActivityResumed(@NonNull Activity activity) {
    
                }
    
                @Override
                public void onActivityPaused(@NonNull Activity activity) {
    
                }
    
                @Override
                public void onActivityStopped(@NonNull Activity activity) {
    
                }
    
                @Override
                public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle bundle) {
    
                }
    
                @Override
                public void onActivityDestroyed(@NonNull Activity activity) {
    
                }
            });
        }
    }
    

    And then use it like:

     if (MyApplication.currentActivity!=null){
                 // your code here
            }
    

    Don't forget to add your application class to manifest:

     <application
            android:name=".MyApplication"
            .../>