13

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.

Deeps
  • 135
  • 1
  • 1
  • 6
  • In what development platform? – Brendan Mar 19 '14 at 09:34
  • In Android, I am creating an application where in it will be working background, my application has to detect what are all other application the user has opened or Launched or used. – Deeps Mar 19 '14 at 09:42
  • Possible duplicate of [Android, Detect when other apps are launched](http://stackoverflow.com/questions/3290936/android-detect-when-other-apps-are-launched) – Manuel Allenspach Dec 05 '16 at 11:37

3 Answers3

10

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;
}
desidigitalnomad
  • 1,443
  • 21
  • 33
  • @Pedram You are right. Same problem facing here. Can you provide us any other way for this? – VVB Jan 23 '16 at 12:21
  • Which permission is required? – M. Usman Khan Feb 23 '17 at 12:42
  • ActivityManager.getRunningAppProcesses() returns only the current process on 9.0 – Ondrej Sotolar Feb 11 '19 at 10:51
  • 1
    I suspect about this "You ***cannot*** detect an App launch in Android". Because there are many apps in Google Play store seem to be able to do that such as [App Locker](https://play.google.com/store/apps/details?id=dev.tuantv.android.applocker), [AppLock](https://play.google.com/store/apps/details?id=com.domobile.applockwatcher) – tuantv.dev May 13 '21 at 01:03
0

MORE MODERN ANSWER (Nov 2022):

This can be handled by the new [app usage API][1]

The system collects the usage data on a per-app basis, aggregating the data over daily, weekly, monthly, and yearly intervals. The maximum duration that the system keeps this data is as follows:

Daily data: 7 days Weekly data: 4 weeks Monthly data: 6 months Yearly data: 2 years For each app, the system records the following data:

The last time the app was used

The total length of time the app was in the foreground for that time interval (by > day, week, month, or year)

Timestamp capturing when a component (identified by a package and activity name) ?> moved to the foreground or background during a day

Timestamp capturing when a device configuration changed (such as when the device orientation changed because of rotation)

A background service can be used to constantly watch for updates to timestamps for specific apps regarding when they moved to the foreground with the API above.

JakeD
  • 407
  • 2
  • 7
  • 19
-3

With the help of @aaRBiyecH's answer, I have created a service which can detect if other application launches. In this example, the service detects for the Android Dialer app (com.android.dialer):

@Override
public int onStartCommand(Intent intent, int flags, int startId){
    private static final String TAG = "com.myapp.Service"; // Replace this with your actual class' name
    Timer timer  =  new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
        boolean isDialerAppLaunched = false, isDialerAppClosed = false;
        int dialerAppLaunches = 0;
        @Override
        public void run() {
            ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningAppProcessInfo> runningAppProcessInfo = am.getRunningAppProcesses();

            for ( ActivityManager.RunningAppProcessInfo appProcess: runningAppProcessInfo ) {
                Log.d(appProcess.processName.toString(),"is running");
                if (appProcess.processName.equals("com.android.dialer")) {
                    if ( appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND){
                        if (!isDialerAppLaunched){
                            isDialerAppLaunched = true;
                            Log.d(TAG, "Dialer app has been launched");
                        }
                        else if (isDialerAppClosed){
                            phonelaunches++;
                            isDialerAppClosed = false;
                            Log.d("Dialer app has been launched " + String.valueOf(phonelaunches) + "times.");
                        }
                    }
                    else {
                        isDialerAppClosed = true;
                        Log.d(str,"Dialer app has been closed.");

                    }
                }
            }
        }
    },2000,3000);

    return START_STICKY;
}

Here I go through all the running tasks and check if it is our intended application. If so, I check if the application is in the foreground and application is never launched using the isDialerAppLaunched variable. isDialerAppClosed is used when the intended application is in the background and the variable is set accordingly.

All this is implemented in a Service class.

Edric
  • 24,639
  • 13
  • 81
  • 91
forcode
  • 25
  • 5
  • Is this going to check every 3 seconds 24/7? I think it would kill the battery no? – 124697 Sep 10 '16 at 18:35
  • 2
    Hi there Shashank! Please take note that in Java, there's a data type known as `boolean`s. I believe this is what you're looking for instead of using `0` to indicate a false value and `1` for a true value. Please also take note that the `Toast` in your service class would keep showing every 3 seconds which would be detrimental to the user who keeps seeing the toast every few seconds. This is a bad case. Also, as @code511788465541441 said, it's a bad idea to make the service run every 3 seconds. This can be bad especially for phones with lots of apps and can even drain the phone's battery! – Edric Aug 25 '18 at 15:15
  • so what are the solutions for tracking the app whether it's run or not? is there any safeties method? – gumuruh Apr 17 '23 at 05:53