天天看点

Android 通过包名打开App的代码

做launcher时,用户点击apk的图标就对应着需要打开这个apk,有两种方式可以启动这个apk

第一种:知道apk的包名和它的主activity

[java] view

plaincopyprint?

Android 通过包名打开App的代码
Android 通过包名打开App的代码

// 帮助  

private componentname help_set;  

private final static string help_set_pack = "cn.abc.help";  

private final static string help_set_name = "cn.abc.help.mainactivity";  

/** 

 * 启动一个app 

 * com -- componentname 对象,包含apk的包名和主activity名 

 * param -- 需要传给apk的参数 

 */  

private void startapp(componentname com, string param) {  

    if (com != null) {  

        packageinfo packageinfo;  

        try {  

            packageinfo = getpackagemanager().getpackageinfo(com.getpackagename(), 0);  

        } catch (namenotfoundexception e) {  

            packageinfo = null;  

            toast.maketext(this, "没有安装", toast.length_short).show();  

            e.printstacktrace();  

        }  

            intent intent = new intent();  

            intent.setflags(intent.flag_activity_new_task);  

            intent.setcomponent(com);  

            if (param != null) {  

                bundle bundle = new bundle(); // 创建bundle对象  

                bundle.putstring("flag", param); // 装入数据  

                intent.putextras(bundle); // 把bundle塞入intent里面  

            }  

            startactivity(intent);  

        } catch (exception e) {  

            toast.maketext(this, "启动异常", toast.length_short).show();  

    }  

}  

第二种:只知道apk的包名,这种方法最常用了,毕竟要启动的apk不一定是我们自己写的。

Android 通过包名打开App的代码
Android 通过包名打开App的代码

       /* 

public void startapp(string apppackagename){  

    try{  

        intent intent = this.getpackagemanager().getlaunchintentforpackage(apppackagename);  

        startactivity(intent);  

    }catch(exception e){  

        toast.maketext(this, "没有安装", toast.length_long).show();  

综合起来比较第二种方法的代码要简洁得多,比较实用!

继续阅读