kotlin 保存图片并申请权限

85 阅读1分钟
    inflater: LayoutInflater, container: ViewGroup?,

    savedInstanceState: Bundle?

): View? {

    // Inflate the layout for this fragment

    return inflater.inflate(R.layout.fragment_pager_photo, container, false)

}



override fun onActivityCreated(savedInstanceState: Bundle?) {

    super.onActivityCreated(savedInstanceState)



    val photoList = arguments?.getParcelableArrayList<PhotoItem>("PHOTO_LIST")

    PagerPhotoListAdapter().apply {

        viewPager2.adapter = this

        submitList(photoList)

    }



    viewPager2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {

        override fun onPageSelected(position: Int) {

            super.onPageSelected(position)

            photoTag.text = getString(R.string.photo_tag, position + 1, photoList?.size)

        }

    })



    viewPager2.setCurrentItem(arguments?.getInt("PHOTO_POSITION") ?: 0, false)



    saveButton.setOnClickListener {

      //api29之后 又把写入权限放开 写入无需申请,读要申请权限

        if (Build.VERSION.SDK_INT < 29 && ContextCompat.checkSelfPermission(

                requireContext(),

                Manifest.permission.WRITE_EXTERNAL_STORAGE

            ) != PackageManager.PERMISSION_GRANTED

        ) {

            requestPermissions(

                arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),

                REQUEST_WRITE_EXTERNAL_STORAGE

            )

        } else {

            viewLifecycleOwner.lifecycleScope.launch {

                savePhoto()

            }

        }

    }

}



override fun onRequestPermissionsResult(

    requestCode: Int,

    permissions: Array<out String>,

    grantResults: IntArray

) {

    super.onRequestPermissionsResult(requestCode, permissions, grantResults)

    when (requestCode) {

        REQUEST_WRITE_EXTERNAL_STORAGE -> {

            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                viewLifecycleOwner.lifecycleScope.launch {

                    savePhoto()

                }

            } else {

                Toast.makeText(requireContext(), "存储失败", Toast.LENGTH_SHORT).show()

            }

        }

    }

}

//suspend 挂起 可运行在子线程

private suspend fun savePhoto() {

    withContext(Dispatchers.IO) {//运行在子线程

        val holder =

            (viewPager2[0] as RecyclerView).findViewHolderForAdapterPosition(viewPager2.currentItem)

                    as PagerPhotoViewHolder

        val bitmap = holder.itemView.pagerPhoto.drawable.toBitmap()



        val saveUri = requireContext().contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,

            ContentValues()

        )?: kotlin.run {

            Toast.makeText(requireContext(), "存储失败", Toast.LENGTH_SHORT).show()

            return@withContext

        }

        requireContext().contentResolver.openOutputStream(saveUri).use {

            if (bitmap.compress(Bitmap.CompressFormat.JPEG,90,it)) {

                MainScope().launch {Toast.makeText(requireContext(), "存储成功", Toast.LENGTH_SHORT).show() }

            } else {

                MainScope().launch { Toast.makeText(requireContext(), "存储失败", Toast.LENGTH_SHORT).show() }

            }

        }

    }

}

}