我正在使用kiosk xamarin.android
app。
我需要知道我当前的前台应用(PackageName)
是什么。
尝试了一些样品,但没有用。
- 样本1 -
ActivityManager activityManager = (ActivityManager)BaseContext.GetSystemService(ActivityService);
List<ActivityManager.RunningAppProcessInfo> runningProcesses = activityManager.RunningAppProcesses.ToList();
foreach (ActivityManager.RunningAppProcessInfo processInfo in runningProcesses)
{
if (processInfo.Importance == Android.App.Importance.Foreground)
{
foreach (String activeProcess in processInfo.PkgList)
{
if (activeProcess.Equals(_context.PackageName))
{
return true;
}
}
}
}
- 样本2 -
ActivityManager activityManager = (ActivityManager)GetSystemService(Context.ActivityService);
var packageName = activityManager.RunningAppProcesses;
- 样本3 -
var am = _context.GetSystemService(ActivityService).JavaCast<ActivityManager>();
IList<ActivityManager.RunningTaskInfo> taskInfo = am.GetRunningTasks(5);
var componentInfo = taskInfo[0].TopActivity;
我在OnPause()
中调用这些代码,但所有这些代码只返回我的任务(my package name)
。
我也跟着这个例子 find application running in foreground from service
如果有人能给我至少一个理由,我感到非常高兴。
答案 0 :(得分:0)
终于找到了答案
Android 5.1.1 and above - getRunningAppProcesses() returns my application package only
UsageStatsManager usm = (UsageStatsManager)this.getSystemService("usagestats");
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<Long, UsageStats>();
for (UsageStats usageStats : appList) {
mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
}
if (mySortedMap != null && !mySortedMap.isEmpty()) {
currentApp = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
}
}