Android判断当前App应用处于前台(可见)或后台(不可见)
package zhangphil.test;
import android.app.ActivityManager;;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class JavaActivity extends AppCompatActivity {
private ActivityManager activityManager;
private String packageName;
private boolean stop = false;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.drawable_activity);
activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
packageName = this.getPackageName();
new Thread(new AppStatus()).start();
}
private class AppStatus implements Runnable {
@Override
public void run() {
stop = false;
while (!stop) {
try {
if (appOnForeground()) {
System.out.println("当前App处于前台");
} else {
System.out.println("当前App处于后台");
}
} catch (Exception e) {
e.printStackTrace();
}
try {
TimeUnit.SECONDS.sleep(1);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
private boolean appOnForeground() {
List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
if (appProcesses == null)
return false;
for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.processName.equals(packageName) && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
return true;
}
}
return false;
}
}
以上这个方案是全局性的判断当前App是否处于前台可见,抑或后台不可见。
需要明白的一点儿是,在大型Android项目中,存在很多Activity时候,仅靠让全部Activity继承自一个类似Base的Activity,然后在Base的Activity生命周期中做相应逻辑处理,进而判断当前App是否处于前台后台的方法是不可取行不通的。