簡體   English   中英

如何從 assets 文件夾安裝 APK 文件?

[英]How to install APK file from assets folder?

我想從 Assets 文件夾中安裝一個 APK 文件。 我使用方法:將Apk文件從Assets文件夾復制到內部存儲文件夾。 然后安裝APK文件。 但我得到了這個錯誤:

`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();}
        }
    });
}





          

如果 targetSdkVersion 高於 24,則使用 FileProvider 授予訪問權限。

創建 xml 文件(路徑: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>

在AndroidManifest.xml中添加一個Provider

<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>

如果您使用的是 androidx,則 FileProvider 路徑應為:

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

並更換

Uri uri = Uri.fromFile(yourPath);

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

編輯:當您包含帶有 Intent 的 URI 時,請確保添加以下行:

intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM