处理android11以上无法删除相册图片的问题
生活随笔
收集整理的這篇文章主要介紹了
处理android11以上无法删除相册图片的问题
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
在android11手機(jī)上,當(dāng)APP重新安裝后,無(wú)法刪除之前在APP上保存的圖片,是因?yàn)闆](méi)有app沒(méi)有修改這張圖片的權(quán)限,所以需要重新手動(dòng)申請(qǐng)權(quán)限,先上圖:
功能代碼實(shí)現(xiàn):
1、創(chuàng)建一個(gè)fragment,用于處理fragment 的回調(diào)信息。如果是activity的話,直接在 onActivityResult處理就可以了
2、創(chuàng)建刪除文件的工具類(lèi)
object ImageUtil {/*** 刪除文件* @return*/fun deleteFileUri(activity: FragmentActivity, imgPath: String, callBack: FileUtilCallback) {val cursor: Cursor = MediaStore.Images.Media.query(activity.contentResolver,MediaStore.Images.Media.EXTERNAL_CONTENT_URI,arrayOf<String>(MediaStore.Images.Media._ID),MediaStore.Images.Media.DATA.toString() + "=?",arrayOf(imgPath),null)try {if (cursor.moveToFirst()) {val id: Long = cursor.getLong(0)val contentUri: Uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URIval uri: Uri = ContentUris.withAppendedId(contentUri, id)val count: Int = activity.contentResolver.delete(uri, null, null)if (count > 0) {callBack.onResult(true)} else {callBack.onResult(false)}} else {val isSuccess = File(imgPath).delete()if (isSuccess) {callBack.onResult(true)} else {callBack.onResult(false)}}} catch (e: java.lang.Exception) {e.printStackTrace()if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && e is RecoverableSecurityException) {val DELETE_REQUEST_CODE = 1001ActivityResultFragment.registerActivityResult(activity,object : ActivityResultFragment.ActivityResultListener {override fun onRequest(fragment: ActivityResultFragment?) {try {fragment!!.startIntentSenderForResult(e.userAction.actionIntent.intentSender,DELETE_REQUEST_CODE,null,0, 0, 0, null)} catch (sendIntentException: IntentSender.SendIntentException) {sendIntentException.printStackTrace()callBack.onResult(false)}}override fun onActivityResult(requestCode: Int,resultCode: Int,@Nullable data: Intent?) {if (requestCode == DELETE_REQUEST_CODE && resultCode == Activity.RESULT_OK) {deleteFileUri(activity, imgPath, callBack)} else {callBack.onResult(false)}}})} else {callBack.onResult(false)}}}}3、在界面中設(shè)置一個(gè)點(diǎn)擊事件,實(shí)現(xiàn)刪除圖片功能的調(diào)用
R.id.delteimage -> {ImageUtil.deleteFileUri(requireActivity(),imagePath, //圖片路徑object : FileUtilCallback {override fun onResult(success: Boolean) {if (success) {ToastUtils.showBottom("刪除成功")goSelectPhoto() //更新列表} else {ToastUtils.showBottom("刪除失敗,請(qǐng)手動(dòng)刪除")}}}) }現(xiàn)在就可以實(shí)現(xiàn)在fragment里面 實(shí)現(xiàn)刪除文件功能,在獲取權(quán)限后自動(dòng)刪除該文件了
與50位技術(shù)專(zhuān)家面對(duì)面20年技術(shù)見(jiàn)證,附贈(zèng)技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的处理android11以上无法删除相册图片的问题的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: MySQL DML语言笔记
- 下一篇: Zabbix 探索主机 “Discove