【问题标题】:Trouble with dowload file from Android app从 Android 应用程序下载文件的问题
【发布时间】:2021-12-06 07:36:32
【问题描述】:

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

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

文件已在设备上创建,但标记为“在队列中”并且没有进一步的反应。

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

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

我哪里做错了?

【问题讨论】:

    标签: java android android-studio download


    【解决方案1】:

    请尝试此类代码方式可能会对您有所帮助

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

    【讨论】:

    • 谢谢,课程效果很好。运行类:``` DownloadHelper downloadHelper = new DownloadHelper(); DownloadHelper.DownloadCompleteListener downloadCompleteListener = new DownloadHelper.DownloadCompleteListener() { @Override public void ondownloadComplete(String name, String path, Uri uri) { } @Override public void ondownloadFailled(String error) { } }; downloadHelper.downloadFile(getApplicationContext(),"server/…); ```
    猜你喜欢
    • 1970-01-01
    • 2016-10-07
    • 1970-01-01
    • 2021-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-06
    相关资源
    最近更新 更多