简体   繁体   English

以编程方式从资产文件夹安装 APK 时出现解析错误

[英]Parse error when programmatically installing an APK from Assets Folder

I am trying to install apk programatically from assets folder, But Parse Error I have Googled for days and fine almost everything is fine but still error exists Here is my code我正在尝试以编程方式从 assets 文件夹安装 apk,但是 Parse Error 我已经用 Google 搜索了好几天,几乎一切都很好,但仍然存在错误这是我的代码

AndroidManifest.xml AndroidManifest.xml

   <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />

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

</application

file_provider_paths.xml file_provider_paths.xml

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

    <root-path name="root" path="." />

</paths>

MainActivity主要活动

private void installApk() {

        File f = new File("file:///android_asset/app.apk");
        f.setReadable(true, false);
        Uri apkUri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider",f);


        Intent installIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
        installIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        installIntent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        installIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(installIntent);

}

Checking Permission检查权限

    private void checkWriteExternalStoragePermission() {


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (!getPackageManager().canRequestPackageInstalls()) {
                startActivity(new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES).setData(Uri.parse(String.format("package:%s", getPackageName()))));
            }
        }


        if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            installApk();
        } else {
            installApk();
        }
    }

    private void requestWriteExternalStoragePermission() {
        if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this,  new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE);
        } else{
            ActivityCompat.requestPermissions(MainActivity.this,new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode==MY_PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE && grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
           
                installApk();
           

        } else {
            Toast.makeText(MainActivity.this, "Permission Not Granted.", Toast.LENGTH_SHORT).show();
        }
    }

File app.apk location : main->assets文件 app.apk 位置:main->assets

Please Note even I write file as请注意,即使我将文件写为

File f = new File(getFilesDir(), "app.apk");

and still parse error仍然解析错误

TargetSDK = 31目标SDK = 31

You cannot install APK directly from assets folder because that folder is not accessible to system's package installer.您不能直接从 assets 文件夹安装 APK,因为系统的软件包安装程序无法访问该文件夹。 You must first copy that APK to a shared folder like public documents directory and then pass the URI of file from that directory to intent您必须首先将该 APK 复制到公共文档目录等共享文件夹,然后将该目录中的文件 URI 传递给意图

val publicDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)

Edit: Steps to copy file to external storage:编辑:将文件复制到外部存储的步骤:

val file = new File("file:///android_asset/app.apk");
val publicDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)
val destinationAPKFile = File(publicDir, "your_apk_name.apk")
try {
      FileUtils.copyFile(file, destinationAPKFile)
     } 
catch (e: Exception) 
{
    e.printStackTrace();
}

Then you can use the URI of destinationAPKFile and install APK as you are doing.然后您可以使用destinationAPKFile 的URI 并照常安装APK。

Edit 2: In java编辑2:在java中

File file = new File("file:///android_asset/app.apk");
File publicDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
File destinationAPKFile = File(publicDir, "your_apk_name.apk");
try {
      FileUtils.copyFile(file, destinationAPKFile)
     } 
catch (Exception e) 
{
    e.printStackTrace();
}

Edit 3: To use FileUtils.copyTo, add following dependency to your app level gradle编辑 3:要使用 FileUtils.copyTo,请将以下依赖项添加到您的应用级别 gradle

implementation group: 'commons-io', name: 'commons-io', version: '2.6'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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