android listen for app launch
Asked Answered
C

2

6

I need to develop a service which listen for every activity start. Must I do something like this?

ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> runningAppProcessInfo = am.getRunningAppProcesses();
for (int i = 0; i < runningAppProcessInfo.size(); i++) {
    Log.v("Proc: ", runningAppProcessInfo.get(i).processName);
}

And do I need to do it every X seconds? Does it affect battery consumption?

Castled answered 29/9, 2011 at 11:11 Comment(1)
Additional info: ActivityManager.getRunningTasks(1) will return the first task from the list of running tasks. This task seems to always be the one in the foreground.Nicolis
S
1

As far as I know there is currently no way to listen to an app's launch, Unless it is the first time that it is launching. ACTION_PACKAGE_FIRST_LAUNCH (Broadcast Action: Sent to the installer package of an application when that application is first launched (that is the first time it is moved out of the stopped state).

So I guess your solution is the best for this right now.

Selfcontained answered 28/11, 2011 at 9:26 Comment(0)
S
2

As far as I know there is a class IActivityController.Stub in android.app package. But this is an {@hide} interface (as someone said there have some method to access @hide api).

We can set a Listener to listen Activity switch like this:

mAm = ActivityManagerNative.getDefault();          
    try {
        mAm.setActivityController(new ActivityController());

   } catch (RemoteException e) {
        System.err.println("** Failed talking with activity manager!");}

and Class ActivityManagerNative is @hide also. ActivityController is a class extends IActivityController.Stub .

How to access @hide Api:

  1. you can get the android source code to build an have-@hide-api Android.jar to use.
  2. by reflection.
Soccer answered 30/5, 2013 at 10:0 Comment(1)
A note about this: on modern versions of Android, calling setActivityController requires the SET_ACTIVITY_WATCHER permission which requires that your application is signed with the key used to sign the Android framework, which isn't really possible if you're developing a third party application designed to run on all ROMs.Gemina
S
1

As far as I know there is currently no way to listen to an app's launch, Unless it is the first time that it is launching. ACTION_PACKAGE_FIRST_LAUNCH (Broadcast Action: Sent to the installer package of an application when that application is first launched (that is the first time it is moved out of the stopped state).

So I guess your solution is the best for this right now.

Selfcontained answered 28/11, 2011 at 9:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.