fun saveFiletoAlbum( activity: Activity?, fileType: Int, resourceName: String ) { try { val contentValues = ContentValues() var destPathUnderQ = "" findMimeTypeBySuffix(activity, fileType, resourceName)?.let { contentValues.put("mime_type", it) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { val folderName = Environment.DIRECTORY_DCIM + File.separator + getString(R.string.display_name) contentValues.put( MediaStore.MediaColumns.DISPLAY_NAME, System.currentTimeMillis().toString() ) contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, folderName) } else { val dirFile = File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).absolutePath + File.separator + getString(R.string.display_name) ) if (!dirFile.exists()) { dirFile.mkdirs() } val lastName = if (resourceName.lastIndexOf("/") == -1) { System.currentTimeMillis().toString() } else { resourceName.substring(resourceName.lastIndexOf("/") + 1) } val destFile = File(dirFile, lastName) destPathUnderQ = destFile.absolutePath contentValues.put(MediaStore.MediaColumns.DATA, destFile.absolutePath) } } val insertUri = activity.contentResolver.insert( when (fileType) { DownloadFileTypeEnum.IMAGE -> { MediaStore.Images.Media.EXTERNAL_CONTENT_URI } DownloadFileTypeEnum.VIDEO -> { MediaStore.Video.Media.EXTERNAL_CONTENT_URI } else -> { MediaStore.Images.Media.EXTERNAL_CONTENT_URI } }, contentValues ) ?: kotlin.run { ToastUtil.showShort("failed!") return@withContext } // use can close stream automatically activity.contentResolver.openOutputStream(insertUri).use { when (fileType) { DownloadFileTypeEnum.IMAGE -> { val toBitmap = BitmapFactory.decodeFile(resourceName) val exeResult = toBitmap.compress(Bitmap.CompressFormat.PNG, 100, it) if (exeResult) { ToastUtil.showShort("success!") notifyAlbumUpdate(activity, destPathUnderQ) } else { ToastUtil.showShort("failed!") } } DownloadFileTypeEnum.VIDEO -> { if (copyFileToStream(resourceName, it)) { ToastUtil.showShort("success!") notifyAlbumUpdate(activity, destPathUnderQ) } else { ToastUtil.showShort("failed!") } } else -> {} } } } catch (e: Exception) { e.printStackTrace() } }
fun copyFileToStream(oldPath: String, out: OutputStream?): Boolean { if (out == null) return false try { var bytesum = 0 var byteread = 0 val oldFile = File(oldPath) if (oldFile.exists()) { // 读入原文件 val inStream = FileInputStream(oldPath) val buffer = ByteArray(4096) while (inStream.read(buffer).also { byteread = it } != -1) { bytesum += byteread //字节数 文件大小 out.write(buffer, 0, byteread) } inStream.close() out.close() return true } } catch (e: java.lang.Exception) { e.printStackTrace() } return false }
fun notifyAlbumUpdate(activity: Activity?, fileAbsolutePath: String) { val intent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE) val uri = Uri.fromFile(File(fileAbsolutePath)) intent.data = uri activity?.sendBroadcast(intent) }