如何获得最上面的活动的任何标识符?标识符、如何获得

由网友(给我一个理由忘记)分享简介:我有一个服务,它的行为必须改变时,最上面的活动变化。再说,活动A有效,然后服务启动某种处理。这种处理必须停止活动时,一个不再可见:用户pressed返回,主页或做其他任何东西,使得活动一不可见的。这一活动的一定不知道的服务 - 即:不能有明确告知的服务,它会消失。I have a service and its be...

我有一个服务,它的行为必须改变时,最上面的活动变化。再说,活动A有效,然后服务启动某种处理。这种处理必须停止活动时,一个不再可见:用户pressed返回,主页或做其他任何东西,使得活动一不可见的。这一活动的一定不知道的服务 - 即:不能有明确告知的服务,它会消失。

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:

获取最顶端的活动的任何形式的标识(对象引用,类名称,标识等), 在收到通知时,最上面的活动变化?

P.S。这听起来像是恶意软件的行为,但它不是!它是合法的用例!

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

编辑:活动不是在我的应用程序。它们可以是任何东西 - 浏览器,地图应用程序,设置等

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

推荐答案

这上面部分已经过时。见底部的答案。

This top part is outdated. See bottom for answer.

我假设你指的是活动在自己的应用程序:

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

所有活动的呼叫 onResume()来到前台时和的onPause()离开前台时。只需重写此方法与你的功能(一定 super.onResume() super.onPause()分别打电话!)。

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!).

至于标识符,或许你可以让你的服务有一个静态方法,它被称为一个活动来到前台(在 onResume()),提供一个对自身的引用,它的类,一些任意ID等。

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.

参考:http://developer.android.com/reference/android/app/Activity.html

编辑:

您可以通过 ActivityManager访问前活动的身份 - >运行的任务 - > 组件名。一定要声明<使用-权限的Andr​​oid:名称=android.permission.GET_TASKS/> 在清单

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();

对于得到一个通知,你可能不得不只检查前活动每隔x毫秒。

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

阅读全文

相关推荐

最新文章