-1

I know we can detect the installed application but is there any way to detect that which application is in use or which is in idle/closed state?

For example, if I open the Whatsapp, it can detect the WhatsApp and Toast me a message "using WhatsApp".

General Grievance
  • 4,555
  • 31
  • 31
  • 45

1 Answers1

1

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

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 your stuff here.
  }
}

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

this response is from this post : How to get the list of running applications?

Amir Hossein Mirzaei
  • 2,325
  • 1
  • 9
  • 17
  • A background service which detects whether the app is open or not for eg : if in my application I want to detect "Whatsapp" whenever it got open by the user just toast a message. – Sanjot Singh Hora Jul 18 '18 at 19:33