How to `getTopActivity` name or get currently runn

2019-01-04 00:47发布

I am creating a app lock application. How to get current running task in lollipop? getRunningTaskinfo method is deprecated in lollipop API, then how to overcome this problem?

7条回答
放荡不羁爱自由
2楼-- · 2019-01-04 00:57

Can be achieved like this.....

ActivityManager am =(ActivityManager)context.getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
ActivityManager.RunningTaskInfo task = tasks.get(0); // current task
ComponentName rootActivity = task.baseActivity;


rootActivity.getPackageName();//*currently active applications package name*

For lollipop:

ActivityManager mActivityManager =(ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);

if(Build.VERSION.SDK_INT > 20){
    String activityName =mActivityManager.getRunningAppProcesses().get(0).processName;
 }
else{
 String activityName =   mActivityManager.getRunningTasks(1).get(0).topActivity.getPackageName();
}

for complete example check this out...

查看更多
叼着烟拽天下
3楼-- · 2019-01-04 01:02

Try this.. This worked for me.

ActivityManager activityManager = (ActivityManager) getSystemService (Context.ACTIVITY_SERVICE);

if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP)    
{

String packageName = activityManager.getRunningAppProcesses().get(0).processName;
} 
else if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP)
{
String packageName =  ProcessManager.getRunningForegroundApps(getApplicationContext()).get(0).getPackageName();

}
else
{
String packageName = activityManager.getRunningTasks(1).get(0).topActivity.getPackageName();
}
查看更多
欢心
4楼-- · 2019-01-04 01:05

@Manish Godhani's answer (https://stackoverflow.com/a/38829083/8179249) works very well, but you have to give the right permissions for this !

See the two first points of that answer : https://stackoverflow.com/a/42560422/8179249

It works for me (before adding permissions I was getting 'null' too), as shown below : Results given by the code of that answer, after adding permissions

查看更多
贪生不怕死
5楼-- · 2019-01-04 01:06

You can use the AccessibilityService to get current Running app. Accessibility Service provides the onAccessibilityEvent event.

Following is some sample code.

@Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
            if (event.getPackageName() != null && event.getClassName() != null) {
                Log.d("Foreground App", event.getPackageName().toString());  

            }
        }
    }

You can find more info about Accessibility Service here

查看更多
Emotional °昔
6楼-- · 2019-01-04 01:15

try this:

ActivityManager mActivityManager =(ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);

if(Build.VERSION.SDK_INT > 20){
String mPackageName = mActivityManager.getRunningAppProcesses().get(0).processName;
}
else{
  String mpackageName = mActivityManager.getRunningTasks(1).get(0).topActivity.getPackageName();
}

we can get using UsageStats:

public static String getTopAppName(Context context) {
    ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    String strName = "";
    try {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            strName = getLollipopFGAppPackageName(context);
        } else {
            strName = mActivityManager.getRunningTasks(1).get(0).topActivity.getClassName();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return strName;
}


private static String getLollipopFGAppPackageName(Context ctx) {

    try {
        UsageStatsManager usageStatsManager = (UsageStatsManager) ctx.getSystemService("usagestats");
        long milliSecs = 60 * 1000;
        Date date = new Date();
        List<UsageStats> queryUsageStats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, date.getTime() - milliSecs, date.getTime());
        if (queryUsageStats.size() > 0) {
            Log.i("LPU", "queryUsageStats size: " + queryUsageStats.size());
        }
        long recentTime = 0;
        String recentPkg = "";
        for (int i = 0; i < queryUsageStats.size(); i++) {
            UsageStats stats = queryUsageStats.get(i);
            if (i == 0 && !"org.pervacio.pvadiag".equals(stats.getPackageName())) {
                Log.i("LPU", "PackageName: " + stats.getPackageName() + " " + stats.getLastTimeStamp());
            }
            if (stats.getLastTimeStamp() > recentTime) {
                recentTime = stats.getLastTimeStamp();
                recentPkg = stats.getPackageName();
            }
        }
        return recentPkg;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}

// TO ENABLE USAGE_STATS

    // Declare USAGE_STATS permisssion in manifest

    <uses-permission
    android:name="android.permission.PACKAGE_USAGE_STATS"
    tools:ignore="ProtectedPermissions" />


    Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
    startActivity(intent);
查看更多
爱情/是我丢掉的垃圾
7楼-- · 2019-01-04 01:16

Best solution of get Running app in API 21 or up is below try it. this work for me

private String retriveNewApp() {
    if (VERSION.SDK_INT >= 21) {
        String currentApp = null;
        UsageStatsManager usm = (UsageStatsManager) this.getSystemService(Context.USAGE_STATS_SERVICE);
        long time = System.currentTimeMillis();
        List<UsageStats> applist = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 1000, time);
        if (applist != null && applist.size() > 0) {
            SortedMap<Long, UsageStats> mySortedMap = new TreeMap<>();
            for (UsageStats usageStats : applist) {
                mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
            }
            if (mySortedMap != null && !mySortedMap.isEmpty()) {
                currentApp = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
            }
        }
        Log.e(TAG, "Current App in foreground is: " + currentApp);

        return currentApp;

    }
    else {

        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        String mm=(manager.getRunningTasks(1).get(0)).topActivity.getPackageName();
        Log.e(TAG, "Current App in foreground is: " + mm);
        return mm;
    }
}
查看更多
登录 后发表回答