Android examples for App:App Information
get Current Task App Name
//package com.java2s; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.ActivityManager; import android.app.usage.UsageStats; import android.app.usage.UsageStatsManager; import android.content.Context; import android.os.Build; import android.util.Log; import java.util.List; import java.util.SortedMap; import java.util.TreeMap; public class Main { @TargetApi(Build.VERSION_CODES.LOLLIPOP) @SuppressLint("NewApi") public static String getTaskPackNameForMi(Context context) { String currentApp = "CurrentNULL"; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { UsageStatsManager usm = (UsageStatsManager) context .getSystemService(Context.USAGE_STATS_SERVICE); long time = System.currentTimeMillis(); List<UsageStats> appList = usm.queryUsageStats( UsageStatsManager.INTERVAL_DAILY, time - 1000 * 1000, time);/* w ww. j av a2 s . c o m*/ if (appList != null && appList.size() > 0) { SortedMap<Long, UsageStats> mySortedMap = new TreeMap<>(); for (UsageStats usageStats : appList) { mySortedMap.put(usageStats.getLastTimeUsed(), usageStats); } if (!mySortedMap.isEmpty()) { currentApp = mySortedMap.get(mySortedMap.lastKey()) .getPackageName(); } } } else { ActivityManager am = (ActivityManager) context .getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.RunningAppProcessInfo> tasks = am .getRunningAppProcesses(); currentApp = tasks.get(0).processName; } return currentApp; } }