`onRequestPermissionsResult()` is not working in Fragment-Kotlin - android

Problem:
I have done this LocationPermission task with activity but I want to do it with the fragment. In Fragment method onRequestPermissionsResult() is not being called.
There are many answers to this question but unfortunately non of them worked for me. Some of those answers are in java which is not applicable in kotlin, for instance, one answer says using 'FragmentCompat' this problem can be solved but we don't have FragmentCompat in Kotlin.
What I did so far?
I followed this question and many others.
Before ActivityCompat.requestPermissions(requireActivity(), arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), 1)
After:
requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),1)
though requestPermissions is depricated But nothing worked so far.
PLEASE DO CONSIDER KOTLIN LANGUAGE FOR ANSWERS
Code in Fragment:
fun RequestLocationPermission()
{
Log.d(TAG, "RequestLocationPermission: ")
if(ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
if(ActivityCompat.shouldShowRequestPermissionRationale(requireActivity(), Manifest.permission.ACCESS_FINE_LOCATION)){
requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),1)
}
else{
ActivityCompat.requestPermissions(requireActivity(), arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), 1)
requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),1)
}
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
Toast.makeText(requireContext(), "Request Permission Called", Toast.LENGTH_SHORT).show()
Log.d(TAG, "onRequestPermissionResult Called ")
when (requestCode) {
1 -> when {
grantResults.isEmpty() ->
// If user interaction was interrupted, the permission request
// is cancelled and you receive empty arrays.
Log.d(TAG, "User interaction was cancelled.")
grantResults[0] == PackageManager.PERMISSION_GRANTED ->{
// Permission was granted.
locationPermission = true
fetchLocation()
}
else -> {
// Permission denied.
Toast.makeText(requireContext(), "Permission Denied", Toast.LENGTH_SHORT).show();
}
}
}
}

Related

Unable to get longitude and latitude kotlin android

Here's my code:
private var longitude = ""
private var latitude = ""
In the oncreateView, I have to do a api call with my latitude and longitude data. But the value of latitude and longitude never change!
//location
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(requireActivity())
// getCurrentLocation
checkPermissions()
//CALL API
val request = Request.Builder()
.url(" API_PATH?latitude=$latitude&longitude=$longitude")
.build()
val client = OkHttpClient()
...
private fun checkPermissions(){
if(ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_DENIED){
ActivityCompat.requestPermissions(requireActivity(), arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION), 1)
}
else{
getLocations()
}
}
private fun getLocations() {
if (ActivityCompat.checkSelfPermission(
requireContext(),
Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
requireContext(),
Manifest.permission.ACCESS_COARSE_LOCATION
) != PackageManager.PERMISSION_GRANTED
) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return
}
fusedLocationProviderClient.lastLocation.addOnCompleteListener {
if(it == null){
Toast.makeText(requireContext(), "sorry can't get the location", Toast.LENGTH_SHORT).show()
}else it.apply {
latitude = it.result.latitude.toString()
longitude = it.result.longitude.toString()
}
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if(requestCode== 1){
if(grantResults.isNotEmpty() && grantResults[0]==PackageManager.PERMISSION_GRANTED){
//permission granted
if(ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.ACCESS_COARSE_LOCATION) ==
PackageManager.PERMISSION_GRANTED){
Toast.makeText(requireContext(), "Permission granted", Toast.LENGTH_SHORT).show()
getLocations()
}
}else{
Toast.makeText(requireContext(), "Permission denied", Toast.LENGTH_SHORT).show()
//denied permission
}
}
}
First, I enter always in th first condition in checkPermissions(). I don't know why. Secondly, I also try to write getLocations() in the first condition in the first if in checkPermissions(). But longitude and latitude are never update.
Can you help me please, I am on this case for a long time and I have no idea.
I think you always enter the first condition in checkPermissions() because you haven't yet granted the permissions.
I think you need to request the permissions where the TODO code is commented out.
It will be something like:
// You can directly ask for the permission.
requestPermissions(CONTEXT,
arrayOf(Manifest.permission.REQUESTED_PERMISSION),
REQUEST_CODE)
Found from https://developer.android.com/training/permissions/requesting
I hope that steers you in the right direction.
If you want to cheat for testing, you can go to Settings -> Apps -> Your app -> Permissions and enable the permissions and then re-test. Of course, you'll have to do the request in code for the users of your app before you release the app.

Android Studio keeps showing Missing Permission, even though i am handling it explicitly. How do I fix it?

While using Google Map API every time I add relate to location like here below, Android Studio keep showing error :
private fun enableMyLocationOnMap() {
googleMap.setPadding(0, ViewUtils.dpToPx(48f), 0, 0)
googleMap.isMyLocationEnabled = true //<----ERROR
}
Error: Call requires permission which may be rejected by user: code should explicitly check to see if permission is available (with checkPermission) or explicitly handle a potential SecurityException
I am handling permission explicitly:
override fun onStart() {
super.onStart()
when {
PermissionUtils.isAccessFineLocationGranted(this) -> {
when {
PermissionUtils.isLocationEnable(this) -> {
setUpLocationListener()
}
else -> {
PermissionUtils.showGPSNotEnableDialog(this)
}
}
}
else -> {
PermissionUtils.requestAccessFineLocation(
this
, LOCATION_PERMISSION_REQUEST_CODE
)
}
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
when (requestCode) {
LOCATION_PERMISSION_REQUEST_CODE -> {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
when {
PermissionUtils.isLocationEnable(this) -> {
setUpLocationListener()
}
else -> {
PermissionUtils.showGPSNotEnableDialog(this)
}
}
} else {
Toast.makeText(this, "Location Permission not granted", Toast.LENGTH_LONG)
.show()
}
}
}
}
where PermissionUtils.kt :
object PermissionUtils {
fun requestAccessFineLocation(activity: AppCompatActivity, requestId: Int) {
ActivityCompat.requestPermissions(
activity,
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
requestId
)
}
fun isAccessFineLocationGranted(context: Context): Boolean {
return ContextCompat.checkSelfPermission(
context,
Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED
}
fun isLocationEnable(context: Context): Boolean {
val locationManager: LocationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
|| locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
}
fun showGPSNotEnableDialog(context: Context) {
AlertDialog.Builder(context)
.setTitle(context.getString(R.string.enable_gps))
.setMessage(context.getString(R.string.required_for_this_app))
.setCancelable(false)
.setPositiveButton(context.getString(R.string.enable_now)) { _, _ ->
context.startActivity(Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS))
}
.show()
}
}
AndroidManifest.xml have :
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
Android Studio cannot "see" that you made the check elsewhere in the code. Also, it is theoretically possible for the user to revoke the permission between when you're checking for it and its usage.
You need to do the check directly before using the permission. For example:
private fun enableMyLocationOnMap() {
if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
googleMap.setPadding(0, ViewUtils.dpToPx(48f), 0, 0)
googleMap.isMyLocationEnabled = true //<----ERROR
} else {
// request permission flow
}
}

Request permission dialog isn't appear Android 6.0.1

I'm trying to get a Write_external_storage permission at the beginning of app work. But I can't see permission box. Here is my code:
override fun onStart() {
.....
if (Singleton.isPermissionGranted(this)) {
btn_submit_t.isEnabled
} else {
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 1)
}
super.onStart()
}
and then I added onRequestPermissionsResult:
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
when (requestCode) {
1 -> {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.i("m","permission_is_granted")
// permission was granted, yay! Do the
// contacts-related task you need to do.
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(this, "Permission denied to read your External storage", Toast.LENGTH_SHORT).show()
Handler().postDelayed({
if (Build.VERSION.SDK_INT >= 23) {
if(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
//your permission is granted
} else {
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 1)
}
}
else {
//permission is automatically granted on devices lower than android M upon installation
}
//ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 1)
}, 100)
}
return
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
I tested it on different devices, and my problem appears on Xiaomi device with Android 6.0.1 version. I also added checking but it didn't help me. Where can be the problem?
Have u added "WRITE EXTERNAL STORAGE" permission in Manifest File?

Ask permissions just showing granted

I followed the simple steps to ask for multiple permissions at once, here is my code for the permission request:
class MainActivity : AppCompatActivity() {
private val permissionCode = 100
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
getPermissions()
}
fun getPermissions() {
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.NFC, Manifest.permission.INTERNET),
permissionCode
)
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
when (requestCode) {
permissionCode -> {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission granted
Toast.makeText(this, "Permissions granted", Toast.LENGTH_SHORT).show()
} else {
// Permission denied
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show()
}
}
}
}
When I am starting the app I dont get any dialog to accept or deny the permissions and just get the toast "Permissions granted" but if I check the permissions in the app info I dont see any permissions granted. What I am doing wrong? Can someone help me?
Neither INTERNET nor NFC are permissions that need to be requested at runtime. Just having them in the manifest (via <uses-permission> elements) is sufficient.
Only permissions with a protection level of dangerous need to be requested at runtime — this table lists those. INTERNET and NFC are normal permissions, not dangerous.

Location permission callback being called again and again

I have implemented Runtime Permission. For testing purpose I have denied location permission and then again I have denied the permission with "Never to ask again" checkbox.
Now there is the problem. OnRequestPermissionResult is being called again and again from the system. For this, I can't show a dialog or snackbar on the screen properly. Here is my implementation. Where is the problem?
Checking location permission
override fun onResume() {
super.onResume()
if (checkLocationPermission())
startLocationUpdates()
updateUI()
}
This is my location update call
#SuppressLint("MissingPermission")
private fun startLocationUpdates() {
// Begin by checking if the device has the necessary location settings.
mLocationSettingsClient.checkLocationSettings(mLocationSettingsRequest)
.addOnSuccessListener(this, {
mFusedLocationClient.requestLocationUpdates(mLocationRequest,
mLocationCallback, Looper.myLooper());
updateUI()
})
.addOnFailureListener(this, {
handlingLocationClientSettingsFailure(it)
});
}
private fun handlingLocationClientSettingsFailure(it: Exception) {
val apiException = it as ApiException
when (apiException.statusCode) {
LocationSettingsStatusCodes.RESOLUTION_REQUIRED -> {
try {
Lg.d(TAG, "Inside start location update method FAILURE: REQUIRED")
// Show the dialog by calling startResolutionForResult(), and check the
// result in onActivityResult().
val rae = it as ResolvableApiException
rae.startResolutionForResult(this#MainActivity, REQUEST_CHECK_SETTINGS);
} catch (sie: IntentSender.SendIntentException) {
Log.i(TAG, "PendingIntent unable to execute request.");
}
}
LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE -> {
val errorMessage = "Location settings are inadequate, and cannot be " +
"fixed here. Fix in Settings.";
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
mRequestingLocationUpdates = false;
}
}
updateUI()
}
override fun onStop() {
super.onStop()
stopLocationUpdates()
}
private fun stopLocationUpdates() {
if (!mRequestingLocationUpdates) {
Lg.d(TAG, "Permission Denied! So No op!!!")
return
}
mFusedLocationClient.removeLocationUpdates(mLocationCallback)
.addOnCompleteListener(this) { mRequestingLocationUpdates = false }
}
private val MY_PERMISSIONS_REQUEST_LOCATION = 99;
private fun startLocationPermissionRequest() {
ActivityCompat.requestPermissions(this#MainActivity,
arrayOf(ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION),
MY_PERMISSIONS_REQUEST_LOCATION);
}
private fun checkLocationPermission(): Boolean {
if (ContextCompat.checkSelfPermission(this#MainActivity, ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(this#MainActivity, ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
android.Manifest.permission.ACCESS_FINE_LOCATION)) {
showSnackbar(R.string.location_permission_rationale,
android.R.string.ok,
View.OnClickListener {
startLocationPermissionRequest()
})
} else {
// No explanation needed, we can request the permission.
startLocationPermissionRequest()
}
return false
} else {
// Permission has already been granted
return true
}
}
#SuppressLint("NeedOnRequestPermissionsResult")
override fun onRequestPermissionsResult(requestCode: Int,
permissions: Array<out String>, grantResults: IntArray) {
when (requestCode) {
MY_PERMISSIONS_REQUEST_LOCATION -> {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(this#MainActivity, ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(this#MainActivity, ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED
) {
setLocationEnabled()
startLocationUpdates()
}
} else {
val showRationale = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
shouldShowRequestPermissionRationale(permissions[0])
} else {
TODO("VERSION.SDK_INT < M")
}
if (!showRationale) {
// user also CHECKED "never ask again"
// you can either enable some fall back,
// disable features of your app
// or open another dialog explaining
// again the permission and directing to
// the app setting
showingNecessaryMsgForLocationPermissionDenied()
} else {
// user did NOT check "never ask again"
// this is a good place to explain the user
// why you need the permission and ask if he wants
// to accept it (the rationale)
}
}
return
}
// other 'case' lines to check for other
// permissions this app might request
}
}
private fun showingNecessaryMsgForLocationPermissionDenied() {
Lg.d("TestTag", "Called")
MaterialDialog.Builder(this)
.title("Permission")
.content(R.string.permission_denied_explanation)
.onPositive { dialog, which ->
// Build intent that displays the App settings screen.
val intent = Intent().apply {
action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
data = Uri.fromParts("package", APPLICATION_ID, null)
flags = Intent.FLAG_ACTIVITY_NEW_TASK
}
startActivity(intent)
}
.positiveText(R.string.ok)
.show()
}
In this showingNecessaryMsgForLocationPermissionDenied() function I put a log, in my logcat I see that this function called again and again. How to stop it? Here is the logcat screentshot
I want to show this dialog when user denied permission. But I can't draw this smoothly for the above problem.
Note: I have tested the google repository of location update project. Same problem
Based on the documentation of Activity.requestPermissions
This method may start an activity allowing the user to choose which permissions to grant and which to reject. Hence, you should be prepared that your activity may be paused and resumed. Further, granting some permissions may require a restart of your application.
In this code, you are calling checkLocationPermission() in onResume(). Then from checkLocationPermission() call goes to requestPermissions which takes Activity in onPasue(). After onRequestPermissionsResult(), onResume() gets called again, creating infinte loop.
I would suggest having a boolean variable to decide if to call to checkLocationPermission() required.
var isRequestRequired = true;
override fun onResume() {
super.onResume()
if (isRequestRequired && checkLocationPermission())
startLocationUpdates()
updateUI()
}
then update isRequestRequired to false before showingNecessaryMsgForLocationPermissionDenied()
isRequestRequired = false
showingNecessaryMsgForLocationPermissionDenied()
This will stop onResume() from calling checkLocationPermission() again and again

Categories

Resources