ss_t_t_nの日記

開発の備忘録など

permission 覚え書き

こういうコード断片を適宜残すのは大切だと感じた

インタフェース

interface RuntimePermissionHandler<T> {

	companion object {
		const val REQUEST_CAMERA = 1
	}

	var controller: T?
	var onPermissionOk: (() -> Unit)?
	var onPermissionNg: ((message: String?) -> Unit)?

	fun requestPermission()
	fun handlePermissionResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray)
}

実装

class CameraPermissionHandler(override var controller: Activity?, override var onPermissionOk: (() -> Unit)?) : RuntimePermissionHandler<Activity> {
	override var onPermissionNg: ((message: String?) -> Unit)? = null

	override fun requestPermission() {
		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
			onPermissionOk?.invoke()
			return
		}
		controller?.let {
			if (ContextCompat.checkSelfPermission(it, CAMERA) == PackageManager.PERMISSION_GRANTED) {
				onPermissionOk?.invoke()
				return
			}
			ActivityCompat.requestPermissions(it, arrayOf(CAMERA), RuntimePermissionHandler.REQUEST_CAMERA)
		}
	}

	override fun handlePermissionResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
		if (requestCode == RuntimePermissionHandler.REQUEST_CAMERA && grantResults.isNotEmpty()) {
			if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
				onPermissionOk?.invoke()
			} else {
				onPermissionNg?.invoke("fail!!!!!!!!!!")
			}
		}
	}

}

呼ぶ

class MainActivity : AppCompatActivity() {

	private var mCameraPermissionHandler: RuntimePermissionHandler<Activity>? = null

	override fun onCreate(savedInstanceState: Bundle?) {
		super.onCreate(savedInstanceState)
		setContentView(R.layout.activity_main)
		mCameraPermissionHandler = CameraPermissionHandler(this, { init() })
		mCameraPermissionHandler?.onPermissionNg = {
			message ->
			message?.let {
				Snackbar.make(root, it, Snackbar.LENGTH_SHORT).show()
			}
		}
		mCameraPermissionHandler?.requestPermission()
	}

	override fun onDestroy() {
		super.onDestroy()
		mCameraPermissionHandler = null
	}

	override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
		super.onRequestPermissionsResult(requestCode, permissions, grantResults)
		mCameraPermissionHandler?.handlePermissionResult(requestCode, permissions, grantResults)
	}

	private fun init() {
		val s = Snackbar.make(root, "init!", Snackbar.LENGTH_LONG)
		s.setAction("reInit", {
			v ->
			val ss = Snackbar.make(v, "reinit!!!!!", Snackbar.LENGTH_SHORT)
			ss.show()
		})
		s.show()
	}

}

使ってみたら、イマイチな箇所があったので更新・・。
shouldShowRequestPermissionRationaleの使い方がいまいちピンと来ない・・。