如何获得在Android的5.0(L)上运行的应用程序的活动名称? [英] How to get running application activity Name in android 5.0(L)?

查看:292
本文介绍了如何获得在Android的5.0(L)上运行的应用程序的活动名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用下面的code取得的Andr​​oid当前正在运行的活动名称。

I am using the following code to get the current running activity name in 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());

这是工作的罚款在下面的Andr​​oid所有版本 5.0 。但在Android的5.0它的总是返回发射活动

This is working fine in all the versions below android 5.0. But in Android 5.0 it always returning the launcher activity.

请在此任何一个帮助,因为我想使运行在所有的Andr​​oid版本的应用程序。

Please any one help in this because I want to make run the application in all android versions.

推荐答案

在此之前的Andr​​oid L您的code将工作,但Android的大号起getRunningTask将无法正常工作。你必须使用getAppRunningProcess。

Prior to Android L your code will work, but from Android L onward getRunningTask will not work. You have to use getAppRunningProcess.

勾选此code以下 -

Check this code below -

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()]);
}
}  

希望这有助于你:)

Hope this helps you :)

这篇关于如何获得在Android的5.0(L)上运行的应用程序的活动名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆