Android 通过包名打开App的代码

来源:互联网 发布:python sum函数 编辑:程序博客网 时间:2024/05/16 06:29

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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// 帮助
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的参数
 */
privatevoid 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();
        }
        try{
            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不一定是我们自己写的。

?
1
2
3
4
5
6
7
8
9
10
11
    /*
 * 启动一个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();
    }
}


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

转载自:http://www.2cto.com/kf/201312/269058.html
0 0
原创粉丝点击