Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect When other Application opened or Launched

Tags:

android

I would like to track or detect when the user tries to open a application in the mobile like facebook or yahoo or gmail or any other application. Eg:- To know these are the application user has opened in last 30 minutes.

like image 582
Deeps Avatar asked Mar 19 '14 09:03

Deeps


1 Answers

You cannot detect an App launch in Android. But you can get the list of currently open apps using this code and check if the app you're looking for is open or not:

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
  }
}

You can also check if the app is running in the foreground using this method

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;
}
like image 167
desidigitalnomad Avatar answered Oct 19 '22 01:10

desidigitalnomad