我是安卓新手。我正在开发一个应用程序储物柜,它使用面部 id 而不是使用 kotlin 的普通 pin/pattern。我有系统中已安装应用程序的列表。但是,如何获取有关使用服务打开哪个应用程序的信息请帮助。
问问题
410 次
1 回答
0
像这样:
爪哇版
private String retriveAppInForeground() {
String currentApp = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
UsageStatsManager usm = (UsageStatsManager) this.getSystemService(Context.USAGE_STATS_SERVICE);
long time = System.currentTimeMillis();
List<UsageStats> appList = null;
if (usm != null) {
appList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 1000, time);
}
if (appList != null && !appList.isEmpty()) {
SortedMap<Long, UsageStats> sortedMap = new TreeMap<>();
for (UsageStats usageStats : appList) {
sortedMap.put(usageStats.getLastTimeUsed(), usageStats);
}
if (!sortedMap.isEmpty()) {
currentApp = sortedMap.get(sortedMap.lastKey()).getPackageName();
}
}
} else {
ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
if (am != null) {
currentApp =(am.getRunningTasks(1).get(0)).topActivity.getPackageName();
}
}
Log.e("ActivityTAG", "Application in foreground: " + currentApp);
return currentApp;
}
Kotlin 版本
private fun retriveAppInForeground(): String? {
var currentApp: String? = null
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
val usm = this.getSystemService(Context.USAGE_STATS_SERVICE) as UsageStatsManager
val time = System.currentTimeMillis()
val appList: List<UsageStats>?
appList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 1000, time)
if (appList != null && appList.isNotEmpty()) {
val sortedMap = TreeMap<Long, UsageStats>()
for (usageStats in appList) {
sortedMap.put(usageStats.lastTimeUsed, usageStats)
}
currentApp = sortedMap.takeIf { it.isNotEmpty() }?.lastEntry()?.value?.packageName
}
} else {
val am = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
@Suppress("DEPRECATION") //The deprecated method is used for devices running an API lower than LOLLIPOP
currentApp = am.getRunningTasks(1)[0].topActivity.packageName
}
Log.e("ActivityTAG", "Application in foreground: " + currentApp)
return currentApp
}
确保您的应用具有访问使用情况统计信息的适当权限:
<uses-permission android:name="android.permission.PACKAGE_USAGE_STATS"/>
并且用户授予适当的权限,您可以将用户带到适当的设置屏幕以启用权限(在设置您的应用程序时):
startActivity(new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS));
还有一件事,请始终确保在发布新问题之前搜索任何类似的问题。
于 2019-03-27T13:51:25.227 回答