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