从 Android 应用程序下载文件时出现问题

Trouble with dowload file from Android app

需要通过应用程序从网络服务器下载文件,但文件没有加载,这是我使用的代码:

 manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
 Uri uri = Uri.parse("https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf");
 DownloadManager.Request request = new DownloadManager.Request(uri);
 request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
 long reference = manager.enqueue(request);

在清单中,我有这些权限:

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.WAKE_LOCK"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.ACCESS_DOWNLOAD_MANAGER"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
    <uses-permission android:name="android.permission.REQUEST_DELETE_PACKAGES"/>

文件已在设备上创建,但标记“在队列中”,没有进一步发生。

如果您只是在浏览器中点击链接,则下载不会出现问题。

通过设置 - 还检查了对设备内存的访问。

我哪里错了?

请试试这个class代码方式可能对你有帮助

public class DownloadHelper {
    private long downloadReference = 0
    private DownloadManager downloadManager;
    DownloadCompleteListener completeListener= null;
    
    public interface DownloadCompleteListener{
        void ondownloadComplete(String name,String path,Uri uri);
        void ondownloadFailled(String error);
    }


    private BroadcastReceiver receiver = new BroadcastReceiver () {
        
        @Override
        void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action == DownloadManager.ACTION_DOWNLOAD_COMPLETE) {
                long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
                if (downloadId != downloadReference) {
                    context.unregisterReceiver(this);
                    return;
                }
                DownloadManager.Query query = new DownloadManager.Query();
                query.setFilterById(downloadReference);
                Cursor cursor = downloadManager.query(query);
                if(cursor != null){
                    if (cursor.moveToFirst()) {
                        int columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
                        if (DownloadManager.STATUS_SUCCESSFUL == cursor.getInt(columnIndex)) {
                            String localFile = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                            String localName = localFile.substring(localFile.lastIndexOf("/")+1);//cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME))
                            completeListener.ondownloadComplete(localName,localFile,null);
                        } else if (DownloadManager.STATUS_FAILED == cursor.getInt(columnIndex)) {
                            completeListener.ondownloadFailled(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_REASON)));
                        }
                    }else{
                        completeListener.ondownloadFailled("Download cancelled or failled");
                    }
                    cursor.close();
                }else{
                    completeListener.ondownloadFailled("Download cancelled or failled");
                }
                context.unregisterReceiver(this);
            }
        }
    };

    public String getallreadyfile(String name){
        return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                .getAbsolutePath().toString() + "/" + name;
    }

    public void downloadFile(Context context,String url,String mimeType,DownloadCompleteListener completeListener) {
        this.completeListener = completeListener;
        String guessFileName = URLUtil.guessFileName(url, null, mimeType);
        if(url == null || url.isEmpty()){            
            return;
        }
        String allreadyfile = getallreadyfile(guessFileName);
        File applictionFile = new File(allreadyfile);
        if(isAllreadyAvailabel(context,applictionFile)){
            completeListener.ondownloadComplete(applictionFile.getName(),applictionFile.getAbsolutePath(),null);
            return
        }

        downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        Uri downloadUri = Uri.parse(url);
        DownloadManager.Request request = new DownloadManager.Request(downloadUri);
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE).setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
        //setAllowedOverRoaming(true)
//            setTitle(guessFileName)
//            setDescription(guessFileName)
//            setVisibleInDownloadsUi(true)
        request.allowScanningByMediaScanner();
//            setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)

        //request.setDestinationUri(Uri.fromFile(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)))
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, guessFileName);

        context.registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

        downloadReference = downloadManager.enqueue(request);
    }

    public boolean isAllreadyAvailabel(Context context,File applictionFile){
        if(applictionFile.canRead() && applictionFile.length()>0) {
            return true;
        }else{
            try {
                File file = new File(applictionFile.getAbsolutePath());
                if (file.exists()) {
                    file.delete();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }
}