Android to determine whether app foreground is running or running in the background (running state) _android

Source: Internet
Author: User

In this paper, we introduce the content of Android to Judge app state by the way of illustration, as follows:

To understand this piece, first of all need to understand some concepts, app,process,task

1.process is the process, the concept of Linux.

2. A generic app has a UID, runs in a process, and if the app has a different UID defined for the service, the service runs in another process, meaning the UID is the same as the process ID, and a UID represents a process Or you can define a UID for a few apps, and they're running in a process.

3.task is an activity stack of the Android system that contains the activity of multiple apps, and can be used to activitymanager the activity information in the stack to determine the state of the activity's corresponding application.

3.1 Things that can be done include:

Activitymanagermactivitymanager = (Activitymanager) context.getsystemservice (context.activity_service);
Packagemanagermpackagemanager = Context.getpackagemanager ();

①getrecenttasks () Gets the recently opened task, which can be implemented using the mobile phone to view recently opened applications.

②getrunningappprocess () Gets the process in the app run.

List List = Mactivitymanager.getrunningappprocesses ();
StringBuilder apps = new StringBuilder ();
for (Runningappprocessinfo info:list) {
apps.append (info.processname + "\ n" + info.importance);
System.out.println (Apps.tostring ());

The list is a collection of processes currently running on the system, and the importance attribute ==100 indicates that the process is in the foreground and that other numbers are in the background, so the importance and processname determine if the application is in the foreground

When I did the test, the method returned only the process of this application in the list, the foreground is the state is 100, the background state is 400,

This is because my mobile phone is more than 5.0, starting from api21 This method can only return the application of the process information, if the application has service and defined process attributes, then return two processes, the app process is still 100,service is another value. 5.0 below can return all, another method 5.0 above can return all, 5.0 below is not OK, say later.

* In addition: when the service of an app is set to be sticky, the app for the service is considered to be in the foreground, the app process is importance 100, and this is not the way to judge if it's in the foreground.

Summary: More than 5.0 can only determine whether their application is in the foreground, when the service is set to the app is sticky, it can not be used.

If (importance = 100) A constant of 100 under Runningprocessinfo importance_foreground

So here's to write if (info.importance = = Runningprocessinfo.importance_foreground)

③getrunningservices () Gets the background service in the running of the system.

④getrunningtask () Gets the tasks in the system running.

It says the activity task stack, the top of the stack activity app is the foreground of the app, all get the top of the stack activity information to get his package name, compare the application of the package name to judge the application is not in the foreground, 5.0 before can determine which application in the foreground, 5.0 will only return itself and some unimportant task, can no longer judge whether other applications are in the foreground, can only judge themselves.

Activitymanager am = (activitymanager) context
. Getsystemservice (context.activity_service);
List tasks = am.getrunningtasks (1);
if (!tasks.isempty ()) {
ComponentName topactivity = tasks.get (0). topactivity;
if (Topactivity.getpackagename (). Equals (Context.getpackagename ())) {



All the activity that has been done before is integrated baseactivity, rewrite OnCreate method, OnStop method, define a variable count statistics open activity number, oncreate when Count++,onstop count-- , when count = = 0 o'clock, the application is in the background. Now, starting with API14, the API provides a callback for all activity lifecycle, which is activitylifecyclecallbacks, which triggers the lifecycle of each activity, Register this callback by Registeractivitylifecyclecallbacks.

In fact, as with rewriting Baseactivity's OnCreate and OnStop, count++,onstop in the OnCreate of the callback, add a judgment in count--, if (count = 0) {"I'm Backstage"}, Why is it in the OnStop? Whether it's back return or home exit, or other means to exit, the activity will always callback onstop.

can also be called directly in the OnStop getrunningappprocess or getrunningtask to determine whether the application is running backstage, this time can do some things. Then back to the front desk to call OnCreate, and can do something.

I have done this is to detect a new version of the update every time the application runs to the foreground. Registers this callback in the OnCreate of the custom application.

5.UsageStatsManager, this is the above said to be effective after 5.0. Use to add permissions

<uses-permission android:name= "Android.permission.PACKAGE_USAGE_STATS" tools:ignore= "Protectedpermissions" xmlns:tools= "Http://" ></uses-permission>

Mobile-settings-security-advanced, in the right to view the use of applications, select their own application.

6. With the barrier-free features of Android,

7. Read process progress information from Linux kernel protection in the/proc directory, GitHub address

You do not need permissions to determine whether any application is in the foreground, but retrieving the folder takes time.


Get a series of running app processes

List processes = processmanager.getrunningappprocesses ();</androidappprocess>

Get detailed information about any running app process

Androidappprocess process = processes.get (location);
String processname =;
Stat Stat = Process.stat ();
int pid = Stat.getpid ();
int parentprocessid = Stat.ppid ();
Long starttime = Stat.stime ();
int policy = Stat.policy ();
char state = Stat.state ();
Statm STATM = Process.statm ();
Long totalsizeofprocess = Statm.getsize ();
Long residentsetsize = Statm.getresidentsetsize ();
PackageInfo PackageInfo = process.getpackageinfo (context, 0);
String appName = PackageInfo.applicationInfo.loadLabel (PM). toString ();

Judge whether at the front desk

if (Processmanager.ismyprocessintheforeground ()) {
//do stuff

Get detailed information on a series of running app processes

List processes = Processmanager.getrunningappprocessinfo (CTX);</activitymanager.runningappprocessinfo>

The above content is for Android to Judge app State, hope to be helpful to everybody!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.