Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android listen for app launch

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?

like image 424
Ste Avatar asked Sep 29 '11 11:09

Ste


People also ask

What does launch application by main activity mean?

Typically, one activity in an app is specified as the main activity, which is the first screen to appear when the user launches the app. Each activity can then start another activity in order to perform different actions.

What happens when an Android app is launched?

An Android process is started whenever it is required. Any time a user or some other system component requests a component (could be a service, an activity or an intent receiver) that belongs to your application be executed, the Android system spins off a new process for your app if it's not already running.

What code is executed when an application launched?

In most cases, every Android application runs in its own Linux process. This process is created for the application when some of its code needs to be run, and will remain running until it is no longer needed and the system needs to reclaim its memory for use by other applications.


2 Answers

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.
like image 70
JerrySher Avatar answered Sep 30 '22 12:09

JerrySher


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.

like image 28
Guy Avatar answered Sep 30 '22 12:09

Guy