Android Question INline java 4 get running package name

ArminKH

Well-Known Member
hi can any body help me to use this code with inline java?
B4X:
public class DetectCalendarLaunchRunnable implements Runnable {

@Override
public void run() {
  String[] activePackages;
  if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
    activePackages = getActivePackages();
  } else {
    activePackages = getActivePackagesCompat();
  }
  if (activePackages != null) {
    for (String activePackage : activePackages) {
      if (activePackage.equals("com.google.android.calendar")) {
        //Calendar app is launched, do something
      }
    }
  }
  mHandler.postDelayed(this, 1000);
}

String[] getActivePackagesCompat() {
  final List<ActivityManager.RunningTaskInfo> taskInfo = mActivityManager.getRunningTasks(1);
  final ComponentName componentName = taskInfo.get(0).topActivity;
  final String[] activePackages = new String[1];
  activePackages[0] = componentName.getPackageName();
  return activePackages;
}

String[] getActivePackages() {
  final Set<String> activePackages = new HashSet<String>();
  final List<ActivityManager.RunningAppProcessInfo> processInfos = mActivityManager.getRunningAppProcesses();
  for (ActivityManager.RunningAppProcessInfo processInfo : processInfos) {
    if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
      activePackages.addAll(Arrays.asList(processInfo.pkgList));
    }
  }
  return activePackages.toArray(new String[activePackages.size()]);
}
}
tnx
 

DonManfred

Expert
Licensed User
Longtime User
your posted code will not work on lollipop too.

As MKY mentioned, getRunningTasks() method does not work for getting current application at Lolipop. As sunxin8086 said, the one way for getting running applications is using getRunningAppsProcesses() method. However, the condition info.importance == IMPORTANCE_FOREGROUND can not detemine the current app uniquely.
 
Last edited:
Upvote 0

jahswant

Well-Known Member
Licensed User
Longtime User
Yes @arminkh will not work on lolipop... Try this
B4X:
ActivityManager manager = (ActivityManager)mContext.getSystemService(Context.ACTIVITY_SERVICE);

List<ActivityManager.RunningAppProcessInfo> tasks = manager.getRunningAppProcesses(); 

Log.i("current_app",tasks.get(0).processName);
 
Last edited:
Upvote 0

ArminKH

Well-Known Member
Yes @arminkh will not work on lolipop... Try this

ActivityManager manager = (ActivityManager)mContext.getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.RunningAppProcessInfo> tasks = manager.getRunningAppProcesses(); Log.i("current_app",tasks.get(0).processName);
Is this java code?
Tnx
 
Upvote 0
Top