您的位置:首页 > 其它

Activity中启动另一个应用的另类方法,无需类名

2011-11-25 23:24 405 查看
Activity中启动另一个应用的另类方法,无需类名

由陈瑞轩发布于2011-10-22,Saturday,13:50 [android开发]

PackageManager类中有一个

public abstract Intent getLaunchIntentForPackage (String packageName) 方法,源码如下:

/**

* Return a "good" intent to launch a front-door activity in a package,

* for use for example to implement an "open" button when browsing through

* packages. The current implementation will look first for a main

* activity in the category {@link Intent#CATEGORY_INFO}, next for a

* main activity in the category {@link Intent#CATEGORY_LAUNCHER}, or return

* null if neither are found.

*

* <p>Throws {@link NameNotFoundException} if a package with the given

* name can not be found on the system.

*

* @param packageName The name of the package to inspect.

*

* @return Returns either a fully-qualified Intent that can be used to

* launch the main activity in the package, or null if the package does

* not contain such an activity.

*/

public abstract Intent getLaunchIntentForPackage(String packageName);

Android 开发有时需要在一个应用中启动另一个应用,比如Launcher加载所有的已安装的程序的列表,当点击图标时可以启动另一个应用。

一般我们知道了另一个应用的包名和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);

}

}

本文来陈瑞轩的博客,转载请标明出处:http://www.chenruixuan.com/?post=708
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐