Android在一个app中安装并卸载另一个app

Android在一个app中安装并卸载另一个app

  1. 在app→src→main下新建文件夹asserts,将准备安装的apk文件放在asserts内
  2. 在app→src→main→res下新建文件夹xml,右击xml文件夹,选择new→XML Resource File,File name为文件名,可随意,本文中为filepaths;Root element为资源类型,输入paths,确定并编辑以下代码:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>
  1. 编辑AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.myapplication">
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:requestLegacyExternalStorage="true"
        android:theme="@style/Theme.MyApplication">
        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="包名"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/filepaths步骤2中的文件"
                />
        </provider>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>
  1. MainActivity.java
public class MainActivity extends AppCompatActivity {
    Context mContext;
    private Button bt,bt0;
    private TextView tx;
    public static boolean isGrantExternalRW(Activity activity) {
    //权限判定
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && activity.checkSelfPermission(
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            activity.requestPermissions(new String[]{
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
            }, 1);
            return false;
        }
        return true;
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;
        tx=findViewById(R.id.text);
        bt=findViewById(R.id.button);//安装
        bt0=findViewById(R.id.button0);//卸载
//        Toast.makeText(this, ""+Environment.getExternalStorageDirectory().getAbsolutePath(), 0).show();
       if(!this.isGrantExternalRW(MainActivity.this)){return;}//判断是否有权限修改,这很重要
       else{
        if(copyApkFromAssets(this, "app-debug.apk", Environment.getExternalStorageDirectory().getAbsolutePath()+"/app-debug.apk")){
            bt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    new AlertDialog.Builder(mContext)
                            .setIcon(R.drawable.ic_launcher)
                            .setMessage("是否安装?")
                            .setPositiveButton("yes", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Intent intent = new Intent(Intent.ACTION_VIEW);
                                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                                    intent.setDataAndType(Uri.parse("file://" + Environment.getExternalStorageDirectory().getAbsolutePath()+"/app-debug.apk"),
//                                            "application/vnd.android.package-archive");
                                    File apkFile = new File(Environment.getExternalStorageDirectory()+"/app-debug.apk");
                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                        Uri uri = FileProvider.getUriForFile(MainActivity.this, "com.example.myapplication", apkFile);
                                        intent.setDataAndType(uri, "application/vnd.android.package-archive");
                                    } else {
                                        intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
                                    }
                                    mContext.startActivity(intent);

                                }
                            }).show();
                }
            });
            bt0.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Uri packageURI = Uri.parse("package:com.example.a22");//package:+想要卸载的包名
                    Intent intent =new Intent(Intent.ACTION_DELETE);
                    intent.setData(packageURI);
                    mContext.startActivity(intent);
                }
            });
        }

    }}
    public boolean copyApkFromAssets(Context context, String fileName, String path) {
    //将asserts中的apk文件复制到手机存储中
    //可以从手机存储划到最下面,是单独的文件,没有设置文件夹
        boolean copyIsFinish = false;
        try {
            InputStream is = context.getAssets().open(fileName);
            File file = new File(path);
            file.createNewFile();
            FileOutputStream fos = new FileOutputStream(file);
            int  length = is.available();
            byte[] temp = new byte[length];
            int i = 0;
            while ((i = is.read(temp)) > 0) {
                fos.write(temp, 0, i);
            }
            fos.close();
            is.close();

            copyIsFinish = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return copyIsFinish;
    }
}

网络上的教程有很多自相矛盾,本人防止权限出错,把能加的权限都设置了一遍,有空可以选择测试一下,应该有的可以删掉

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值