简体   繁体   中英

How to install APK file from assets folder?

I want to install an APK file from the Assets folder. I use the method: Copy the Apk file from the Assets folder to the folder of internal storage. Then install the APK file. But I got this error:

`android.os.FileUriExposedException: file:///sdcard/myapk.apk exposed beyond app through 
Intent.getData()` 

MainActivity.java:

    btn2 = findViewById(R.id.btn2);
    btn2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            rarPath = "test.apk";
            AssetManager assetManager = getAssets();

            InputStream in = null;
            OutputStream out = null;
            try {
                in = assetManager.open(rarPath);
                out = new FileOutputStream("/sdcard/myapk.apk");

                byte[] buffer = new byte[1024];

                int read;
                while((read = in.read(buffer)) != -1) {

                    out.write(buffer, 0, read);

                }

                in.close();
                in = null;

                out.flush();
                out.close();
                out = null;

                Intent intent = new Intent(Intent.ACTION_VIEW);

                intent.setDataAndType(Uri.fromFile(new File("/sdcard/myapk.apk")),
                        "application/vnd.android.package-archive");

                startActivity(intent);

            } catch(Exception e) { e.printStackTrace();
                Toast.makeText(getApplicationContext(),"Error !",Toast.LENGTH_LONG).show();}
        }
    });
}





          

If targetSdkVersion is higher than 24, then FileProvider is used to grant access.

Create an xml file(Path: res\xml) provider_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>

Add a Provider in AndroidManifest.xml

<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="${applicationId}.provider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/provider_paths"/>
</provider>

If you are using androidx, the FileProvider path should be:

android:name="androidx.core.content.FileProvider"

and replace

Uri uri = Uri.fromFile(yourPath);

to

Uri uri = FileProvider.getUriForFile(MainActivity.this,BuildConfig.APPLICATION_ID + ".provider",yourPath);

Edit: While you're including the URI with an Intent make sure to add below line:

intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM