一般我们知道了另一个应用的包名和MainActivity的名字之后便可以直接通过如下代码来启动:
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
ComponentName cn = new ComponentName(packageName, className);
intent.setComponent(cn);
startActivity(intent);
但是更多的时候,我们一般都不知道应用程序的启动Activity的类名,而只知道包名,我们可以通过ResolveInfo类来取得启动Acitivty的类名。
下面是实现代码:
private void openApp(String packageName) {
PackageInfo pi = getPackageManager().getPackageInfo(packageName, 0);
Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
resolveIntent.setPackage(pi.packageName);
List<ResolveInfo> apps = pm.queryIntentActivities(resolveIntent, 0);
ResolveInfo ri = apps.iterator().next();
if (ri != null ) {
String packageName = ri.activityInfo.packageName;
String className = ri.activityInfo.name;
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
ComponentName cn = new ComponentName(packageName, className);
intent.setComponent(cn);
startActivity(intent);
}
}
{
Intent intent = new Intent(Intent.ACTION_MAIN);
ComponentName componentName = new ComponentName("com.lenovo.gemini.OOBE", "com.lenovo.gemini.OOBE.Settings");
intent.setComponent(componentName);
startActivity(intent);
}
在代码中"com.lenovo.gemini.OOBE" 是要打开的程序包名," com.lenovo.gemini.OOBE.Settings"是要打开的Activity。
例子:程序中调用浏览器,代码如下:
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://163.com"));
startActivity(intent);