class WallpaperFragment : Fragment() {
private var _binding: FragmentWallpaperBinding? = null
private val binding get() = _binding!!
private lateinit var SettingsDataStore: SettingsDataStore
private var wallpaper = "default"
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentWallpaperBinding.inflate(inflater, container, false)
/* PICK PHOTO and Bind It------------------------------------------------------------------*/
var selectedImageUri: Uri? = null
val startForResult =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
if (result.resultCode == Activity.RESULT_OK) {
val intent = result.data
selectedImageUri = intent?.data
binding.backgroundImage.setImageURI(selectedImageUri)
lifecycleScope.launch {
SettingsDataStore.saveLayoutToPreferencesStore(wallpaper, requireContext())
}
}
}
binding.changeWallpaper.setOnClickListener() {
val intent = Intent(Intent.ACTION_GET_CONTENT,MediaStore.Images.Media.EXTERNAL_CONTENT_URI )
startForResult.launch(Intent.createChooser(intent, "Complete action using"))
} /*----------------------------------------------------------------------------------------*/
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
SettingsDataStore = SettingsDataStore(requireContext())
SettingsDataStore.preferenceFlow.asLiveData().observe(viewLifecycleOwner) { value ->
wallpaper = value
if (wallpaper.isNotBlank() && wallpaper!="default"){
Log.d("sss", wallpaper) //content://com.google.android.apps.photos.contentprovider/-1/1/content://media/external/images/media/24/ORIGINAL/NONE/2048773088
binding.backgroundImage.setImageURI(wallpaper.toUri())
}
}
}
}
我可以獲取影像 uri,我可以在 startForResult 中使用它。我還可以保存 uri (//content://com.google.android.apps.photos.contentprovider/-1/1/content://media/external/images/media/24/ORIGINAL/NONE/ 2048773088)。但是當我嘗試在 onViewCreated 中重用它時,會出現這樣的錯誤
java.lang.SecurityException: Permission Denial: opening provider com.google.android.apps.photos.contentprovider.impl.MediaContentProvider from ProcessRecord{677aefb 15300:com.yt.graduation/u0a149} (pid=15300, uid=10149) that is not exported from UID 10135
即使應用程式已關閉并打開,我也希望能夠再次使用我通過 startForResult 獲得的 selectedImageUri。
uj5u.com熱心網友回復:
使用 ACTION_GET_CONTENT 獲得的 uri 以后不能使用。
請改用 ACTION_OPEN_DOCUMENT 并在獲取 uri 時獲取持久 uri 權限。
然后保存 uri.toString() 并稍后重用。
您不想保存我們假設的影像檔案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/463369.html
