简体   繁体   English

使用下载管理器从服务器下载音频文件

[英]Download Audio File from server using Download Manager

I am newbie in Android.我是安卓新手。 I have one requirement in my application.我的申请中有一项要求。 I need to download audio files, .mp3 files from server using Downloadmanager and save it in specific folder in my device.我需要使用 Downloadmanager 从服务器下载音频文件、.mp3 文件并将其保存在我设备的特定文件夹中。 Please help me to complete this task请帮我完成这个任务

Thanks in advance提前致谢

The Android DownloadManager introduced in Android 2.3. Android 2.3 中引入的 Android DownloadManager。 (API 9) is a system service which allows to handle long-running HTTP downloads in the background and notify the triggering application via a broadcast receiver once the download is finished. (API 9) 是一种系统服务,它允许在后台处理长时间运行的 HTTP 下载,并在下载完成后通过广播接收器通知触发应用程序。

Courtesy: http://www.vogella.com/blog/2011/06/14/android-downloadmanager-example/礼貌: http : //www.vogella.com/blog/2011/06/14/android-downloadmanager-example/

Please see the below code请看下面的代码

object DownloadHelper {
    private var downloadReference: Long = 0
    private lateinit var downloadManager: DownloadManager
    var completeListener:DownloadCompleteListener?= null
    interface DownloadCompleteListener{
        fun ondownloadComplete(name:String,path:String?,uri:Uri?)
        fun ondownloadFailled(error:String)
    }


    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)
                if(cursor != null){
                    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))
                                var localName = localFile.substring(localFile.lastIndexOf("/")+1)//cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME))
                                completeListener!!.ondownloadComplete(localName,localFile,null)
                            } else if (DownloadManager.STATUS_FAILED == cursor.getInt(columnIndex)) {
                                completeListener!!.ondownloadFailled(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_REASON)))
                            }
                        }else{
                            completeListener!!.ondownloadFailled("Download cancelled or failled")
                    }
                        cursor.close()
                    }
                }else{
                    completeListener!!.ondownloadFailled("Download cancelled or failled")
                }
                context.unregisterReceiver(this)
            }
        }
    }

    fun getAudiofilePath(name:String):String{
        return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC)
            .getAbsolutePath().toString() + "/" + name
    }

    fun downloadFile(context: Context,title: String,url: String?,uristring: Uri?, mimeType: String? = null,completeListener: DownloadCompleteListener) {
        this.completeListener = completeListener
        val guessFileName = URLUtil.guessFileName(url, null, mimeType)
        if(url == null || url.isEmpty()){
            completeListener!!.ondownloadComplete(title,url,uristring)
            return
        }
        var audiofilepath = getAudiofilePath(guessFileName);
        var applictionFile = File(audiofilepath);
        if(isAllreadyAvailabel(context,applictionFile)){
            completeListener!!.ondownloadComplete(applictionFile.name,applictionFile.absolutePath,null)
            return
        }

        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_MUSIC, guessFileName)

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

            downloadReference = downloadManager.enqueue(this)
        }
    }

    fun getAllreadyDownloadAudioPath(context: Context,url:String,mimeType: String? = null):String {
        val guessFileName = URLUtil.guessFileName(url, null, mimeType)
        var audiofilepath = getAudiofilePath(guessFileName);
        var applictionFile = File(audiofilepath);
        if(isAllreadyAvailabel(context,applictionFile)){
            return applictionFile.absolutePath
        }
        return ""
    }

    fun downloadVideo(context: Context,title: String, urlFromServer: String?, mimeType: String? = null,completeListener: DownloadCompleteListener) {
        this.completeListener = completeListener
        val guessFileName = URLUtil.guessFileName(urlFromServer, null, mimeType)
        if(urlFromServer == null || urlFromServer.isEmpty()){
            completeListener!!.ondownloadComplete(title,urlFromServer, Uri.EMPTY)
            return
        }

        val directory = File(Environment.getExternalStorageDirectory().toString() + File.separator + "zingsharetemp")
        directory.mkdirs()
//        var audiofilepath = getAudiofilePath(guessFileName);
        var applicationFile = File(directory!!.path+'/'+guessFileName);
        if(isAllreadyAvailabel(context,applicationFile)){
            completeListener!!.ondownloadComplete(applicationFile.name,applicationFile.absolutePath,null)
            return
        }
        downloadManager = context!!.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
        val downloadUri = Uri.parse(urlFromServer)
        val request = DownloadManager.Request(downloadUri)
        request.apply {
            setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE or DownloadManager.Request.NETWORK_WIFI)
            allowScanningByMediaScanner()
            setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, guessFileName)
            context.registerReceiver(receiver, IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE))
            downloadReference = downloadManager.enqueue(this)
        }
    }

    fun isAllreadyAvailabel(context: Context,applictionFile:File):Boolean{
        if(applictionFile.canRead() && applictionFile.length()>0) {
            return true
        }else{
            deleteFiles(applictionFile.absolutePath)
        }
        return false
    }
}


fun download(){

   DownloadHelper.downloadFile(context,
                title,
                url,
                uristring,
                "audio/*",
                object : DownloadHelper.DownloadCompleteListener {
                    override fun ondownloadComplete(name: String, path: String?, uristring: Uri?) {
                       
                    }

                    override fun ondownloadFailled(error: String) {
                     
                    }
                })

}

hope it will help you希望它会帮助你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM