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

时间:2015-04-25 09:02:46

标签: android android-download-manager

我是Android的新手。我的申请中有一项要求。我需要使用Downloadmanager从服务器下载音频文件,.mp3文件,并将其保存在我的设备的特定文件夹中。请帮我完成这项任务

提前致谢

2 个答案:

答案 0 :(得分:0)

Android 2.3中引入的Android DownloadManager。 (API 9)是一种系统服务,允许在后台处理长时间运行的HTTP下载,并在下载完成后通过广播接收器通知触发应用程序。

提供者: http://www.vogella.com/blog/2011/06/14/android-downloadmanager-example/

答案 1 :(得分:0)

请看下面的代码

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

}

希望能帮到你