2015年5月26日 星期二

【Android】 取得正在執行的 app 專案名



A : Get Running Processes Lists 

 

        ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningAppProcessInfo = am.getRunningAppProcesses();

        for (int i = 0; i < runningAppProcessInfo.size(); i++) {

            Log.d("", "processName:" + runningAppProcessInfo.get(i).processName);

            if(runningAppProcessInfo.get(i).processName.equals("app.you.are.looking.for")) {

                // Do you stuff
            }
        }

 

 

B: Get Top Task ( Foreground Tasks)

 

 public static boolean isForeground(Context ctx, String myPackage){
    ActivityManager manager = (ActivityManager) ctx.getSystemService(ACTIVITY_SERVICE);
    List< ActivityManager.RunningTaskInfo > runningTaskInfo = manager.getRunningTasks(1);

    ComponentName componentInfo = runningTaskInfo.get(0).topActivity;
    if(componentInfo.getPackageName().equals(myPackage)) {
        return true;
    }     
    return false;
}

 

c. 權限 

<uses-permission android:name="android.permission.GET_TASKS"></uses-permission>

 

 

 

沒有留言:

張貼留言