Android how to know an app has been started and ra

2019-01-15 16:43发布

问题:

In Android, how does one know an app has been started. I want to detect all apps installed when it starts, and range apps' priority according to its using times. Is there a solution to suggest to do this?

I know using broadcast, but is there some Intent send out from ActivityManager when app had been started, and how to detect this Intent in code? Any other solution is welcome, too.

回答1:

First part:

If you know the package name of your app, try this (put this following snippet in the onCreate method of your app):

 ActivityManager am= (ActivityManager) this.getSystemService(ACTIVITY_SERVICE); 

Then,

 boolean exit = false;
 while(!exit)
 { 
      List<RunningTaskInfo> taskInfo = am.getRunningTasks(1);
      ComponentName componentInfo = taskInfo.get(0).topActivity;
     if(componentInfo.getPackageName().equals("Your package name"))
     {
      //Do your work here
      exit = true;
     }
 }

When you start your app, this will be put into componentInfo. The taskInfo.get(0).topActivity will return the activity in the foreground. Hence you can know that your app has been started by comparing package using the second code snippet.

Note:Put this second code snippet in an Asynctask so that the checking of whether the app has started can be done in the background.

Second part:

To get the priorities, I think you can do it by checking the list TaskInfo which will contain all the running apps.