Android判断当前应用程序处于前台还是后台的两种方法
1、通过runningtaskinfo类判断(需要额外权限):
/**
*判断当前应用程序处于前台还是后台
*/
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;
}
需要在androidmenitfest.xml文件中添加以下权限
<uses-permission android:name="android.permission.get_tasks" />
2、通过runningappprocessinfo类判断(不需要额外权限):
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("后台", appprocess.processname);
return true;
}else{
log.i("前台", appprocess.processname);
return false;
}
}
}
return false;
}
上一篇: 二个android模拟器互发短信程序演示
下一篇: 第11讲-Java泛型和文件操作