I am working on push notification in android where i am using a below method to show notification, but the problem is that now ActivityManager.getRunningTasks(1); is being
in Kotlin
fun isAppRunning(context: Context): Boolean {
val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
return activityManager.appTasks
.filter { it.taskInfo != null }
.filter { it.taskInfo.baseActivity != null }
.any { it.taskInfo.baseActivity.packageName == context.packageName }
}
This should help you get started
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.AppTask> tasks = activityManager.getAppTasks();
for (ActivityManager.AppTask task : tasks) {
Log.d(TAG, "stackId: " + task.getTaskInfo().stackId);
}
May you want this:
/***
* Checking Whether any Activity of Application is running or not
* @param context
* @return
*/
public static boolean isForeground(Context context) {
// Get the Activity Manager
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
// Get a list of running tasks, we are only interested in the last one,
// the top most so we give a 1 as parameter so we only get the topmost.
List<ActivityManager.RunningAppProcessInfo> task = manager.getRunningAppProcesses();
// Get the info we need for comparison.
ComponentName componentInfo = task.get(0).importanceReasonComponent;
// Check if it matches our package name.
if(componentInfo.getPackageName().equals(context.getPackageName()))
return true;
// If not then our app is not on the foreground.
return false;
}
This should work for the pre Lollipop devices as well as for Lollipop devices
public static boolean isBackgroundRunning(Context context) {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
for (String activeProcess : processInfo.pkgList) {
if (activeProcess.equals(context.getPackageName())) {
//If your app is the process in foreground, then it's not in running in background
return false;
}
}
}
}
return true;
}
Edit: It should return true if the app is in background, not the opposite
val cn: ComponentName
val am = applicationContext.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
cn = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
am.appTasks[0].taskInfo.topActivity
} else {
am.getRunningTasks(1)[0].topActivity
}
This is work for me