如何使用DownloadManager停止在android中下载文件?

Wun*_*Wun 2 android gridview download android-download-manager

我从SD卡读取文件,并在Gridview上显示.

当我从中选择项目Gridview并获取position项目时.

我点击下载按钮,它将下载该项目.

我使用时如何停止项目下载downloadManager

代码是下载按钮,如下所示:

FileNode file = mFileList.get(temp_position) ;//Get the item I have select from Gridview

                                final String filename = file.mName.substring(file.mName.lastIndexOf("/") + 1) ;
                                final String urlString = "http://" + mIp + file.mName ;

                                String serviceString = Context.DOWNLOAD_SERVICE ;
                                DownloadManager downloadManager ;
                                downloadManager = (DownloadManager) getActivity().getSystemService(
                                        serviceString) ;

                                Uri uri = Uri.parse(urlString) ;
                                DownloadManager.Request request = new Request(uri) ;
                                request.setTitle(filename) ;
                                request.setDescription(urlString) ;

                                String ext = filename.substring(filename.lastIndexOf(".") + 1)
                                        .toLowerCase(Locale.US) ;
                                String mimeType = MimeTypeMap.getSingleton()
                                        .getMimeTypeFromExtension(ext) ;

                                Log.i("MIME", ext + "  ==>  " + mimeType) ;

                                if (mimeType != null) {
                                    request.setMimeType(mimeType) ;
                                }
                                request.allowScanningByMediaScanner() ;

                                request.setNotificationVisibility(Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED) ;

                                request.setDestinationInExternalPublicDir(MainActivity.sAppName, filename) ;

                                downloadManager.enqueue(request) ;
Run Code Online (Sandbox Code Playgroud)

如何在下载文件时停止项目下载?

A--*_*--C 9

DownloadManager#enqueue返回long表示id下载发生的代码.将其保存long在变量中.

然后,如果您需要取消下载,请DownloadManager#remove()在那么长时间内调用传递.

例如

//start a download
long id = downloadManager.enqueue(request);

//stop a download
downloadManager.remove(id);
Run Code Online (Sandbox Code Playgroud)