问题
here in my case, a app invokes a service and the service will inturn starts an activity. My problem here is to get the app package which invokes that service.
Can anybody help me to solve this ?
回答1:
I found this directly from android source and it works fine :)
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;
}
回答2:
Try this
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;
}
}
It may useful to you to get second top activity.
来源:https://stackoverflow.com/questions/13620037/how-can-i-get-the-package-name-of-2nd-top-activity-which-is-in-other-package