Get current App Package Name On Foreground - Android App

Android examples for App:App Running

Description

Get current App Package Name On Foreground

Demo Code


//package com.java2s;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;

import java.util.List;

public class Main {

    public static String currentAppPackageNameOnForeground(
            final Context context) {
        try {/*from   ww  w  .j a  v  a  2s  .  c om*/
            ActivityManager am = (ActivityManager) context
                    .getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> tasks = am
                    .getRunningTasks(1);
            if (!tasks.isEmpty()) {
                ComponentName topActivity = tasks.get(0).topActivity;
                return topActivity.getPackageName();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "";
    }
}

Related Tutorials