我使用以下代码获取android中的当前运行活动名称。
ActivityManager am = (ActivityManager) aContext
.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> alltasks = am
.getRunningTasks(1);
ComponentName componentInfo = alltasks.get(0).topActivity;
componentInfo.getClassName();
System.out.println("Current:"+componentInfo.getClassName());
这在android 5.0
下面的所有版本中运行良好。但在Android 5.0中,始终返回启动器活动。
请任何一个帮助,因为我想在所有Android版本中运行应用程序。
答案 0 :(得分:15)
在Android L之前,您的代码将起作用,但是从Android L开始,getRunningTask将无法正常工作。你必须使用getAppRunningProcess。
检查以下代码 -
public class DetectCalendarLaunchRunnable implements Runnable {
@Override
public void run() {
String[] activePackages;
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
activePackages = getActivePackages();
} else {
activePackages = getActivePackagesCompat();
}
if (activePackages != null) {
for (String activePackage : activePackages) {
if (activePackage.equals("com.google.android.calendar")) {
//Calendar app is launched, do something
}
}
}
mHandler.postDelayed(this, 1000);
}
String[] getActivePackagesCompat() {
final List<ActivityManager.RunningTaskInfo> taskInfo = mActivityManager.getRunningTasks(1);
final ComponentName componentName = taskInfo.get(0).topActivity;
final String[] activePackages = new String[1];
activePackages[0] = componentName.getPackageName();
return activePackages;
}
String[] getActivePackages() {
final Set<String> activePackages = new HashSet<String>();
final List<ActivityManager.RunningAppProcessInfo> processInfos = mActivityManager.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo processInfo : processInfos) {
if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
activePackages.addAll(Arrays.asList(processInfo.pkgList));
}
}
return activePackages.toArray(new String[activePackages.size()]);
}
}
希望这可以帮助你:)
答案 1 :(得分:2)
您可以使用:
String packageName = "";
String className = "";
UsageStatsManager usageStatsManager = (UsageStatsManager) this.getSystemService(Context.USAGE_STATS_SERVICE);
if (usageStatsManager != null)
{
UsageEvents queryEvents = usageStatsManager.queryEvents(System.currentTimeMillis() - 10000, System.currentTimeMillis());
if (queryEvents != null)
{
UsageEvents.Event event = new UsageEvents.Event();
while (queryEvents.hasNextEvent())
{
UsageEvents.Event eventAux = new UsageEvents.Event();
queryEvents2.getNextEvent(eventAux);
if (eventAux.getEventType() == UsageEvents.Event.MOVE_TO_FOREGROUND)
{
event = eventAux;
}
}
packageName = event.getPackageName();
className = event.getClassName();
}
}
您需要android.permission.PACKAGE_USAGE_STATS,这是系统级权限,不会授予第三方应用。但是,声明权限意味着使用API的意图,并且设备的用户可以通过“设置”应用程序授予权限。
或者你可以这样做:
pm grant com.your.package android.permission.PACKAGE_USAGE_STATS
答案 2 :(得分:0)