1. 程式人生 > >判斷應用是否在後臺或者正在執行

判斷應用是否在後臺或者正在執行

 /**
     * 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(); } }