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