2015年1月16日 星期五

Get Other App Status in Android

1. Before API Level 21 (Lolipop , 5.0 )


ref:
http://stackoverflow.com/questions/22500959/detect-when-other-application-opened-or-launched

http://developer.android.com/reference/android/app/ActivityManager.html

getRunningAppProcesses()
Returns a list of application processes that are running on the device.

getRunningTasks(int maxNum)
This method was deprecated in API level 21. As of LOLLIPOP, this method is no longer available to third party applications: the introduction of document-centric recents means it can leak person information to the caller. For backwards compatibility, it will still retu rn a small subset of its data: at least the caller's own tasks, and possibly some other tasks such as home that are known to not be sensitive.


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++) {
  if(runningAppProcessInfo.get(i).processName.equals("com.the.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;
}

2. After API Level 21 (Lolipop)


the getRunningTasks is deprecated


other approach :
getAppTasks 
http://developer.android.com/reference/android/app/ActivityManager.html#getAppTasks%28%29


http://www.intertech.com/Blog/android-5-api-changes-getapptasks/

沒有留言:

張貼留言