下载管理器无法下载 APK

Posted

技术标签:

【中文标题】下载管理器无法下载 APK【英文标题】:Download Manager cannot download APK 【发布时间】:2020-11-09 00:56:34 【问题描述】:

我正在尝试从服务器下载一个 apk 文件,但管理器写道等待连接,然后写道下载失败。但是这个文件可以通过 Chrome 或者 Retrofit + InputStream 下载。我也尝试下载 jpg 进行测试和所有作品

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)

【问题讨论】:

【参考方案1】:

使用此代码使用下载管理器下载 apk:

第 1 步:下载 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) 

        
    

第 2 步:下载后如果您想查看状态

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);
    

第 3 步:安装通知

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);
        
    
;

【讨论】:

以上是关于下载管理器无法下载 APK的主要内容,如果未能解决你的问题,请参考以下文章

IIS不能下载.apk文件

无法使用下载管理器在 android webview 中下载 excel

Android简易版图书管理系统

安卓手机不能安装apk软件这是啥情况?安装的时候提示没有可用程序打开本文件

我的安卓程序里的app-debug.apk安装包发到手机上可以下载安装后闪一下就

如何配置IIS使其支持APK文件的下载