1

I want to get notified when foreground application change. Is there any way to do this ? and it should work for the devices running on Android 5+ as well.

Can anyone help me?

  • Possibly Similar to http://stackoverflow.com/q/13193592/6399911 – malik-ab Jun 09 '16 at 09:58
  • 1
    look at Sam answer: http://stackoverflow.com/questions/3873659/ Github project based on that answer: https://github.com/seguri/GetForegroundActivity – Milon May 09 '17 at 19:12

1 Answers1

0

It was possible till Android 5 only. Lollipop deprecated getRunningTasks(), then getRunningAppProcess() was used. MarshMallow doesn't allow both. However using an external small library by Jared Rummler, you can get the current running processes on Android. The link is: https://github.com/jaredrummler/AndroidProcesses

I can as well post my code how to do it till Lollipop, if you want !!

public class MyService extends Service {
Context context;
Handler handler;
Runnable runnable;
NotificationManager mNotificationManager;
NotificationCompat.Builder mBuilder;
public MyService() {
}

@Override
public IBinder onBind(Intent intent) {
    // TODO: Return the communication channel to the service.
    throw new UnsupportedOperationException("Not yet implemented");
}


@Override
public void onCreate() {
    super.onCreate();
    context = this;
    mBuilder =
            new NotificationCompat.Builder(context)
                    .setSmallIcon(R.drawable.tick)
                    .setContentTitle("My notification")
                    .setContentText("Foreground Application Changed");

    Intent resultIntent = new Intent(context, MainActivity.class);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    stackBuilder.addParentStack(MainActivity.class);
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent =
            stackBuilder.getPendingIntent(
                    0,PendingIntent.FLAG_UPDATE_CURRENT
            );
    mBuilder.setContentIntent(resultPendingIntent);
    mNotificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    Log.i("debug", "in onCreateService");

    handler = new Handler();
    runnable = new Runnable() {
        @Override
        public void run() {
            new Thread(new Runnable() {
                @Override
                public void run() {


                    ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
                    final Set<String> activePackages = new HashSet();
                    List<ActivityManager.RunningAppProcessInfo> list = activityManager.getRunningAppProcesses();

                    for (ActivityManager.RunningAppProcessInfo processInfo : list) {
                        if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                            activePackages.addAll(Arrays.asList(processInfo.pkgList));
                        }
                    }
                    for(String a : activePackages.toArray(new String[activePackages.size()])) {

                        if(foregroundApps.contains(a)) {
                            Log.i("debug", "App in foreground " + a);
                            mNotificationManager.notify(1, mBuilder.build());
                        }

                    }
                  }


            }).start();
            //process runnable object in 3 secs
            handler.postDelayed(this,3000);
        }
    };

    //make operation on UI thread, call runnable in 3 secs
    handler.postDelayed(runnable,3000);
}

Start this service from your activity. To prevent getting notified for all running apps, you can have a list of all installed apps. Then pass this as list of foreground apps

PackageManager packageManager;
List<PackageInfo> packages;
List<PackageInfo> packageList;
packageList = new ArrayList<>();   
packageManager = getPackageManager();
packages = packageManager.getInstalledPackages(PackageManager.GET_PERMISSIONS);
    for (PackageInfo pi : packages) {
        boolean b = isSystemPackage(pi);
        if ((!b)) {
            packageList.add(pi);

        }
    }
}
private boolean isSystemPackage(PackageInfo pkgInfo) {
    return ((pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) ? true
            : false;

}
kuhi
  • 31
  • 3
  • Thanks for the answer. Is there any way to get notified(any event) when foreground app change(till Android L)? and also please share your code. – Sapna Sharma Jun 09 '16 at 10:22