This example for you to share the Android to determine the current app state of the specific implementation code for your reference, the specific contents are as follows
First type:
/**
* To determine whether the current application is in the foreground or background
* * @param context * @return/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;
}
The above code requires a permission:
< uses-permission android:name= "Android.permission.GET_TASKS"/>
The second type:
The following code is my latest discovery, without permission, to be duly completed:
However, I did a little adjustment, backstage is divided into: service backstage and activity backstage, this is not considered the front desk are considered backstage.
service running in the background, appprocess.importance = Importance_service,
• No service running backstage,
public static Boolean IsBackground (context context) {
Activitymanager Activitymanager = (Activitymanager) Context.getsystemservice (context.activity_service);
list<activitymanager.runningappprocessinfo> appprocesses = activitymanager.getrunningappprocesses ();
for (Activitymanager.runningappprocessinfo appprocess:appprocesses) {
if (appProcess.processName.equals) ( Context.getpackagename ()) {
if (appprocess.importance = = ActivityManager.RunningAppProcessInfo.IMPORTANCE_ foreground) {
System.out.print (String.Format ("Foreground App:", Appprocess.processname));
return false;
} else{
System.out.print ("Background App:" +appprocess.processname);
return true;
}
}
return false;
}
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.