如何将文件下载到本地下载文件夹?

时间:2018-09-17 00:54:48

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

我使用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);

2 个答案:

答案 0 :(得分:1)

根据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();

答案 1 :(得分:1)

对于Android Q和以前的Android Q(<= P),您需要使用ContentResolver将文件从存储位置复制到Download文件夹,该文件将显示在Download文件夹中

            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()
            }

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

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())
            }