Installing an APK results in a parse error

╄→尐↘猪︶ㄣ 提交于 2019-12-12 19:24:12

问题


I created an app-debug.apk file in /sdcard/Download

I have this code:

@Override
public void onClick(View v){
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/sdcard/Download/" + "app-debug.apk")),
    "application/vnd.android.package-archive");
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
}

I am getting this error:

Parse error

There was a problem parsing the package.

How can I modify it programmatically without getting this error?


回答1:


For Android N and above you should use FileProvider like this :

        Uri apkUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", file);
        Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
        intent.setData(apkUri);
        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);

In your AndroidManifest.xml :

    <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/provider_paths" />
    </provider>
    </application>

Then create file named provider_paths.xml under res/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="." />
</paths>

Don't forget to add permission in manifest also:

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


来源:https://stackoverflow.com/questions/36783585/installing-an-apk-results-in-a-parse-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!