P1NG2WIN
P1NG2WIN

Reputation: 864

Download Manager cannot download APK

I'm trying to download an apk file from the server, but the manager writes waiting for a connection and then writes that the download failed. But this file can be downloaded via Chrome or Retrofit + InputStream. Also i tried to download jpg for test and all works

const val APK_NAME = "test-apk.apk"

val downloadRequest = DownloadManager
    .Request(Uri.parse(remoteUpdateConf.newAppStoreUrl))
    .setAllowedNetworkTypes(
        DownloadManager.Request.NETWORK_WIFI
            or DownloadManager.Request.NETWORK_MOBILE
    )
    .setAllowedOverRoaming(false)
    .setTitle(getString(R.string.update_downloading))
    .setNotificationVisibility(
        DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED
    )
    .setShowRunningNotification(true)
    .setVisibleInDownloadsUi(true)
    .setMimeType("application/vnd.android.package-archive")
    .setDestinationInExternalPublicDir(
        Environment.DIRECTORY_DOWNLOADS,
        APK_NAME
    )

downloadManager.enqueue(downloadRequest)

Upvotes: 0

Views: 416

Answers (1)

Vela
Vela

Reputation: 97

Use this code for download apk using Download Manager:

step 1: Download Apk:

private void DownloadFile(String urlPath, String fileName) {
        try {
            String OutputDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();
            outputFile = new File(OutputDir, fileName);
            if (outputFile.exists()) {
                outputFile.delete();
            }
            OutputFullPATH = outputFile.toString();
            // Download File from url
            Uri uri = Uri.parse(urlPath + fileName);

            DownloadManager.Request request = new DownloadManager.Request(uri);
            request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
            request.setTitle("Application Name apk download");
            request.setDescription("Downloading Application Name apk");
            //Setting the location to which the file is to be downloaded
            request.allowScanningByMediaScanner();
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
            //request.setDestinationInExternalFilesDir(UserAuthenticationActivity.this, Environment.DIRECTORY_DOWNLOADS, fileName + System.currentTimeMillis());


            DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
            DownloadID = downloadManager.enqueue(request);
            IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
            registerReceiver(receiver, filter);
            //return output;
        } catch (Exception e) {

        }
    }

step 2: After Download if you want to check status

public int getDownloadedStatus() {
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(DownloadID);
        DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        Cursor cursor = downloadManager.query(query);

        if (cursor.moveToFirst()) {
            int columnOndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
            int status = cursor.getInt(columnOndex);
            return status;
        }
        return DownloadManager.ERROR_UNKNOWN;
    }

public void CancelDownload() {
    DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
    downloadManager.remove(DownloadID);
    }

step 3: Notification for Install

private BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            ShowProgressBar(false);
            Long DownloadedID = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            if (DownloadedID == DownloadID) {
                if (getDownloadedStatus() == DownloadManager.STATUS_SUCCESSFUL) {
                    Toast.makeText(context, "Download Completed", Toast.LENGTH_LONG).show();
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        Uri contentUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", new File(OutputFullPATH));
                        Intent openFileIntent = new Intent(Intent.ACTION_VIEW);
                        openFileIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        openFileIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        openFileIntent.setData(contentUri);
                        startActivity(openFileIntent);
                        unregisterReceiver(this);
                        finish();
                    } else {
                        Intent install = new Intent(Intent.ACTION_VIEW);
                        install.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        install.setDataAndType(Uri.parse(OutputFullPATH),
                                "application/vnd.android.package-archive");
                        startActivity(install);
                        unregisterReceiver(this);
                        finish();
                    }
                } else {
                    Toast.makeText(context, "Download Not Completed", Toast.LENGTH_LONG).show();
                }
            }
        } catch (Exception ex) {
            CrashAnalytics.CrashReport(ex);
        }
    }
};

Upvotes: 3

Related Questions