Android to determine whether the current application is in the foreground or the background of two methods _android

Source: Internet
Author: User

1, through the Runningtaskinfo class judgment (need additional authority):

Copy Code code as follows:

/**
* Determine whether the current application is in the foreground or in the background
*/
public static Boolean Isapplicationbroughttobackground (final 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

Copy Code code as follows:

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

2, through the Runningappprocessinfo class judgment (does not require additional permissions):

Copy Code code as follows:

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;
}

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.