如何获取其他包中的第二个顶级活动的包名?

时间:2012-11-29 06:26:09

标签: android android-package-managers

在我的情况下,应用程序调用服务,服务将启动活动。我的问题是获取调用该服务的应用程序包。

有人可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

我是直接从android源码发现的,它运行正常:)

final ActivityManager am = (ActivityManager)
                getSystemService(Context.ACTIVITY_SERVICE);

        final List<ActivityManager.RecentTaskInfo> recentTasks =
                am.getRecentTasks(3, ActivityManager.RECENT_IGNORE_UNAVAILABLE);
        for (int i = 0, index = 0; i < 3 && (index < 3); ++i) {
            final ActivityManager.RecentTaskInfo recentInfo = recentTasks.get(i);

            Intent intent = new Intent( recentInfo.baseIntent);
            if ( recentInfo.origActivity != null) {
                intent.setComponent( recentInfo.origActivity);
            }

            final PackageManager pm = getPackageManager();
            final ResolveInfo resolveInfo = pm.resolveActivity(intent, 0);
            final ActivityInfo info = resolveInfo.activityInfo;
            final String title = info.loadLabel(pm).toString();

            Log.d("hello","  "+title+" "+info.packageName);
           final ImageView iv = (ImageView)findViewById(R.id.imageView1);
           iv.setImageDrawable(info.loadIcon(pm));
                ++index;
            }

答案 1 :(得分:0)

试试这个

ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
          ComponentName topActivity = tasks.get(1).topActivity;
          if (!topActivity.getPackageName().equals(context.getPackageName())) {
            return true;
          }
        }

获得第二项顶级活动对您有用。