// Called when the user is performing an action which requires the app to read the // user's contacts public void getPermissionToAccessLocation(View view) { // 1) Use the support library version ContextCompat.checkSelfPermission(...) to avoid // checking the build version since Context.checkSelfPermission(...) is only available // in Marshmallow // 2) Always check for permission (even if permission has already been granted) // since the user can revoke permissions at any time through Settings if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // The permission is NOT already granted. // Check if the user has been asked about this permission already and denied // it. If so, we want to give more explanation about why the permission is needed. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (shouldShowRequestPermissionRationale( Manifest.permission.ACCESS_FINE_LOCATION)) { // Show our own UI to explain to the user why we need to read the contacts // before actually requesting the permission and showing the default UI } } // Fire off an async request to actually get the permission // This will show the standard permission request dialog UI if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_REQUEST); } } } // Callback with the request from calling requestPermissions(...) @Override public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) { // Make sure it's our original ACCESS_FINE_LOCATION request if (requestCode == PERMISSIONS_REQUEST) { if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Toast.makeText(this, "location permission granted", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, "location permission denied", Toast.LENGTH_SHORT).show(); } } else { super.onRequestPermissionsResult(requestCode, permissions, grantResults); } }
Add Permission in AndroidMenifiest.xml file
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Comments
Post a Comment
Thanks, I'll respond you soon!