【问题标题】:How do i download files to the local downloads folder?如何将文件下载到本地下载文件夹?
【发布时间】:2019-02-20 21:31:11
【问题描述】:

我使用 WebView 启用了文件的下载设置。我正在使用 DownloadManager 保存文件。但是这些文件不会出现在本地下载目录中。我下载的文件都保存在这里。

> file/storage/emulated/0/Android/data/com.myapp/files/x.mp3

我已经尝试了很多。但不知何故,它没有下载到本地下载文件夹中。我该怎么办?

我的代码

String string = String.valueOf((URLUtil.guessFileName(url, contentDisposition, mimeType)));

            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
            request.setMimeType(mimeType);
            String cookies = CookieManager.getInstance().getCookie(url);

            request.addRequestHeader("cookie", cookies);
            request.addRequestHeader("User-Agent", userAgent);
            request.setTitle("test17");
            request.setDescription("Downloading file...");
            request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType));
            request.allowScanningByMediaScanner();

            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            request.setDestinationInExternalFilesDir(getContext(), DIRECTORY_DOWNLOADS ,  string);
            DownloadManager dm = (DownloadManager)getActivity().getSystemService(DOWNLOAD_SERVICE);
            dm.enqueue(request);

【问题讨论】:

  • 使用Prdownloader库..易于使用和集成

标签: android android-studio android-download-manager


【解决方案1】:

对于 Android Q 和之前的 Android Q (

            val file = File(filePath)
            val manager =
                (context.getSystemService(Activity.DOWNLOAD_SERVICE) as DownloadManager)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {                 
                val resolver = context.contentResolver
                val contentValues = ContentValues().apply {
                    put(MediaStore.Files.FileColumns.DISPLAY_NAME, file.name)
                    put(MediaStore.Files.FileColumns.MIME_TYPE, "application/pdf")
                    put(
                        MediaStore.Files.FileColumns.RELATIVE_PATH,
                        Environment.DIRECTORY_DOWNLOADS
                    )
                }

                val uri = resolver.insert(
                    MediaStore.Downloads.EXTERNAL_CONTENT_URI,
                    contentValues
                )

                val fos = resolver.openOutputStream(uri!!)
                val fin = FileInputStream(file)
                fin.copyTo(fos!!, 1024)
                fos.flush()
                fos.close()
                fin.close()
            } else {
                var destination =
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                        .toString() + "/" + file.name

                val uri = Uri.parse("file://$destination")
                val fos = context.contentResolver.openOutputStream(uri!!)
                val fin = FileInputStream(file)
                fin.copyTo(fos!!, 1024)
                fos.flush()
                fos.close()
                fin.close()
            }

仅显示带有“已下载”文件名的通知后,会打开系统“下载”视图

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val name = "Some Channel"
            val descriptionText = "Default channel"
            val importance = NotificationManager.IMPORTANCE_DEFAULT
            val channel = NotificationChannel(DEFAULT_CHANNEL, name, importance).apply {
                description = descriptionText
            }
            // Register the channel with the system
            val notificationManager: NotificationManager =
                context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(channel)
        }

            val intent = Intent()
            intent.action = DownloadManager.ACTION_VIEW_DOWNLOADS
            val pendingIntent: PendingIntent = PendingIntent.getActivity(context, 0, intent, 0)

            val builder = NotificationCompat.Builder(context, DEFAULT_CHANNEL)
                .setSmallIcon(R.drawable.save_icon)
                .setContentTitle("123file")
                .setContentText("File succesfully exported")
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                // Set the intent that will fire when the user taps the notification
                .setContentIntent(pendingIntent)
                .setAutoCancel(true)

            with(NotificationManagerCompat.from(context)) {
                // notificationId is a unique int for each notification that you must define
                notify(135, builder.build())
            }

【讨论】:

    【解决方案2】:

    根据documentation有2种外部存储

    • 公共文件:应该免费提供给其他应用程序和用户的文件。当用户卸载您的应用程序时,这些文件应该仍然可供用户使用。例如,您的应用拍摄的照片或其他下载的文件应保存为公共文件。
    • 私人文件:属于您的应用程序的文件,在用户卸载您的应用程序时将被删除。尽管这些文件在技术上可供用户和其他应用访问,因为它们位于外部存储上,但它们不会为您的应用之外的用户提供价值。

    在您的代码中,调用DownloadManager.Request.setDestinationInExternalFilesDir() 等同于调用Context.getExternalFilesDir() 将获得私有文件目录。

    如果要将下载的文件保存到下载目录,请使用DownloadManager.Request.setDestinationInExternalPublicDir()

    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "x.mp3");
    // call allowScanningByMediaScanner() to allow media scanner to discover your file
    request.allowScanningByMediaScanner();
    

    【讨论】:

    • 非常感谢您的回答。但是这段代码对我也不起作用。下载开始时,应用程序停止。我在一个片段中使用这个片段。知道问题出在哪里吗?
    • @BeginnerDeveloper 你能发布一个日志,当你的应用程序停止时显示错误?
    • 因为问题看不到日志猫。添加此代码后,应用程序将在下载时停止。 --> " request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS , string);"不过用的时候没问题。 --> " request.setDestinationInExternalFilesDir(getContext(), DIRECTORY_DOWNLOADS , string);"
    • @BeginnerDeveloper 如果你用我建议的代码替换了你的代码,但你的应用程序停止了,那么我不知道发生了什么,因为你说没有日志,你确定吗?你用什么标签来找到你的日志?
    • 请检查我添加了一个 logcat。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-28
    • 2020-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多