我正在创建一个app lock应用程序.如何在棒棒糖中获得当前的运行任务?在lollipop API中不推荐使用getRunningTaskinfo方法,那么如何克服这个问题呢?
解决方法:
试试这个:
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();}
我们可以使用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 "";}
//启用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);
总结 以上是内存溢出为你收集整理的android – 如何`getTopActivity`名称或获取当前在棒棒糖中运行的应用程序包名称?全部内容,希望文章能够帮你解决android – 如何`getTopActivity`名称或获取当前在棒棒糖中运行的应用程序包名称?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)