Android代码方式操作应用程序安装、卸载、分享、启动

通过代码的方式来执行应用程序的安装、卸载、分享、启动。
  • 通过代码方式来安装其他应用程序
String fileName = Environment.getExternalStorageDirectory() + "/myApp.apk";        
Intent intent = new Intent(Intent.ACTION_VIEW);     

intent.setDataAndType(Uri.parse("file://" + filePath),"application/vnd.android.package-archive");     
//或者     
//intent.setDataAndType(Uri.fromFile(new File(fileName)), "application/vnd.android.package-archive");      

startActivity(intent);
  • 通过代码方式来卸载应用程序
Uri packageURI = Uri.parse("package:com.android.myapp");        
Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);        
startActivity(uninstallIntent);   

或者写成 

Intent intent = new Intent();
intent.setAction(Intent.ACTION_DELETE);
intent.setData(Uri.parse("package:com.njupt.htmlui1"));
startActivity(intent);
  • 通过代码方式来分享应用程序
// intent.setType("text/plain"); //纯文本

  Intent intent=new Intent(Intent.ACTION_SEND);  
  intent.setType("image/*");  
  intent.putExtra(Intent.EXTRA_SUBJECT, "Share");  
  intent.putExtra(Intent.EXTRA_TEXT, "I have successfully share my message through my app");  
  intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
  startActivity(Intent.createChooser(intent, getTitle()));
/*
 * 图片分享 it.setType("image/png");  //添加图片 File f = new
 * File(Environment.getExternalStorageDirectory()+"/name.png");
 * 
 * Uri uri = Uri.fromFile(f); intent.putExtra(Intent.EXTRA_STREAM,
 * uri);  
 */
  • 通过代码方式来启动其他应用程序
方法一:

try{
    Intent intent = this.getPackageManager().getLaunchIntentForPackage(appPackageName);
    startActivity(intent);
}catch(Exception e){
    Toast.makeText(this, "没有安装", Toast.LENGTH_LONG).show();
}

方式二:

/**
 * 启动一个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();
        }
        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();
        }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值