Search code examples
androidnullpointerexceptionandroid-install-apkandroid-fileprovider

provider crashes when installing apk


I want to install an apk programmatically on Android 7. As I searched I have to use provider for that, but the app keeps crashing. I will be thankful if anyone could tell me why.

Android manifest: (inside application tag)

        <provider
            android:name=".GenericFileProvider"
            android:authorities="com.hamed.demo"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths"/>
        </provider>

code to install:

Intent install = new Intent(Intent.ACTION_VIEW);
install.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
install.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
// the following line crashes
Uri apkUri = FileProvider.getUriForFile(AppsList.this,
BuildConfig.APPLICATION_ID + ".provider", file);
install.setDataAndType(apkUri, downloadManager[0].getMimeTypeForDownloadedFile(downloadId));
startActivity(install);

provider_path.xml in res/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>

and my GenericFileProvider class is exatly form here

But when it reaches the line I added comment on, app crashes and I face this error:

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.hamed.demo, PID: 13090
                  java.lang.RuntimeException: Error receiving broadcast Intent { act=android.intent.action.DOWNLOAD_COMPLETE flg=0x10000011 pkg=com.hamed.demo (has extras) } in com.hamed.demo.AppsList$6@ce55de9
                      at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:1153)
                      at android.os.Handler.handleCallback(Handler.java:751)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      at android.os.Looper.loop(Looper.java:241)
                      at android.app.ActivityThread.main(ActivityThread.java:6274)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                   Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.XmlResourceParser android.content.pm.PackageItemInfo.loadXmlMetaData(android.content.pm.PackageManager, java.lang.String)' on a null object reference
                      at android.support.v4.content.FileProvider.parsePathStrategy(FileProvider.java:584)
                      at android.support.v4.content.FileProvider.getPathStrategy(FileProvider.java:558)
                      at android.support.v4.content.FileProvider.getUriForFile(FileProvider.java:400)
                      at com.hamed.demo.AppsList$6.onReceive(AppsList.java:217)
                      at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:1143)
                      at android.os.Handler.handleCallback(Handler.java:751) 
                      at android.os.Handler.dispatchMessage(Handler.java:95) 
                      at android.os.Looper.loop(Looper.java:241) 
                      at android.app.ActivityThread.main(ActivityThread.java:6274) 
                      at java.lang.reflect.Method.invoke(Native Method) 
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 

If that matters, the downloaded apk is located in downloads directory of internal storage of the device.

Thanks


Solution

  • Try to use this code

    File file = new File(
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
                    "app.apk");
    
            final Uri uri = Uri.fromFile(file);
            final String AUTHORITY = "com.company.app.update.provider";
    
            if (file.exists())
                file.delete();
    
            DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
            DownloadManager.Request request = new DownloadManager.Request(
                    Uri.parse("https://example.com/app.apk"));
            request.setDestinationUri(uri);
            downloadManager.enqueue(request);
    
            final BroadcastReceiver onComplete = new BroadcastReceiver() {
    
                public void onReceive(Context context, Intent intent) {
    
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    
                        Uri contentUri = FileProvider.getUriForFile(context, AUTHORITY, file);
                        Intent openFileIntent = new Intent(Intent.ACTION_VIEW)
                                .setDataAndType(contentUri, "application/vnd.android.package-archive")
                                .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                                .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(openFileIntent);
                        unregisterReceiver(this);
                        finish();
    
                    } else {
    
                        Intent openFileIntent = new Intent(Intent.ACTION_VIEW)
                                .setDataAndType(uri, "application/vnd.android.package-archive")
                                .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(openFileIntent);
                        unregisterReceiver(this);
                        finish();
                    }
                }
            };
    
            registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));