如何在棒棒糖中获取“ getTopActivity”名称或获取当前正在运行的应用程序包名称?

我正在创建一个应用锁定应用程序。如何在棒棒糖中获取当前正在运行的任务?getRunningTaskinfo棒棒糖API中已弃用该方法,那么如何解决此问题?



青春有我
浏览 715回答 3
3回答

catspeake

在API 21或更高版本中获取“运行应用”的最佳解决方案是尝试以下方法。这项工作对我来说private String retriveNewApp() {&nbsp; &nbsp; if (VERSION.SDK_INT >= 21) {&nbsp; &nbsp; &nbsp; &nbsp; String currentApp = null;&nbsp; &nbsp; &nbsp; &nbsp; UsageStatsManager usm = (UsageStatsManager) this.getSystemService(Context.USAGE_STATS_SERVICE);&nbsp; &nbsp; &nbsp; &nbsp; long time = System.currentTimeMillis();&nbsp; &nbsp; &nbsp; &nbsp; List<UsageStats> applist = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 1000, time);&nbsp; &nbsp; &nbsp; &nbsp; if (applist != null && applist.size() > 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; SortedMap<Long, UsageStats> mySortedMap = new TreeMap<>();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (UsageStats usageStats : applist) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (mySortedMap != null && !mySortedMap.isEmpty()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; currentApp = mySortedMap.get(mySortedMap.lastKey()).getPackageName();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; Log.e(TAG, "Current App in foreground is: " + currentApp);&nbsp; &nbsp; &nbsp; &nbsp; return currentApp;&nbsp; &nbsp; }&nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);&nbsp; &nbsp; &nbsp; &nbsp; String mm=(manager.getRunningTasks(1).get(0)).topActivity.getPackageName();&nbsp; &nbsp; &nbsp; &nbsp; Log.e(TAG, "Current App in foreground is: " + mm);&nbsp; &nbsp; &nbsp; &nbsp; return mm;&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Android