Tuesday, June 30, 2015

Find application running in foreground from service in Android

Use this code in Service to get foreground apps and take your own task.
 try {
            ActivityManager activityManager = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();

            //   final String packageName = context.getPackageName();
            for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
                //   if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals()) {
                if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    Log.i("Foreground App", appProcess.processName);
                    String B2MAppsPKGName = appProcess.processName;

                    ////////Select Package name From SQLite DataBase//////////

                    OurStoreAppsPackages = new ArrayList<String>();
                    OurStoreAppsPackages = databaseHelper.getOurAllAppsPackage();

                    if (OurStoreAppsPackages.contains(B2MAppsPKGName)) {
                        //  if (storedPackageName == true) {
                        Log.i("DatabaseForeground App", B2MAppsPKGName);

                        ////// Go to GameStartPage page ./////////
                        Intent ii = new Intent(this, GameStartPage.class);
                        ii.putExtra("pkgName", B2MAppsPKGName);
                        ii.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(ii);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

No comments:

Post a Comment