Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 views
in Technique[技术] by (71.8m points)

android - How to get any identifier of the topmost activity?

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 stop when Activity A is no longer visible: user pressed "Back", "Home" or did anything else that makes Activity A invisible. This Activity A must not be aware of the service -- i.e. it must not have to explicitly inform the Service that it is going away.

In the nutshell, is there a way to:

  • Get any kind of identification (object reference, class name, ID, etc.) of the topmost Activity,
  • Receive notification when topmost Activity changes?

P.S. This may sound like malware behavior, but it is not! It is legitimate use-case!

Edit: Activities are not in my application. They can be just about anything -- browser, maps app, settings, etc.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...