美文网首页
Android实现保存图片和视频到系统相册

Android实现保存图片和视频到系统相册

作者: 壹元伍角叁分 | 来源:发表于2021-09-08 20:31 被阅读0次

1、保存类

object FileSaveUtils {
    /**
     * 保存图片
     * @param context
     * @param file
     */
    fun saveImage(context: Context, file: File) {
        val localContentResolver = context.contentResolver
        val localContentValues = getImageContentValues(file, System.currentTimeMillis())
        localContentResolver.insert(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            localContentValues
        )

        val localIntent = Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE")
        val localUri = Uri.fromFile(file)
        localIntent.data = localUri
        context.sendBroadcast(localIntent)
    }

    private fun getImageContentValues(
        paramFile: File,
        paramLong: Long
    ): ContentValues {
        val localContentValues = ContentValues()
        localContentValues.put("title", paramFile.name)
        localContentValues.put("_display_name", paramFile.name)
        localContentValues.put("mime_type", "image/jpeg")
        localContentValues.put("datetaken", paramLong)
        localContentValues.put("date_modified", paramLong)
        localContentValues.put("date_added", paramLong)
        localContentValues.put("orientation", Integer.valueOf(0))
        localContentValues.put("_data", paramFile.absolutePath)
        localContentValues.put("_size", paramFile.length())
        return localContentValues
    }

    /**
     * 保存视频
     * @param context
     * @param file
     */
    fun saveVideo(context: Context, file: File) {
        //是否添加到相册
        val localContentResolver = context.contentResolver
        val localContentValues = getVideoContentValues(file, System.currentTimeMillis())
        val localUri = localContentResolver.insert(
            MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
            localContentValues
        )
        context.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, localUri))
    }

    private fun getVideoContentValues(
        paramFile: File,
        paramLong: Long
    ): ContentValues {
        val localContentValues = ContentValues()
        localContentValues.put("title", paramFile.name)
        localContentValues.put("_display_name", paramFile.name)
        localContentValues.put("mime_type", "video/mp4")
        localContentValues.put("datetaken", paramLong)
        localContentValues.put("date_modified", paramLong)
        localContentValues.put("date_added", paramLong)
        localContentValues.put("_data", paramFile.absolutePath)
        localContentValues.put("_size", paramFile.length())
        return localContentValues
    }
}

2、下载类

class AndroidDownloadManager(private val context: Context, private val url: String) {
    private var downloadManager: DownloadManager? = null
    private var downloadId: Long? = 0L
    private val name: String
    private var path: String = ""

    val listener: AndroidDownloadManagerListener? = null

    init {
        name = getFileNameByUrl(url)
    }

    /**
     * 开始下载
     */
    fun download() {
        val request = DownloadManager.Request(Uri.parse(url))
        //移动网络情况下是否允许漫游
        request.setAllowedOverRoaming(false)
        //在通知栏中显示,默认就是显示的
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE)
        request.setTitle(name)
        request.setDescription("文件正在下载中......")
        request.setVisibleInDownloadsUi(true)

        //设置下载的路径
        val file = File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), name)
        request.setDestinationUri(Uri.fromFile(file))
        path = file.absolutePath

        //获取DownloadManager
        if (downloadManager == null) {
            downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
        }
        //将下载请求加入下载队列,加入下载队列后会给该任务返回一个long型的id,通过该id可以取消任务,重启任务、获取下载的文件等
        if (downloadManager != null) {
            listener?.onPrepare()
            downloadId = downloadManager?.enqueue(request)
        }

        //注册广播接收者,监听下载状态
        context.registerReceiver(
            receiver,
            IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)
        )
    }

    //广播监听下载的各个状态
    private val receiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            val query = DownloadManager.Query()
            downloadId?.run {
                //通过下载的id查找
                query.setFilterById(this)
                val cursor = downloadManager!!.query(query)
                if (cursor!!.moveToFirst()) {
                    val status =
                        cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS))
                    when (status) {
                        //下载暂停
                        DownloadManager.STATUS_PAUSED -> {

                        }
                        //下载延迟
                        DownloadManager.STATUS_PENDING -> {

                        }
                        //正在下载
                        DownloadManager.STATUS_RUNNING -> {

                        }
                        //下载完成
                        DownloadManager.STATUS_SUCCESSFUL -> {
                            listener?.onSuccess(path)
                            cursor.close()
                            unregisterBroadcastReceiver()

                        }
                        //下载失败
                        DownloadManager.STATUS_FAILED -> {
                            listener?.onFailed(Exception("下载失败"))
                            cursor.close()
                            unregisterBroadcastReceiver()
                        }
                    }
                }
            }
        }
    }


    private fun unregisterBroadcastReceiver() {
        context.unregisterReceiver(receiver)
    }

    /**
     * 通过URL获取文件名
     *
     * @param url
     * @return
     */
    private fun getFileNameByUrl(url: String): String {
        var filename = url.substring(url.lastIndexOf("/") + 1)
        filename = filename.substring(
            0,
            if (filename.indexOf("?") == -1) filename.length else filename.indexOf("?")
        )
        return filename
    }
}

interface AndroidDownloadManagerListener {
    fun onPrepare()

    fun onSuccess(path: String)

    fun onFailed(throwable: Throwable)
}

相关文章

网友评论

      本文标题:Android实现保存图片和视频到系统相册

      本文链接:https://www.haomeiwen.com/subject/gpqbwltx.html