조현욱
조현욱

Reputation: 79

Installing an APK results in a parse error

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?

Upvotes: 5

Views: 2509

Answers (1)

Matin Zadeh Dolatabad
Matin Zadeh Dolatabad

Reputation: 1017

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

Upvotes: 1

Related Questions