From 97dac704bcc5f4dc441f0d31c4a680235ad50e2e Mon Sep 17 00:00:00 2001 From: Torsten Grote Date: Fri, 26 Jun 2020 14:15:34 -0300 Subject: [anastasis] ask for permission to fill in phone number automatically --- anastasis-ui/src/main/AndroidManifest.xml | 2 + .../main/java/org/gnu/anastasis/ui/MainActivity.kt | 2 + .../gnu/anastasis/ui/authentication/SmsFragment.kt | 50 ++++++++++++++++++++++ 3 files changed, 54 insertions(+) (limited to 'anastasis-ui/src') diff --git a/anastasis-ui/src/main/AndroidManifest.xml b/anastasis-ui/src/main/AndroidManifest.xml index 3f2402b..9340508 100644 --- a/anastasis-ui/src/main/AndroidManifest.xml +++ b/anastasis-ui/src/main/AndroidManifest.xml @@ -17,6 +17,8 @@ + + + if (hasFocus) checkPerm() + } saveSmsButton.setOnClickListener { viewModel.smsChecked.value = true findNavController().popBackStack() } } + private fun checkPerm() = when { + ContextCompat.checkSelfPermission(requireContext(), PERMISSION) + == PERMISSION_GRANTED -> { + // You can use the API that requires the permission. + fillPhoneNumber() + } + shouldShowRequestPermissionRationale(PERMISSION) -> { + // In an educational UI, explain to the user why your app requires this + // permission for a specific feature to behave as expected. In this UI, + // include a "cancel" or "no thanks" button that allows the user to + // continue using your app without granting the permission. + } + else -> { + // You can directly ask for the permission. + requestPermissions(arrayOf(PERMISSION), PERMISSION_REQUEST_CODE) + } + } + + override fun onRequestPermissionsResult( + requestCode: Int, + permissions: Array, + grantResults: IntArray + ) { + if (requestCode == PERMISSION_REQUEST_CODE && grantResults.isNotEmpty() && + grantResults[0] == PERMISSION_GRANTED + ) checkPerm() + } + + @SuppressLint("HardwareIds") + @RequiresPermission(PERMISSION) + private fun fillPhoneNumber() { + val telephonyService = requireContext().getSystemService(TelephonyManager::class.java) + telephonyService?.line1Number?.let { phoneNumber -> + smsView?.editText?.setText(phoneNumber) + smsView?.editText?.setSelection(phoneNumber.length) + } + } + } -- cgit v1.2.3