I'm trying to request permission to access the ringer using this:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& ActivityCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.READ_CONTACTS)
== PackageManager.PERMISSION_DENIED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{ Manifest.permission.READ_CONTACTS },
REQUEST_CODE_READ_CONTACTS);
}
What I don't understand is that the code REQUEST_CODE_READ_CONTACTSis showing up with the error "cannot resolve symbol 'REQUEST_CODE_READ_CONTACTS'.
If you copied the code above from answer in this topic
then just initialize it with 1 and add this method in your code
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults){
switch (requestCode){
case REQUEST_CODE_READ_CONTACTS:
if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
READ_CONTACTS_GRANTED = true;
}
}
if(READ_CONTACTS_GRANTED){
loadContacts();
}
else{
Toast.makeText(this, "Allow permission in settings", Toast.LENGTH_LONG).show();
}
}
The value is a request code that you have to define yourself.
private static final int REQUEST_CODE_READ_CONTACTS = 99; // Can be any value >= 0
You can use it to determine which permission request the user has responded to in the onRequestPermissionsResult() callback by checking for the matching value.
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_READ_CONTACTS:
// Do your thing
break;
case ...
}
}
Related
While scrolling and jump onto one fragment to another, my logcat shown this error and my app crashed and restart. Please suggest me any solution regarding this?
Add in Manifest.xml
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
In activity page
int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, REQUEST_READ_PHONE_STATE);
} else {
//TODO
}
Permissions Result
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Do here
} else {
Toast.makeText(mContext, "The app was not allowed to write to your storage.", Toast.LENGTH_LONG).show();
}
}
}
}
For more details, please refer the following link
http://www.theappguruz.com/blog/runtime-permissions-in-android-marshmallow
Need to check for the grant of the required permissions(specifically to read user device sms)by the android application user as per android 6 and above standards. I am specifically looking for the ContextCompat.checkSelfPermission() method described on android developer site.
See here:
link
Please follow this tutorials Here is complete source code
static final int PERMISSION_ALL = 1;
String[] PERMISSIONS =
{Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION};
protected void runtimePermission() {
if (!hasPermission(ContactUS.this, PERMISSIONS)) {
ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
}
}
public static boolean hasPermission(Context context, String... permissions) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case PERMISSION_ALL:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//permission granted
//your logic here
} else {
//permission denied
}
break;
}
}
you can add run time permission like this
follow this steps
step 1 :- first add this permission in manifiest file
android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_COARSE_LOCATION,
now, than
step 2 : ask runtime permission
String permission = android.Manifest.permission.ACCESS_FINE_LOCATION;
if (ActivityCompat.checkSelfPermission(SearchCityClass.this, permission)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.
checkSelfPermission(SearchCityClass.this, android.Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(SearchCityClass.this, new String[]
{permission}, PERMISSION_GPS_CODE);
}
step 3: finallly handle permsiion result in onRequestPermissionsResult
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PERMISSION_GPS_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, location_permission_granted_msg, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, location_permission_not_granted_msg, Toast.LENGTH_SHORT).show();
}
}
}
if the permission is granted by :
checkSelfPermission(Manifest.permission.READ_CONTACTS)
Request permissions if necessary
if (checkSelfPermission(Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_CONTACTS},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
/* MY_PERMISSIONS_REQUEST_READ_CONTACTS is an app-defined int constant */
return;
}
Handle the permissions request response
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
/* permission granted */
} else {
/* permission denied */
}
return;
}
/* check for other permissions */
}
}
Also you can use a library like this, anyway good luck!
I Have a BaseAdapter with a List of all requires permissions for use correctly the app.
I need to, after onClick in one of them, request the permission and check if is granted or not.
For request, I am using
ActivityCompat.requestPermissions
but I do not know how to get the results.
Is it possible to call O
nRequestpermissionsResultCallback
to know the answer of the user?
How can I do it?
so first i implement in the Adapter
implements ActivityCompat.OnRequestPermissionsResultCallback
then it require one Overide method
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
// it is not work here onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == storagePermission) {
// getPosts(false);
if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(context.getApplicationContext(), "Please allow permission to Continue", Toast.LENGTH_SHORT).show();
}
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(context.getApplicationContext(), " Permissions Granted Succecfully", Toast.LENGTH_SHORT).show();
//here i load my method that i want to run
}
}
}
now problem is this onRequestPermissionsResult is not call from adapter instead
adapter triger onRequestPermissionsResult of the mainActivity Attach with the Adapter
so in main Activity i create this and run onRequestPermissionsResult of adapter by passing
adapterPosts.onRequestPermissionsResult(requestCode,permissions,grantResults);
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == storagePermission) {
// getPosts(false);
if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
//permission not granted
}
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//permission granted
adapterPosts.onRequestPermissionsResult(requestCode,permissions,grantResults);
//loadImageIntent();
}
}
}
To check the permission (in this example it's a permission to use the camera):
int permissionCheck = ContextCompat.checkSelfPermission(this,
Manifest.permission.CAMERA);
if (permissionCheck == PackageManager.PERMISSION_DENIED) {
// permission is not granted yet, let's ask for it
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CAMERA},
MyActivity.cameraRequestCode);
} else {
// permission is already granted
}
If ActivityCompat.requestPermissions is run, then a dialogue appears for the user, after which you can catch the result by overriding the Activity's onRequestPermissionsResult like this:
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case MyActivity.cameraRequestCode: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// action when permission granted
} else {
// action when permission denied
}
return;
}
}
}
MyActivity.cameraRequestCode is a static int, can be any unique int value.
In your adapter class
class Adapter extends RecyclerView.Adapter<Your adapter.MyViewHolder> implements ActivityCompat.OnRequestPermissionsResultCallback{`//enter code here`}
It will override the onRequestPermissionsResult
I have a same problem in RecylclerView.Adapter and I use this section in permission request method
private void requestCallPhonePerm() {
if (ContextCompat.checkSelfPermission(context,
Manifest.permission.CALL_PHONE)
!= PackageManager.PERMISSION_GRANTED) {
onItemCallListener.itemCallPhone(itemPhones);
ActivityCompat.requestPermissions((Activity)context,
new String[]{Manifest.permission.CALL_PHONE},
MY_PERMISSIONS_REQUEST_CALL_PHONE);
} else {
((MainActivity)context).callPhone(itemPhones);
}
}
It's important to use (Activity)context in "requestPermissions" method to be invoked callback in container activity of your adapter
And in my MainActivity that contain recycler I use overrided request permission result normally.
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch(requestCode){
case MY_PERMISSIONS_REQUEST_READ_CONTACTS:
if(grantResults.length>0
&&grantResults[0]==PackageManager.PERMISSION_GRANTED){
new LoadContacts().execute();
}
break;
case MY_PERMISSIONS_REQUEST_CALL_PHONE:
if(grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED){
callPhone(phones);
}else{
}
}
}
I solved this from custom class. My custom class is derived from AppCompatActivity. Also you need to pass Activity context to your custom class and do whatever you need with it.
public bool AreStorageAndCamPermissionsGranted(Activity context)
{
if (Build.VERSION.SdkInt >= Build.VERSION_CODES.M)
if (
context.CheckSelfPermission(Manifest.Permission.Camera)!= Android.Content.PM.Permission.Granted
|| context.CheckSelfPermission(Manifest.Permission.ReadExternalStorage) != Android.Content.PM.Permission.Granted
|| context.CheckSelfPermission(Manifest.Permission.WriteExternalStorage) != Android.Content.PM.Permission.Granted)
{
ActivityCompat.RequestPermissions(context, new String[]
{
Manifest.Permission.Camera,
Manifest.Permission.ReadExternalStorage,
Manifest.Permission.WriteExternalStorage,
}, REQUEST_PERMISSION_CODE);
}
return true;
}
`
I trying to develop an App that uses the Camera hardware in Android. While coding the following line
this.mCameraManager.openCamera(cameraIds[0], new CameraDevice.StateCallback() {...}
I was asked to explicitly check if the permission is available. when i added the permission check, Android added the following lines
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != 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;
}
and I override the follwoing method
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
now, i do not know what to write inside the if-statement and the "onRequestPermissionsResult" mentioned above. your help is highly appreciated
requestPermissions(new String[]{Manifest.permission.CAMERA}, REQ_ACCESS_FINE_LOCATION);
You have to show android permission dialog to users, after that you can catch users motions in onRequestPermissionsResult.
I think that you should look this website : https://developer.android.com/training/permissions/requesting.html
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_CODE_PERMISSIONS:
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED)
// Open Camera
break;
}
}
Try this:
// The permission required by the application to work properly
protected static final String[] requiredPermissions;
private static final int PERMISSION_REQUEST = 0;
static {
List<String> perms = new ArrayList<>(Arrays.asList(
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.CAMERA,
Manifest.permission.RECORD_AUDIO
));
requiredPermissions = perms.toArray(new String[perms.size()]);
}
Call verifyPermissions() method in onCreate():
private void verifyPermissions() {
if (!hasAllPermissions()) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(
this,
requiredPermissions,
PERMISSION_REQUEST
);
}
}
private boolean hasAllPermissions() {
// Check if we have all required permissions.
for (String perm : requiredPermissions) {
if (ActivityCompat.checkSelfPermission(this, perm) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
return true;
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST: {
// If request is cancelled, the result arrays are empty.
if (!hasAllPermissions()) {
finish();
}
return;
}
}
}
I'm writing some sort of hello world program for Google Location Services. I already coded most of the stuff; here's the onConnected method:
public void onConnected(Bundle bundle) {
// Construct the Location Request
mLocationRequest = new LocationRequest();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(30000);
// Check if permission granted
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// If not, ask for it.
// On Marshmallow, display permission request dialog
ActivityCompat.requestPermissions(
this,
new String[] {Manifest.permission.ACCESS_FINE_LOCATION},
LOCATION_REQUEST_NUMBER);
} else {
// If already granted, request for location updates
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
But I'm kinda stumped on what to do after the user tapped Allow on the dialog.
From what I could gather, I should do this:
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults){
switch (requestCode) {
case LOCATION_REQUEST_NUMBER: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission Granted
// Great. Now what?
// I tried the following, but it crashes
// LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
// I also tried the following, but it still does nothing.
mGoogleApiClient.connect();
} else {
// Permission Denied.
}
}
}
}
I tried calling requestLocationUpdates again on the Permission Granted, but this happens:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=#android:requestPermissions:, request=1, result=-1, data=Intent { act=android.content.pm.action.REQUEST_PERMISSIONS (has extras) }} to activity {com.example.starleaf1.locationexercise/com.example.starleaf1.locationexercise.MainActivity}: java.lang.NullPointerException: Attempt to read from field 'int com.google.android.gms.location.LocationRequest.b' on a null object reference
ADDED DETAILS:
I want the app to tell a TextView to display the current coordinates. Which I've coded like so:
#Override
public void onLocationChanged(Location location) {
Log.i(LOG_TAG, "Location has changed.");
output.setText(location.toString());
}
But when the Allow button is tapped, the app just sits there doing nothing. The app have to be restarted to get it to work.
Try this
declare this:
private static final int REQUEST_CODE_SOME_FEATURES_PERMISSIONS = 124;
And then
if(android.os.Build.VERSION.SDK_INT>=23) {
int hasLocationPermission = checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION);
List<String> permissions = new ArrayList<String>();
if (hasLocationPermission != PackageManager.PERMISSION_GRANTED) {
permissions.add(android.Manifest.permission.ACCESS_FINE_LOCATION);
}
if (!permissions.isEmpty()) {
requestPermissions(permissions.toArray(new String[permissions.size()]), REQUEST_CODE_SOME_FEATURES_PERMISSIONS);
}
}
and
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch ( requestCode ) {
case REQUEST_CODE_SOME_FEATURES_PERMISSIONS: {
for( int i = 0; i < permissions.length; i++ ) {
if( grantResults[i] == PackageManager.PERMISSION_GRANTED ) {
Log.d( "Permissions", "Permission Granted: " + permissions[i] );
} else if( grantResults[i] == PackageManager.PERMISSION_DENIED ) {
Log.d( "Permissions", "Permission Denied: " + permissions[i] );
}
}
}
break;
default: {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
You need two permissions
ActivityCompat.requestPermissions(this,new String[] {Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION},LOCATION_REQUEST_NUMBER);
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case LOCATION_REQUEST_NUMBER: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient != null)
mGoogleApiClient.connect();
// 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.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
You should check these permission at time of loading your activity so
that after permission granting , location instance can be initialize
Try to use this one as when we are requesting for permission for location,
we need to request for two permission for ACCESS_FINE_LOCATION and
ACCESS_COURSE_LOCATION.
private static final int PERMISSION_REQUEST_CODE = 1;
private void checkPermission()
{
if(android.os.Build.VERSION.SDK_INT>=23) {
int result = ContextCompat.checkSelfPermission(YourClass.this, Manifest.permission.ACCESS_FINE_LOCATION);
List<String> permissions = new ArrayList<String>();
if( result != PackageManager.PERMISSION_GRANTED ) {
permissions.add( Manifest.permission.ACCESS_FINE_LOCATION );
permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
}
if( !permissions.isEmpty() ) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions( permissions.toArray( new String[permissions.size()] ), PERMISSION_REQUEST_CODE );
}
}
and then
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
for( int i = 0; i < permissions.length; i++ ) {
if( grantResults[i] == PackageManager.PERMISSION_GRANTED ) {
Log.d( "Permissions", "Permission Granted: " + permissions[i] );
// Here you write your code once permission granted
} else if( grantResults[i] == PackageManager.PERMISSION_DENIED ) {
Log.d( "Permissions", "Permission Denied: " + permissions[i] );
}
}
break;
default: {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
After experimenting for a while, I managed to get it to work.
Please note that while this solution works in my experiment, I am not sure if the change I did is indeed what got it to work.
What I did was changing mGoogleApiClient.connect() to mGoogleApiClient.reconnect() in the onRequestPermissionResult. I also set it to Override.
Here's how the method finally looks like:
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case LOCATION_REQUEST_NUMBER: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if(mGoogleApiClient != null) {
mGoogleApiClient.reconnect();
}
} else {
Log.i(LOG_TAG, "Permission denied by user.");
}
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}