Android determines whether the program is active or running on the mobile phone.
Shenyang binzi encountered such a problem in today's project requirements. In Service, it is necessary to determine whether the current program is active, in other words, services running in the background need to check whether the current program is a program of the service, so that you can jump to different pages for different operations when clicking push notifications. The following is the method I encapsulated to share with you.
/***** @ Description: whether the program with the package name is running * @ Method_Name: isRunningApp * @ param context * @ param packageName determine the package name of the program * @ return required permissions *
* @ Return: boolean * @ Creation Date: 1:14:15 * @ version: v1.00 * @ Author: JiaBin * @ Update Date: * @ Update Author: jiaBin */public static boolean isRunningApp (Context context, String packageName) {boolean isAppRunning = false; ActivityManager am = (ActivityManager) context. getSystemService (Context. ACTIVITY_SERVICE); List
List = am. getRunningTasks (100); for (RunningTaskInfo info: list) {if (info. topActivity. getPackageName (). equals (packageName) & info. baseActivity. getPackageName (). equals (packageName) {isAppRunning = true; // find it, breakbreak;} return isAppRunning ;}
First, you must add the permission in the comment to make a judgment. Otherwise, the program will throw an exception. The general idea is to get the Activity manager and get the 100 programs that are currently running through the manager, and then loop through the result set, obtain the package name and the top-level package name of each program's basic page in the iteration process. Use this package name and we need to determine the incoming package name parameters for comparison, if it is found, the program is considered to be running. If it is not found, it indicates that the program is not running. My existing programs are implemented in this way. If you have any vulnerabilities, please criticize and correct them. Shenyang binzi original.