您的位置:首页 > 其它

判断应用是否在后台或者正在运行

2016-09-07 15:55 330 查看
/**
* whether application is in background
* <ul>
* <li>need use permission android.permission.GET_TASKS in Manifest.xml</li>
* </ul>
*
* @param context 上下文
* @return if application is in background return true, otherwise return
* false
*/
public static boolean isApplicationInBackground(Context context) {
ActivityManager am = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> taskList = am.getRunningTasks(1);
if (taskList != null && !taskList.isEmpty()) {
ComponentName topActivity = taskList.get(0).topActivity;
if (topActivity != null
&& !topActivity.getPackageName().equals(
context.getPackageName())) {
return true;
}
}
return false;
}

/**
* whether application is Running
* <ul>
* <li>need use permission android.permission.GET_TASKS in Manifest.xml</li>
* </ul>
*
* @param context 上下文
* @return if application is running return true, otherwise return
* false
*/
public static boolean isApplicationRunning(Context context) {
ActivityManager am = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> taskList = am.getRunningTasks(1);
if (taskList != null && !taskList.isEmpty()) {
ComponentName topActivity = taskList.get(0).topActivity;
if (topActivity != null
&& !topActivity.getPackageName().equals(
context.getPackageName())) {
return false;
}
}
return true;
}

/**
* 打开应用
* @param context
* @param packageName
*/
public static void openApp(Context context, String packageName) {
try {
PackageManager pm =  context.getPackageManager();
PackageInfo pi = pm.getPackageInfo(packageName, 0);
Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
resolveIntent.setPackage(pi.packageName);
List<ResolveInfo> apps = pm.queryIntentActivities(resolveIntent, 0);
ResolveInfo ri = apps.iterator().next();
if (ri != null ) {
String packagename = ri.activityInfo.packageName;
String className = ri.activityInfo.name;
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK );//Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
ComponentName cn = new ComponentName(packagename, className);
intent.setComponent(cn);
context.startActivity(intent);
}
} catch (NameNotFoundException e) {
e.printStackTrace();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  应用