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