簡體   English   中英

如何將文件下載到本地下載文件夾?

[英]How do i download files to the local downloads folder?

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

對於 Android Q 和之前的 Android Q (<= P),您需要使用 ContentResolver 將文件從存儲位置復制到下載文件夾,該文件將出現在下載文件夾中

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

根據文檔,有兩種類型的外部存儲

  • 公共文件:應該可供其他應用程序和用戶免費使用的文件。 當用戶卸載您的應用程序時,這些文件應該仍然可供用戶使用。 例如,您的應用程序捕獲的照片或其他下載的文件應保存為公共文件。
  • 私人文件:理所當然地屬於您的應用程序並且在用戶卸載您的應用程序時將被刪除的文件。 盡管這些文件在技術上可由用戶和其他應用訪問,因為它們位於外部存儲中,但它們不會為應用之外的用戶提供價值。

在您的代碼中,調用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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM