Determine if the app is in the background

Source: Internet
Author: User

1, through the Runningtaskinfo class judgment (requires additional permissions): (Test through 5.1 available, permission name modification

<uses-permission android:name= "Android.permission.REAL_GET_TASKS"/>


/**
* Determine if the current application is in the foreground or in the background
*/
public static Boolean Isapplicationbroughttobackground (final context context) {
Activitymanager am = (activitymanager) context.getsystemservice (Context.activity_service);
list<runningtaskinfo> tasks = am.getrunningtasks (1);
if (!tasks.isempty ()) {
ComponentName topactivity = tasks.get (0). topactivity;
if (!topactivity.getpackagename (). Equals (Context.getpackagename ())) {
return true;
}
}
return false;

}

You need to add the following permissions in the Androidmenitfest.xml file


<uses-permission android:name= "Android.permission.GET_TASKS"/>

2, through the Runningappprocessinfo class judgment (do not need additional permissions) (more than 5.1 system is not available):


public static Boolean IsBackground (context context) {

Activitymanager Activitymanager = (activitymanager) context.getsystemservice (Context.activity_service);
list<runningappprocessinfo> appprocesses = activitymanager.getrunningappprocesses ();
for (Runningappprocessinfo appprocess:appprocesses) {
if (AppProcess.processName.equals (Context.getpackagename ())) {
if (appprocess.importance = = Runningappprocessinfo.importance_background) {
LOG.I ("Backstage", appprocess.processname);
return true;
}else{
LOG.I ("front desk", appprocess.processname);
return false;
}
}
}
return false;
}

Determine if the app is in the background

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: info-contact@alibabacloud.com 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.