How to get any identifier of the topmost activity?

前端 未结 2 1234
春和景丽
春和景丽 2020-11-30 07:09

I have a service and its behavior must change when topmost Activity changes. Say, Activity A is active and then service starts some kind of processing. This processing must

相关标签:
2条回答
  • 2020-11-30 07:47

    Create a baseActivity and extends all other Activities from baseActivity, in onResume save Current Activity in a public static Filed in a Global class (in my case extends Application)

    public class baseActivity extends Activity {
        @Override
        protected void onResume() {
            super.onResume();
            Global.Activity = this;
        }
    }
    

    Other Activities

        public class mainActivity extends baseActivity {
            // You Can Use Global.Activity Everywhere ! , Even in a Object Extended Class
        }
    
    0 讨论(0)
  • 2020-11-30 07:48

    This top part is outdated. See bottom for answer.

    I'm assuming you're referring to Activities within your own application:

    All Activities call onResume() when coming to the foreground and onPause() when leaving the foreground. Simply override this method with your functionality (be sure to call super.onResume() and super.onPause() respectively!).

    As for the identifier, perhaps you could make your Service have a static method that is called by an Activity coming to the foreground (in onResume()), supplying a reference to itself, its class, some arbitrary ID, etc.

    Reference: http://developer.android.com/reference/android/app/Activity.html


    Edit:

    You can access the top Activity's identity via ActivityManager -> running tasks -> ComponentName. Be sure to declare <uses-permission android:name="android.permission.GET_TASKS" /> in your manifest.

    Context context = someArbitraryContext;
    ActivityManager am = (ActivityManager) context.
        getSystemService(Activity.ACTIVITY_SERVICE);
    String packageName = am.getRunningTasks(1).get(0).topActivity.getPackageName();
    String className = am.getRunningTasks(1).get(0).topActivity.getClassName();
    

    As for getting a notification, you'll probably have to just check the top Activity every x milliseconds.

    0 讨论(0)
提交回复
热议问题