首页 > 解决方案 > 从 kotlin Android 中的 url 下载视频?

问题描述

我想从 URL 下载视频。但它给出了一个错误:

E/ContentProviderNative:来自 {P:12600;U:11003} 的 onTransact 错误 2019-01-14 11:54:35.423 3518-22398/?E/DatabaseUtils:向包裹 java.lang.IllegalArgumentException 写入异常:未知 URI:在 com.android.providers.downloads.DownloadProvider.query(DownloadProvider.java:914) 上的 android.content 上的 content://downloads/public_downloads/6796。 ContentProvider.query(ContentProvider.java:1138) 在 android.content.ContentProvider.query(ContentProvider.java:1230) 在 android.content.ContentProvider$Transport.query(ContentProvider.java:251) 在 android.content.ContentProviderNative.onTransact (ContentProviderNative.java:112) 在 android.os.Binder.execTransact(Binder.java:752) 在此处输入图像描述

下载视频文件的代码如下: private var downloadReference: Long = 0 private lateinit var downloadManager: DownloadManager

private val receiver = object : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        val action = intent.action
        if (action == DownloadManager.ACTION_DOWNLOAD_COMPLETE) {
            val downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1)
            if (downloadId != downloadReference) {
                context.unregisterReceiver(this)
                return
            }
            val query = DownloadManager.Query()
            query.setFilterById(downloadReference)
            val cursor = downloadManager.query(query)
            cursor?.let {
                if (cursor.moveToFirst()) {
                    val columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)
                    if (DownloadManager.STATUS_SUCCESSFUL == cursor.getInt(columnIndex)) {
                        var localFile = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI))

                        if (localFile.contains("file:///")) {
                            localFile = localFile.removePrefix("file:///").substringBeforeLast(File.separator)
                        }
                        //context.toast(context.resources.getString(R.string.saved, localFile), Toast.LENGTH_LONG)

                    } else if (DownloadManager.STATUS_FAILED == cursor.getInt(columnIndex)) {
                      //  val message = context.resources.getString("error : ", cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_REASON)))
                        //context.toast(message, Toast.LENGTH_LONG)
                    }
                }
                cursor.close()
            }

            context.unregisterReceiver(this)

        }
    }
}

/////////// New Testing........
fun downloadFile(url: String, mimeType: String? = null) {

    val guessFileName = URLUtil.guessFileName(url, null, mimeType)
    System.out.println("LLLLLLLLLLLLLLLLLLL2 ");
   // Timber.d("mimeType -> $mimeType guessFileName -> $guessFileName created by url -> $url")

    val context = this

    downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager

    val downloadUri = Uri.parse(url)

    val request = DownloadManager.Request(downloadUri)
    request.apply {
        setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE or DownloadManager.Request.NETWORK_WIFI)
        //setAllowedOverRoaming(true)
        setTitle(guessFileName)
        setDescription(guessFileName)
        setVisibleInDownloadsUi(true)
        allowScanningByMediaScanner()
        setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)

        //request.setDestinationUri(Uri.fromFile(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)))
        setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES, guessFileName)

        context.registerReceiver(receiver, IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE))

        downloadReference = downloadManager.enqueue(this)
    }
    System.out.println("LLLLLLLLLLLLLLLLLLL23 ");
}

标签: androidkotlin

解决方案


使用下面的库:

  implementation 'com.mindorks.android:prdownloader:0.5.0'

从给定 url 下载视频的代码如下:

 fun downfile(urll:String,fileName:String){



    if(!isFilePresent(fileName)) {
        var mFile2: File? = File(Environment.getExternalStorageDirectory(), "WallpapersBillionaire")
        System.out.println("File Foond " + mFile2!!.absolutePath)
        var mFile3: File? = File(Environment.getExternalStorageDirectory(), "WallpapersBillionaire")

        var downloadId = PRDownloader.download(urll, mFile2!!.absolutePath, fileName)
                .build()
                .setOnStartOrResumeListener(object : OnStartOrResumeListener {
                    override fun onStartOrResume() {
                        System.out.println("??????????????????? start")
                    }
                })
                .setOnPauseListener(object : OnPauseListener {
                    override fun onPause() {
                    }
                })
                .setOnCancelListener(object : OnCancelListener {
                    override fun onCancel() {
                    }
                })
                .setOnProgressListener(object : OnProgressListener {
                    override fun onProgress(progress: Progress) {
                        circlePeView.visibility = View.VISIBLE

                        var per = (progress.currentBytes.toFloat() / progress.totalBytes.toFloat()) * 100.00
                        //var perint = per*100
                        System.out.println("::??????????????????? Per : " + per + " ?? : " + progress.currentBytes + " ?? : " + progress.totalBytes)

                        circlePeView.setProgress(per.toInt())
                    }
                })
                .start(object : OnDownloadListener {
                    override fun onDownloadComplete() {

                        circlePeView.visibility = View.GONE
                        circlePeView.setProgress(0)
                        prefs = getSharedPreferences(PREFS_FILENAME, 0)

                        val editor = prefs!!.edit()
                        editor.putString(wall, "WallpapersBillionaire/" + fileName)
                        editor.apply()

                        try {
                            val myWallpaperManager = WallpaperManager.getInstance(applicationContext)
                            try {
                                myWallpaperManager.setResource(R.raw.wallp)
                            } catch (e: IOException) {
                                // TODO Auto-generated catch block
                                e.printStackTrace()
                            }

                            val intent = Intent(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER)
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                            intent.putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT,
                                    ComponentName(this@AnimattedViewpagerActivity, VideoLiveWallpaperService::class.java))
                            startActivity(intent)
                        } catch (e: Exception) {
                            val intent = Intent()
                            intent.setAction(WallpaperManager.ACTION_LIVE_WALLPAPER_CHOOSER)
                            try {
                                startActivity(intent)
                            }catch (e2: java.lang.Exception){
                                Toast.makeText(applicationContext,"Please long click on your home screen. Select Video Live Wallpapers form thier. Thanks",Toast.LENGTH_LONG).show()
                            }

                        }
                        System.out.println("??????????????????? complete")
                    }

                    override fun onError(error: Error) {
                        System.out.println("??????????????????? error " + error)
                    }
                })
        System.out.println("??????????????????? called")
    }else{
        System.out.println("File Foond ")
        circlePeView.visibility = View.GONE
        circlePeView.setProgress(0)
        prefs = getSharedPreferences(PREFS_FILENAME, 0)

        val editor = prefs!!.edit()
        editor.putString(wall, "WallpapersBillionaire/" + fileName)
        editor.apply()

        try {
            val myWallpaperManager = WallpaperManager.getInstance(applicationContext)
            try {
                myWallpaperManager.setResource(R.raw.wallp)
            } catch (e: IOException) {
                // TODO Auto-generated catch block
                e.printStackTrace()
            }

            val intent = Intent(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            intent.putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT,
                    ComponentName(this@AnimattedViewpagerActivity, VideoLiveWallpaperService::class.java))
            startActivity(intent)
        } catch (e: Exception) {
            val intent = Intent()
            intent.setAction(WallpaperManager.ACTION_LIVE_WALLPAPER_CHOOSER)

            try {
                startActivity(intent)
            }catch (e2: java.lang.Exception){
                Toast.makeText(applicationContext,"Please long click on your home screen. Select Video Live Wallpapers form thier. Thanks",Toast.LENGTH_LONG).show()
            }

        }
        System.out.println("??????????????????? complete")
    }
}

推荐阅读