How to switch to other running application
I want to 开发者_开发问答write a application to switch to other running application, like "Switch to" on "Windows Task Manager".
I already have it's package name, process name, pid, label. But I don't know how to switch to it. Pls help me! Thank U!
P/S: I'm thinking about use Intent, but Intent.setClassName (String pkname, String cls name) need class name and i don't know how to get it.
That is an easy one.
ActivityManager am = (ActivityManager) inst.getSystemService(Context.ACTIVITY_SERVICE);
for(RunningTaskInfo t: am.getRunningTasks(10)){
String packageName = t.topActivity.getPackageName();
String className = t.topActivity.getClassName();
}
//Which one do you want?
//Could also just do
String packageName = am.getRunningTasks(1).get(0).topActivity.getPackageName();
String className = am.getRunningTasks(1).get(0).topActivity.getClassName();
//then
startActivity(new Intent().setClassName(packageName, className).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//Keep in mind you will need to declare the following permission in your AndroidManifest.xml
android.Manifest.permission.GET_TASKS
Using
List<ActivityManager.RunningTaskInfo> getRunningTasks();
Returns a list of tasks that are running on the device.
If you look at the RunningTaskInfo
API, there is a field public ComponentName baseActivity
ComponentName, on has these two public methods:
String getClassName()
Return the class name of this component.
String getPackageName()
Return the package name of this component.
ActivityManager am = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningTaskInfo info : am.getRunningTasks(9999)){
int id = info.id;
Log.d ("AM", "ID: " + id);
String name = info.baseActivity.getClassName();
Log.d ("AM", "Class: " + name);
}
精彩评论