Android: How can I get the current foreground activity (from a service)?

前端 未结 12 1941
北恋
北恋 2020-11-22 07:53

Is there a native android way to get a reference to the currently running Activity from a service?

I have a service running on the background, and I would like to up

12条回答
  •  轮回少年
    2020-11-22 08:31

    I could not find a solution that our team would be happy with so we rolled our own. We use ActivityLifecycleCallbacks to keep track of current activity and then expose it through a service:

    public interface ContextProvider {
        Context getActivityContext();
    }
    
    public class MyApplication extends Application implements ContextProvider {
        private Activity currentActivity;
    
        @Override
        public Context getActivityContext() {
             return currentActivity;
        }
    
        @Override
        public void onCreate() {
            super.onCreate();
    
            registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
                @Override
                public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                    MyApplication.this.currentActivity = activity;
                }
    
                @Override
                public void onActivityStarted(Activity activity) {
                    MyApplication.this.currentActivity = activity;
                }
    
                @Override
                public void onActivityResumed(Activity activity) {
                    MyApplication.this.currentActivity = activity;
                }
    
                @Override
                public void onActivityPaused(Activity activity) {
                    MyApplication.this.currentActivity = null;
                }
    
                @Override
                public void onActivityStopped(Activity activity) {
                    // don't clear current activity because activity may get stopped after
                    // the new activity is resumed
                }
    
                @Override
                public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
    
                }
    
                @Override
                public void onActivityDestroyed(Activity activity) {
                    // don't clear current activity because activity may get destroyed after
                    // the new activity is resumed
                }
            });
        }
    }
    

    Then configure your DI container to return instance of MyApplication for ContextProvider, e.g.

    public class ApplicationModule extends AbstractModule {    
        @Provides
        ContextProvider provideMainActivity() {
            return MyApplication.getCurrent();
        }
    }
    

    (Note that implementation of getCurrent() is omitted from the code above. It's just a static variable that's set from the application constructor)

提交回复
热议问题