Related
I want to use the
android.permission.CAMERA
android.permission.WRITE_EXTERNAL_STORAGE
in single request using
ActivityCompat.requestPermissions(Activity activity,new String permisionList[],int permissionRequestcode);
But my problem is at time I request only one permission,
I read about group-permission,But it's work for only Same group which one decided by Developer, Like CONTACT_GROUP : read_contact,write_contact etc.
I want create the custom group permission which ask me only one request & provide me only one response.
Thanks
You can ask multiple permissions (from different groups) in a single request. For that, you need to add all the permissions to the string array that you supply as the first parameter to the requestPermissions API like this:
requestPermissions(new String[]{
Manifest.permission.READ_CONTACTS,
Manifest.permission.ACCESS_FINE_LOCATION},
ASK_MULTIPLE_PERMISSION_REQUEST_CODE);
On doing this, you will see the permission popup as a stack of multiple permission popups. Ofcourse you need to handle the acceptance and rejection (including the "Never Ask Again") options of each permissions. The same has been beautifully explained over here.
First initialize permission request code
public static final int PERMISSIONS_MULTIPLE_REQUEST = 123;
Check android version
private void checkAndroidVersion() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkPermission();
} else {
// write your logic here
}
}
check multiple permission code
private void checkPermission() {
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.READ_EXTERNAL_STORAGE) + ContextCompat
.checkSelfPermission(getActivity(),
Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale
(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) ||
ActivityCompat.shouldShowRequestPermissionRationale
(getActivity(), Manifest.permission.CAMERA)) {
Snackbar.make(getActivity().findViewById(android.R.id.content),
"Please Grant Permissions to upload profile photo",
Snackbar.LENGTH_INDEFINITE).setAction("ENABLE",
new View.OnClickListener() {
#Override
public void onClick(View v) {
requestPermissions(
new String[]{Manifest.permission
.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA},
PERMISSIONS_MULTIPLE_REQUEST);
}
}).show();
} else {
requestPermissions(
new String[]{Manifest.permission
.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA},
PERMISSIONS_MULTIPLE_REQUEST);
}
} else {
// write your logic code if permission already granted
}
}
call back method after grant permission by user
#Override
public void onRequestPermissionsResult(int requestCode,
#NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case PERMISSIONS_MULTIPLE_REQUEST:
if (grantResults.length > 0) {
boolean cameraPermission = grantResults[1] == PackageManager.PERMISSION_GRANTED;
boolean readExternalFile = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if(cameraPermission && readExternalFile)
{
// write your logic here
} else {
Snackbar.make(getActivity().findViewById(android.R.id.content),
"Please Grant Permissions to upload profile photo",
Snackbar.LENGTH_INDEFINITE).setAction("ENABLE",
new View.OnClickListener() {
#Override
public void onClick(View v) {
requestPermissions(
new String[]{Manifest.permission
.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA},
PERMISSIONS_MULTIPLE_REQUEST);
}
}).show();
}
}
break;
}
}
There is no hack available at this stage to circumvent asking for permissions from different groups together. That is the nature of how android has developed runtime permissions, to give users a choice of which permissions to accept. Of course not accepting all permissions required by an app, may make the app fail to work properly.
CAMERA and WRITE_EXTERNAL_STORAGE are both regarded as dangerous permissions, and in separate groups, thus both requiring a runtime permission request.
Once permission is granted for a particular group, it does not need to be requested again for the lifetime of the app run, or until it is revoked if given as a default setting.
The only thing you can do is ask the user to accept the decisions as default, which can be revoked, by using "never ask again"
I had the same issue and stumbled on this library.
Basically you can ask for multiple permissions sequentially, plus you can add listeners to popup a snackbar if the user denies your permission.
For multiple permission you can use this code :
final private int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS = 124;
private void insertDummyContactWrapper() {
List<String> permissionsNeeded = new ArrayList<String>();
final List<String> permissionsList = new ArrayList<String>();
if (!addPermission(permissionsList, Manifest.permission.ACCESS_FINE_LOCATION))
permissionsNeeded.add("GPS");
if (!addPermission(permissionsList, Manifest.permission.READ_CONTACTS))
permissionsNeeded.add("Read Contacts");
if (!addPermission(permissionsList, Manifest.permission.WRITE_CONTACTS))
permissionsNeeded.add("Write Contacts");
if (permissionsList.size() > 0) {
if (permissionsNeeded.size() > 0) {
// Need Rationale
String message = "You need to grant access to " + permissionsNeeded.get(0);
for (int i = 1; i < permissionsNeeded.size(); i++)
message = message + ", " + permissionsNeeded.get(i);
showMessageOKCancel(message,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
}
});
return;
}
requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
return;
}
insertDummyContact();
}
private boolean addPermission(List<String> permissionsList, String permission) {
if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
permissionsList.add(permission);
// Check for Rationale Option
if (!shouldShowRequestPermissionRationale(permission))
return false;
}
return true;
}
Here i have a simple solution, - (Multiple permission checking)
String[] permissions = new String[]{
Manifest.permission.WRITE_CALL_LOG,
Manifest.permission.READ_CALL_LOG,
Manifest.permission.READ_CONTACTS,
Manifest.permission.WRITE_CONTACTS}; // Here i used multiple permission check
Then call it in Oncreate
if (checkPermissions()) { // permissions granted.
getCallDetails();
}
Finally, copy the below code
private boolean checkPermissions() {
int result;
List<String> listPermissionsNeeded = new ArrayList<>();
for (String p : permissions) {
result = ContextCompat.checkSelfPermission(getApplicationContext(), p);
if (result != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(p);
}
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), MULTIPLE_PERMISSIONS);
return false;
}
return true;
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MULTIPLE_PERMISSIONS: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // permissions granted.
getCallDetails(); // Now you call here what ever you want :)
} else {
String perStr = "";
for (String per : permissions) {
perStr += "\n" + per;
} // permissions list of don't granted permission
}
return;
}
}
}
As said earlier, currently every permission group has own permission dialog which must be called separately.
You will have different dialog boxes for each permission group but you can surely check the result together in onRequestPermissionsResult() callback method.
Here is a working example link, may be useful for someone.
I faced the same problem and below is the workaround I came up with:
public boolean checkForPermission(final String[] permissions, final int permRequestCode, int msgResourceId) {
final List<String> permissionsNeeded = new ArrayList<>();
for (int i = 0; i < permissions.length; i++) {
final String perm = permissions[i];
if (ContextCompat.checkSelfPermission(getActivity(), permissions[i]) != PackageManager.PERMISSION_GRANTED) {
if (shouldShowRequestPermissionRationale(permissions[i])) {
final AlertDialog dialog = AlertDialog.newInstance( getResources().getString(R.string.permission_title), getResources().getString(msgResourceId) );
dialog.setPositiveButton("OK", new View.OnClickListener() {
#Override
public void onClick(View view) {
// add the request.
permissionsNeeded.add(perm);
dialog.dismiss();
}
});
dialog.show( getActivity().getSupportFragmentManager(), "HCFAlertDialog" );
} else {
// add the request.
permissionsNeeded.add(perm);
}
}
}
if (permissionsNeeded.size() > 0) {
// go ahead and request permissions
requestPermissions(permissionsNeeded.toArray(new String[permissionsNeeded.size()]), permRequestCode);
return false;
} else {
// no permission need to be asked so all good...we have them all.
return true;
}
}
And you call the above method like this:
if ( checkForPermission( new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.CAMERA}, REQUEST_PERMISSION_EXTERNAL_STORAGE_RESULT, R.string.permission_image) ) {
// DO YOUR STUFF
}
check More than one Permission and Request if Not Granted
public void checkPermissions(){
if(ContextCompat.checkSelfPermission(getApplicationContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE)== PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(getApplicationContext(),Manifest.permission.CAMERA)==PackageManager.PERMISSION_GRANTED){
//Do_SOme_Operation();
}else{
requestStoragePermission();
}
}
public void requestStoragePermission(){
ActivityCompat.requestPermissions(this
,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA},1234);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case 1234:if(grantResults[0]==PackageManager.PERMISSION_GRANTED && grantResults[1]==PackageManager.PERMISSION_GRANTED){
// Do_SOme_Operation();
}
default:super.onRequestPermissionsResult(requestCode,permissions,grantResults);
}
}
// **For multiple permission you can use this code :**
// **First:**
//Write down in onCreate method.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{
android.Manifest.permission.READ_EXTERNAL_STORAGE,
android.Manifest.permission.CAMERA},
MY_PERMISSIONS_REQUEST);
}
//**Second:**
//Write down in a activity.
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST:
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
progressBar.setVisibility(View.GONE);
Intent i = new Intent(SplashActivity.this,
HomeActivity.class);
startActivity(i);
finish();
}
}, SPLASH_DISPLAY_LENGTH);
} else {
finish();
}
return;
}
}
Based on what i've searched, i think this is the best answers that i've found out Android 6.0 multiple permissions
Adding generic code for different types of permissions. Copy-paste with minor changes. Read the "TODO" comments in the code below.
Make the following Activity your Launcher Activity:
public class PermissionReqActivity extends AppCompatActivity {
private static final int CODE_WRITE_SETTINGS_PERMISSION = 332;
private static String[] PERMISSIONS_ALL = {Manifest.permission.WRITE_EXTERNAL_STORAGE}; //TODO You can Add multiple permissions here.
private static final int PERMISSION_REQUEST_CODE = 223;
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_permission_req);
context = this;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
boolean allPermissionsGranted = true;
ArrayList<String> toReqPermissions = new ArrayList<>();
for (String permission : PERMISSIONS_ALL) {
if (ActivityCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
toReqPermissions.add(permission);
allPermissionsGranted = false;
}
}
if (allPermissionsGranted)
//TODO Now some permissions are very special and require Settings Activity to launch, as u might have seen in some apps. handleWriteSettingsPermission() is an example for WRITE_SETTINGS permission. If u don't need very special permission(s), replace handleWriteSettingsPermission() with initActivity().
handleWriteSettingsPermission();
else
ActivityCompat.requestPermissions(this,
toReqPermissions.toArray(new String[toReqPermissions.size()]), PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == PERMISSION_REQUEST_CODE) {
boolean allPermGranted = true;
for (int i = 0; i < grantResults.length; i++) {
if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permissions not granted: " + permissions[i], Toast.LENGTH_LONG).show();
allPermGranted = false;
finish();
break;
}
}
if (allPermGranted)
handleWriteSettingsPermission();//TODO As mentioned above, use initActivity() here if u dont need very special permission WRITE_SETTINGS
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
private void handleWriteSettingsPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (Settings.System.canWrite(context)) {
initActivity();
} else {
Toast.makeText(this, "Please Enable this permission for " +
getApplicationInfo().loadLabel(getPackageManager()).toString(), Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
intent.setData(Uri.parse("package:" + context.getPackageName()));
startActivityForResult(intent, CODE_WRITE_SETTINGS_PERMISSION);
}
}
}
//TODO You don't need the following onActivityResult() function if u dont need very special permissions.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && requestCode == CODE_WRITE_SETTINGS_PERMISSION) {
if (Settings.System.canWrite(this))
initActivity();
else {
Toast.makeText(this, "Permissions not granted: " + Manifest.permission.WRITE_SETTINGS, Toast.LENGTH_LONG).show();
finish();
}
}
}
private void initActivity() {
startActivity(new Intent(this, MainActivity.class));
}
}
Based on vedval i have this solution.
public boolean checkForPermission(final String[] permissions, final int permRequestCode) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return true;
}
final List<String> permissionsNeeded = new ArrayList<>();
for (int i = 0; i < permissions.length; i++) {
final String perm = permissions[i];
if (ContextCompat.checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
if (shouldShowRequestPermissionRationale(permissions[i])) {
Snackbar.make(phrase, R.string.permission_location, Snackbar.LENGTH_INDEFINITE)
.setAction(android.R.string.ok, new View.OnClickListener() {
#Override
#TargetApi(Build.VERSION_CODES.M)
public void onClick(View v) {
permissionsNeeded.add(perm);
}
});
} else {
// add the request.
permissionsNeeded.add(perm);
}
}
}
if (permissionsNeeded.size() > 0) {
// go ahead and request permissions
requestPermissions(permissionsNeeded.toArray(new String[permissionsNeeded.size()]), permRequestCode);
return false;
} else {
// no permission need to be asked so all good...we have them all.
return true;
}
}
/**
* Callback received when a permissions request has been completed.
*/
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
if (requestCode == REQUEST_READ_LOCATION) {
int i = 0;
for (String permission : permissions ){
if ( permission.equals(Manifest.permission.ACCESS_FINE_LOCATION) && grantResults.length > 0 && grantResults[i] == PackageManager.PERMISSION_GRANTED) {
initLocationManager();
}
i++;
}
}
}
I am late, but i want tell the library which i have ended with.
RxPermission is best library with reactive code, which makes permission code unexpected just 1 line.
RxPermissions rxPermissions = new RxPermissions(this);
rxPermissions
.request(Manifest.permission.CAMERA,
Manifest.permission.READ_PHONE_STATE)
.subscribe(granted -> {
if (granted) {
// All requested permissions are granted
} else {
// At least one permission is denied
}
});
add in your build.gradle
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
dependencies {
implementation 'com.github.tbruyelle:rxpermissions:0.10.1'
implementation 'com.jakewharton.rxbinding2:rxbinding:2.1.1'
}
you should use the dependency named dexter as given below:
https://github.com/Karumi/Dexter
by this you can get one or many permission easily:
this is the given code
Dexter.withContext(this).
withPermissions(Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
.withListener(new MultiplePermissionsListener() {
#Override
public void onPermissionsChecked(MultiplePermissionsReport
multiplePermissionsReport) {
displaySong();
}
#Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> list,
PermissionToken permissionToken) {
permissionToken.continuePermissionRequest();
}
}).check();
For Asking Multiple Permission At Once You Can Use this Method link
compile 'com.kishan.askpermission:askpermission:1.0.3'
If you got conflicting in support library then
compile('com.kishan.askpermission:askpermission:1.0.3', {
exclude group: 'com.android.support'
})
Now ask for Permission
new AskPermission.Builder(this)
.setPermissions(Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_EXTERNAL_STORAGE)
.setCallback(/* PermissionCallback */)
.setErrorCallback(/* ErrorCallback */)
.request(/* Request Code */);
permission granted callback
public void onPermissionsGranted(int requestCode) {
// your code }
permission denied callback
public void onPermissionsDenied(int requestCode) {
// your code}
ErrorCallbacks
public void onShowRationalDialog(PermissionInterface permissionInterface, int requestCode) {
// Alert user by Dialog or any other layout that you want.
// When user press OK you must need to call below method.
permissionInterface.onDialogShown();
}
public void onShowSettings(PermissionInterface permissionInterface, int requestCode) {
// Alert user by Dialog or any other layout that you want.
// When user press OK you must need to call below method.
// It will open setting screen.
permissionInterface.onSettingsShown();
}
Since I have made a flashlight application and it works properly on the device which have SDK 22 and below. But when I come to check on marshmallow and above devices, it doesn't run and crashes at the beginning only I asked for permission using following code but it doesn't seems to be working at all. here is my code for requesting permission of camera at run time. here is my code:
if( ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{android.Manifest.permission.CAMERA},
5);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 5) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Now user should be able to use camera
}
else {
// Your app will not have this permission. Turn off all functions
// if permission not granted it will force close the app
}
}
I have tried in marshmallow, nougat devices but it doesnt ask for camera permission and i have to go through manually from setting-app-flashlight-permission-allow. can anyone help me please. Currently I am testing my app in Lineage os 7.1.1
You need to add the SDK 23 permission in manifest. add the below line in manifest then you will get runtime permission callback.
<uses-permission-sdk-23 android:name="android.permission.CAMERA"/>
Just you change only if condition your code is perfect like this,
if( ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{android.Manifest.permission.CAMERA},
5);
}
}
to
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if( ContextCompat.checkSelfPermission(this,
android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{android.Manifest.permission.CAMERA},
5);
}
}
if(currentAPIVersion>= 23)
{
if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context,
Manifest.permission.CAMERA)) {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Camera Permission Necessary");
alertBuilder.setMessage("Camera permission is necessary");
alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions((Activity) context,
new String[]{Manifest.permission.CAMERA},
MY_PERMISSIONS_REQUEST_CAMERA);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
} else {
ActivityCompat.requestPermissions((Activity) context,
new String[]{Manifest.permission.CAMERA},
MY_PERMISSIONS_REQUEST_CAMERA);
}
return false;
} else {
return true;
}
} else {
return true;
}
Use the below code and call the "requestPermission" method in onCreate of the Activity:
private static final int REQUEST_CODE_PERMISSION = 2;
List<String> mPermission=new ArrayList<String>();
public void requestPermission()
{
try {
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
!= MockPackageManager.PERMISSION_GRANTED)
mPermission.add(Manifest.permission.CAMERA);
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= MockPackageManager.PERMISSION_GRANTED
)
mPermission.add(Manifest.permission.WRITE_EXTERNAL_STORAGE
);
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
!= MockPackageManager.PERMISSION_GRANTED)
mPermission.add(Manifest.permission.READ_EXTERNAL_STORAGE);
if(mPermission.size()>0)
{
String[] array = mPermission.toArray(new String[mPermission.size()]);
ActivityCompat.requestPermissions(this, array, REQUEST_CODE_PERMISSION);
// If any permission aboe not allowed by user, this condition will execute every tim, else your else part will work
}
} catch (Exception e) {
e.printStackTrace();
}
}
Overwrite the method "onRequestPermissionsResult":
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
Log.e("Req Code", "" + requestCode);
if (requestCode == REQUEST_CODE_PERMISSION) {
if (grantResults.length == mPermission.size()) {
for(int i=0;i<grantResults.length;i++)
{
if(grantResults[i] == MockPackageManager.PERMISSION_GRANTED)
{
//don't do anything....
}
else{
mPermission=new ArrayList<String>();
requestPermission();
break;
}
}
}
else{
Toast.makeText(this,"permition not granted",Toast.LENGTH_LONG).show();
mPermission=new ArrayList<String>();
requestPermission();
}
}
}
do this way:
if (ContextCompat.checkSelfPermission(UserProfileActivity.this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(UserProfileActivity.this, new String[]{Manifest.permission.CAMERA},
5);
} else {
//start flashlight
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[], #NonNull int[] grantResults) {
switch (requestCode) {
case 5: {
for (int i = 0; i < permissions.length; i++) {
if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
//start flashlight
Log.d("Permissions CAMERA", "Permission Granted: " + permissions[i]);
} else if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
Log.d("Permissions CAMERA", "Permission Denied: " + permissions[i]);
}
}
break;
}
default: {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
} break;
}
}
I also had the same problem but managed to fixed it. Here's my case (I don't know if its the same as yours but it's worth a try)
So I have this two activities namely: MainActivity, and FlashlightActivity.
I used to ask for camera permission explicitly in FlaslightActivity just before I tap the switch button but I forgot that I was checking if a user's phone has a camera in the onCreate() method. while I was asking for permission onClick of the switch button of the flashlight, in which that was after I checked if a user's phone has a camera. So what I did was to ask for the permission in my MainActivity just before I start FlashlightActivity.
flashBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(hasPermission()){
Intent flashIntent = new Intent("FlashlightActivity");
startActivity(flashIntent);
}else{
requestPermission();
}
}
});
So basically ask for the permission before you call any Camera related stuffs
From my activity when i call Contacts to get a contact number the application crashed. Application is running ok on other devices but when i'm try to run it in android 6.0, it crashed. i've no idea what i'm doing wrong.
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
After getting the the data in onActivityResult method.
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
switch (reqCode) {
case (PICK_CONTACT) :
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = this.getContentResolver().query(contactData, null, null, null, null);
if (c.moveToFirst()) {
String contactId = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String phoneNumber = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
Log.d(TAG, "name : "+name+" , Phone Number : "+ phoneNumber);
}
}
break;
}
}
can Anyone help me ?
All of the answers here are wrong. You shouldn't need READ_CONTACT permission at all to retrieve single contact using ACTION_PICK intent. You should be granted this permission temporary to be able to retrieve contact specific data. However there are some devices that don't implement this API in a good way. Myself I have found Sony Xperia Z3, but I heard about HTC devices also had this problem.
To have the user select a contact and provide your app access to all the contact information, use the ACTION_PICK action and specify the MIME type to Contacts.CONTENT_TYPE.
The result Intent delivered to your onActivityResult() callback contains the content: URI pointing to the selected contact. The response grants your app temporary permissions to read that contact using the Contacts Provider API even if your app does not include the READ_CONTACTS permission.
Source: https://developer.android.com/guide/components/intents-common.html#Contacts
[UPDATE]
After upgrading Sony Xperia Z3 system image to version 23.5.A.1.291 bug does not occur anymore.
From android 6.0 (Mashmello) , android has introduced Run Time Permissions for users to grand permission to apps while the app is running, not when they install the app. So, Your calling should be like this ->
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
/*If Android M*/
if (ContextCompat.checkSelfPermission(SendMoneyByDetailsActivity.this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
/*If Android M and Not permission granted */
ActivityCompat.requestPermissions(SendMoneyByDetailsActivity.this, new String[]{Manifest.permission.READ_CONTACTS}, REQUEST_READ_CONTACTS);
} else {
/*If Android M and permission granted */
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
}
} else {
/*IF not Android M*/
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
}
And when user grant the permission then you can call the intent to pick contact list ->
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case REQUEST_READ_CONTACTS: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//permission was granted, yay! Do the
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
} else {
// permission denied
}
return;
}
}
}
And don't forgot to add permission in your manifest file.
<uses-permission android:name="android.permission.READ_CONTACTS" />
It not your manifest problem its problem with android 6.0 it requires Runtime Permissions...
after adding this in manifest
<uses-permission android:name="android.permission.READ_CONTACTS" />
Just change your code to this In your code..
public class MainActivity extends Activity {
public static final int REQUIRED_PERMISSIONS = 001;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//give here permissions what ever you want...
// if you are using one add only one... not all..
if ((CheckPermission(this, Manifest.permission.READ_CONTACTS))&&
(CheckPermission(this, Manifest.permission.READ_PHONE_STATE))&&
(CheckPermission(this, Manifest.permission.INTERNET))&&
(CheckPermission(this, Manifest.permission.ACCESS_NETWORK_STATE))&&
(CheckPermission(this, Manifest.permission.ACCESS_WIFI_STATE)))
{
PermHandling();
}
//now reqest runtime permissions..
else {
RequestPermission(MainActivity.this, Manifest.permission.READ_CONTACTS, REQUIRED_PERMISSIONS);
RequestPermission(MainActivity.this, Manifest.permission.READ_PHONE_STATE, REQUIRED_PERMISSIONS );
RequestPermission(MainActivity.this, Manifest.permission.INTERNET, REQUIRED_PERMISSIONS );
RequestPermission(MainActivity.this, Manifest.permission.ACCESS_NETWORK_STATE, REQUIRED_PERMISSIONS );
RequestPermission(MainActivity.this, Manifest.permission.ACCESS_WIFI_STATE, REQUIRED_PERMISSIONS );
}
}
private void PermHandling() {
//Your app internal parts....
//Here your stuff works...
}
//private void NewPermHandling(){
//}
#Override
public void onRequestPermissionsResult(int permsRequestCode, String[] permissions, int[] grantResults) {
switch (permsRequestCode) {
case REQUIRED_PERMISSIONS: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
PermHandling();
} else {
//Toast.makeText(this, "Please Grant Permissions other wise app will close.!", Toast.LENGTH_SHORT).show();
}
return;
}
}
}
public void RequestPermission(Activity thisActivity, String Permission, int Code) {
if (ContextCompat.checkSelfPermission(thisActivity,
Permission)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Permission)) {
} else {
ActivityCompat.requestPermissions(thisActivity,
new String[]{Permission},
Code);
}
}
}
public boolean CheckPermission(Context context, String Permission) {
if (ContextCompat.checkSelfPermission(context,
Permission) == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
}
I also faced same problem my applications worked on till 5.1 but 6.0+ due to Runtime permissions We need to add them.. and accept those permissions at runtime
I think this is permission issue
add bellow permission inside manifest file
<uses-permission android:name="android.permission.READ_CONTACTS" />
accept permissions in marshmallows
https://developer.android.com/training/permissions/requesting.html
actual implementation
add bellow code inside Main Activity
call checkAndAddPermission() method inside onCreate() method
final private int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS = 1244;
private void checkAndAddPermission() {
List<String> permissionsNeeded = new ArrayList<>();
final List<String> permissionsList = new ArrayList<>();
if (!addPermission(permissionsList, android.Manifest.permission.READ_CONTACTS))
permissionsNeeded.add("ReadContacts");
if (permissionsList.size() > 0) {
if (permissionsNeeded.size() > 0) {
// Need Rationale
String message = "You need to grant access to " + permissionsNeeded.get(0);
for (int i = 1; i < permissionsNeeded.size(); i++)
message = message + ", " + permissionsNeeded.get(i);
ActivityCompat.requestPermissions(MainActivity.this, permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
} else {
ActivityCompat.requestPermissions(MainActivity.this, permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
}
}
}
#TargetApi(Build.VERSION_CODES.M)
private boolean addPermission(List<String> permissionsList, String permission) {
if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
permissionsList.add(permission);
// Check for Rationale Option
if (!shouldShowRequestPermissionRationale(permission))
return false;
}
return true;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS: {
Map<String, Integer> perms = new HashMap<>();
// Initial
perms.put(android.Manifest.permission.READ_CONTACTS, PackageManager.PERMISSION_GRANTED);
// Fill with results
for (int i = 0; i < permissions.length; i++)
perms.put(permissions[i], grantResults[i]);
// Check for ACCESS_FINE_LOCATION
if (perms.get(android.Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
// All Permissions Granted
} else {
// Permission Denied
Toast.makeText(MainActivity.this, "Some Permission is Denied", Toast.LENGTH_SHORT)
.show();
}
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
I want to use the
android.permission.CAMERA
android.permission.WRITE_EXTERNAL_STORAGE
in single request using
ActivityCompat.requestPermissions(Activity activity,new String permisionList[],int permissionRequestcode);
But my problem is at time I request only one permission,
I read about group-permission,But it's work for only Same group which one decided by Developer, Like CONTACT_GROUP : read_contact,write_contact etc.
I want create the custom group permission which ask me only one request & provide me only one response.
Thanks
You can ask multiple permissions (from different groups) in a single request. For that, you need to add all the permissions to the string array that you supply as the first parameter to the requestPermissions API like this:
requestPermissions(new String[]{
Manifest.permission.READ_CONTACTS,
Manifest.permission.ACCESS_FINE_LOCATION},
ASK_MULTIPLE_PERMISSION_REQUEST_CODE);
On doing this, you will see the permission popup as a stack of multiple permission popups. Ofcourse you need to handle the acceptance and rejection (including the "Never Ask Again") options of each permissions. The same has been beautifully explained over here.
First initialize permission request code
public static final int PERMISSIONS_MULTIPLE_REQUEST = 123;
Check android version
private void checkAndroidVersion() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkPermission();
} else {
// write your logic here
}
}
check multiple permission code
private void checkPermission() {
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.READ_EXTERNAL_STORAGE) + ContextCompat
.checkSelfPermission(getActivity(),
Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale
(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) ||
ActivityCompat.shouldShowRequestPermissionRationale
(getActivity(), Manifest.permission.CAMERA)) {
Snackbar.make(getActivity().findViewById(android.R.id.content),
"Please Grant Permissions to upload profile photo",
Snackbar.LENGTH_INDEFINITE).setAction("ENABLE",
new View.OnClickListener() {
#Override
public void onClick(View v) {
requestPermissions(
new String[]{Manifest.permission
.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA},
PERMISSIONS_MULTIPLE_REQUEST);
}
}).show();
} else {
requestPermissions(
new String[]{Manifest.permission
.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA},
PERMISSIONS_MULTIPLE_REQUEST);
}
} else {
// write your logic code if permission already granted
}
}
call back method after grant permission by user
#Override
public void onRequestPermissionsResult(int requestCode,
#NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case PERMISSIONS_MULTIPLE_REQUEST:
if (grantResults.length > 0) {
boolean cameraPermission = grantResults[1] == PackageManager.PERMISSION_GRANTED;
boolean readExternalFile = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if(cameraPermission && readExternalFile)
{
// write your logic here
} else {
Snackbar.make(getActivity().findViewById(android.R.id.content),
"Please Grant Permissions to upload profile photo",
Snackbar.LENGTH_INDEFINITE).setAction("ENABLE",
new View.OnClickListener() {
#Override
public void onClick(View v) {
requestPermissions(
new String[]{Manifest.permission
.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA},
PERMISSIONS_MULTIPLE_REQUEST);
}
}).show();
}
}
break;
}
}
There is no hack available at this stage to circumvent asking for permissions from different groups together. That is the nature of how android has developed runtime permissions, to give users a choice of which permissions to accept. Of course not accepting all permissions required by an app, may make the app fail to work properly.
CAMERA and WRITE_EXTERNAL_STORAGE are both regarded as dangerous permissions, and in separate groups, thus both requiring a runtime permission request.
Once permission is granted for a particular group, it does not need to be requested again for the lifetime of the app run, or until it is revoked if given as a default setting.
The only thing you can do is ask the user to accept the decisions as default, which can be revoked, by using "never ask again"
I had the same issue and stumbled on this library.
Basically you can ask for multiple permissions sequentially, plus you can add listeners to popup a snackbar if the user denies your permission.
For multiple permission you can use this code :
final private int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS = 124;
private void insertDummyContactWrapper() {
List<String> permissionsNeeded = new ArrayList<String>();
final List<String> permissionsList = new ArrayList<String>();
if (!addPermission(permissionsList, Manifest.permission.ACCESS_FINE_LOCATION))
permissionsNeeded.add("GPS");
if (!addPermission(permissionsList, Manifest.permission.READ_CONTACTS))
permissionsNeeded.add("Read Contacts");
if (!addPermission(permissionsList, Manifest.permission.WRITE_CONTACTS))
permissionsNeeded.add("Write Contacts");
if (permissionsList.size() > 0) {
if (permissionsNeeded.size() > 0) {
// Need Rationale
String message = "You need to grant access to " + permissionsNeeded.get(0);
for (int i = 1; i < permissionsNeeded.size(); i++)
message = message + ", " + permissionsNeeded.get(i);
showMessageOKCancel(message,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
}
});
return;
}
requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
return;
}
insertDummyContact();
}
private boolean addPermission(List<String> permissionsList, String permission) {
if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
permissionsList.add(permission);
// Check for Rationale Option
if (!shouldShowRequestPermissionRationale(permission))
return false;
}
return true;
}
Here i have a simple solution, - (Multiple permission checking)
String[] permissions = new String[]{
Manifest.permission.WRITE_CALL_LOG,
Manifest.permission.READ_CALL_LOG,
Manifest.permission.READ_CONTACTS,
Manifest.permission.WRITE_CONTACTS}; // Here i used multiple permission check
Then call it in Oncreate
if (checkPermissions()) { // permissions granted.
getCallDetails();
}
Finally, copy the below code
private boolean checkPermissions() {
int result;
List<String> listPermissionsNeeded = new ArrayList<>();
for (String p : permissions) {
result = ContextCompat.checkSelfPermission(getApplicationContext(), p);
if (result != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(p);
}
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), MULTIPLE_PERMISSIONS);
return false;
}
return true;
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MULTIPLE_PERMISSIONS: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // permissions granted.
getCallDetails(); // Now you call here what ever you want :)
} else {
String perStr = "";
for (String per : permissions) {
perStr += "\n" + per;
} // permissions list of don't granted permission
}
return;
}
}
}
As said earlier, currently every permission group has own permission dialog which must be called separately.
You will have different dialog boxes for each permission group but you can surely check the result together in onRequestPermissionsResult() callback method.
Here is a working example link, may be useful for someone.
I faced the same problem and below is the workaround I came up with:
public boolean checkForPermission(final String[] permissions, final int permRequestCode, int msgResourceId) {
final List<String> permissionsNeeded = new ArrayList<>();
for (int i = 0; i < permissions.length; i++) {
final String perm = permissions[i];
if (ContextCompat.checkSelfPermission(getActivity(), permissions[i]) != PackageManager.PERMISSION_GRANTED) {
if (shouldShowRequestPermissionRationale(permissions[i])) {
final AlertDialog dialog = AlertDialog.newInstance( getResources().getString(R.string.permission_title), getResources().getString(msgResourceId) );
dialog.setPositiveButton("OK", new View.OnClickListener() {
#Override
public void onClick(View view) {
// add the request.
permissionsNeeded.add(perm);
dialog.dismiss();
}
});
dialog.show( getActivity().getSupportFragmentManager(), "HCFAlertDialog" );
} else {
// add the request.
permissionsNeeded.add(perm);
}
}
}
if (permissionsNeeded.size() > 0) {
// go ahead and request permissions
requestPermissions(permissionsNeeded.toArray(new String[permissionsNeeded.size()]), permRequestCode);
return false;
} else {
// no permission need to be asked so all good...we have them all.
return true;
}
}
And you call the above method like this:
if ( checkForPermission( new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.CAMERA}, REQUEST_PERMISSION_EXTERNAL_STORAGE_RESULT, R.string.permission_image) ) {
// DO YOUR STUFF
}
check More than one Permission and Request if Not Granted
public void checkPermissions(){
if(ContextCompat.checkSelfPermission(getApplicationContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE)== PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(getApplicationContext(),Manifest.permission.CAMERA)==PackageManager.PERMISSION_GRANTED){
//Do_SOme_Operation();
}else{
requestStoragePermission();
}
}
public void requestStoragePermission(){
ActivityCompat.requestPermissions(this
,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA},1234);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case 1234:if(grantResults[0]==PackageManager.PERMISSION_GRANTED && grantResults[1]==PackageManager.PERMISSION_GRANTED){
// Do_SOme_Operation();
}
default:super.onRequestPermissionsResult(requestCode,permissions,grantResults);
}
}
// **For multiple permission you can use this code :**
// **First:**
//Write down in onCreate method.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{
android.Manifest.permission.READ_EXTERNAL_STORAGE,
android.Manifest.permission.CAMERA},
MY_PERMISSIONS_REQUEST);
}
//**Second:**
//Write down in a activity.
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST:
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
progressBar.setVisibility(View.GONE);
Intent i = new Intent(SplashActivity.this,
HomeActivity.class);
startActivity(i);
finish();
}
}, SPLASH_DISPLAY_LENGTH);
} else {
finish();
}
return;
}
}
Based on what i've searched, i think this is the best answers that i've found out Android 6.0 multiple permissions
Adding generic code for different types of permissions. Copy-paste with minor changes. Read the "TODO" comments in the code below.
Make the following Activity your Launcher Activity:
public class PermissionReqActivity extends AppCompatActivity {
private static final int CODE_WRITE_SETTINGS_PERMISSION = 332;
private static String[] PERMISSIONS_ALL = {Manifest.permission.WRITE_EXTERNAL_STORAGE}; //TODO You can Add multiple permissions here.
private static final int PERMISSION_REQUEST_CODE = 223;
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_permission_req);
context = this;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
boolean allPermissionsGranted = true;
ArrayList<String> toReqPermissions = new ArrayList<>();
for (String permission : PERMISSIONS_ALL) {
if (ActivityCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
toReqPermissions.add(permission);
allPermissionsGranted = false;
}
}
if (allPermissionsGranted)
//TODO Now some permissions are very special and require Settings Activity to launch, as u might have seen in some apps. handleWriteSettingsPermission() is an example for WRITE_SETTINGS permission. If u don't need very special permission(s), replace handleWriteSettingsPermission() with initActivity().
handleWriteSettingsPermission();
else
ActivityCompat.requestPermissions(this,
toReqPermissions.toArray(new String[toReqPermissions.size()]), PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == PERMISSION_REQUEST_CODE) {
boolean allPermGranted = true;
for (int i = 0; i < grantResults.length; i++) {
if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permissions not granted: " + permissions[i], Toast.LENGTH_LONG).show();
allPermGranted = false;
finish();
break;
}
}
if (allPermGranted)
handleWriteSettingsPermission();//TODO As mentioned above, use initActivity() here if u dont need very special permission WRITE_SETTINGS
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
private void handleWriteSettingsPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (Settings.System.canWrite(context)) {
initActivity();
} else {
Toast.makeText(this, "Please Enable this permission for " +
getApplicationInfo().loadLabel(getPackageManager()).toString(), Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
intent.setData(Uri.parse("package:" + context.getPackageName()));
startActivityForResult(intent, CODE_WRITE_SETTINGS_PERMISSION);
}
}
}
//TODO You don't need the following onActivityResult() function if u dont need very special permissions.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && requestCode == CODE_WRITE_SETTINGS_PERMISSION) {
if (Settings.System.canWrite(this))
initActivity();
else {
Toast.makeText(this, "Permissions not granted: " + Manifest.permission.WRITE_SETTINGS, Toast.LENGTH_LONG).show();
finish();
}
}
}
private void initActivity() {
startActivity(new Intent(this, MainActivity.class));
}
}
Based on vedval i have this solution.
public boolean checkForPermission(final String[] permissions, final int permRequestCode) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return true;
}
final List<String> permissionsNeeded = new ArrayList<>();
for (int i = 0; i < permissions.length; i++) {
final String perm = permissions[i];
if (ContextCompat.checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
if (shouldShowRequestPermissionRationale(permissions[i])) {
Snackbar.make(phrase, R.string.permission_location, Snackbar.LENGTH_INDEFINITE)
.setAction(android.R.string.ok, new View.OnClickListener() {
#Override
#TargetApi(Build.VERSION_CODES.M)
public void onClick(View v) {
permissionsNeeded.add(perm);
}
});
} else {
// add the request.
permissionsNeeded.add(perm);
}
}
}
if (permissionsNeeded.size() > 0) {
// go ahead and request permissions
requestPermissions(permissionsNeeded.toArray(new String[permissionsNeeded.size()]), permRequestCode);
return false;
} else {
// no permission need to be asked so all good...we have them all.
return true;
}
}
/**
* Callback received when a permissions request has been completed.
*/
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
if (requestCode == REQUEST_READ_LOCATION) {
int i = 0;
for (String permission : permissions ){
if ( permission.equals(Manifest.permission.ACCESS_FINE_LOCATION) && grantResults.length > 0 && grantResults[i] == PackageManager.PERMISSION_GRANTED) {
initLocationManager();
}
i++;
}
}
}
I am late, but i want tell the library which i have ended with.
RxPermission is best library with reactive code, which makes permission code unexpected just 1 line.
RxPermissions rxPermissions = new RxPermissions(this);
rxPermissions
.request(Manifest.permission.CAMERA,
Manifest.permission.READ_PHONE_STATE)
.subscribe(granted -> {
if (granted) {
// All requested permissions are granted
} else {
// At least one permission is denied
}
});
add in your build.gradle
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
dependencies {
implementation 'com.github.tbruyelle:rxpermissions:0.10.1'
implementation 'com.jakewharton.rxbinding2:rxbinding:2.1.1'
}
you should use the dependency named dexter as given below:
https://github.com/Karumi/Dexter
by this you can get one or many permission easily:
this is the given code
Dexter.withContext(this).
withPermissions(Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
.withListener(new MultiplePermissionsListener() {
#Override
public void onPermissionsChecked(MultiplePermissionsReport
multiplePermissionsReport) {
displaySong();
}
#Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> list,
PermissionToken permissionToken) {
permissionToken.continuePermissionRequest();
}
}).check();
For Asking Multiple Permission At Once You Can Use this Method link
compile 'com.kishan.askpermission:askpermission:1.0.3'
If you got conflicting in support library then
compile('com.kishan.askpermission:askpermission:1.0.3', {
exclude group: 'com.android.support'
})
Now ask for Permission
new AskPermission.Builder(this)
.setPermissions(Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_EXTERNAL_STORAGE)
.setCallback(/* PermissionCallback */)
.setErrorCallback(/* ErrorCallback */)
.request(/* Request Code */);
permission granted callback
public void onPermissionsGranted(int requestCode) {
// your code }
permission denied callback
public void onPermissionsDenied(int requestCode) {
// your code}
ErrorCallbacks
public void onShowRationalDialog(PermissionInterface permissionInterface, int requestCode) {
// Alert user by Dialog or any other layout that you want.
// When user press OK you must need to call below method.
permissionInterface.onDialogShown();
}
public void onShowSettings(PermissionInterface permissionInterface, int requestCode) {
// Alert user by Dialog or any other layout that you want.
// When user press OK you must need to call below method.
// It will open setting screen.
permissionInterface.onSettingsShown();
}
I have this code for creating directory for saving pictures:
File storageDir = null;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
storageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "myphoto");
if (!storageDir.mkdirs()) {
if (!storageDir.exists()){
Log.d("photo", "failed to create directory");
return null;
}
}
}
return storageDir;
storeDir returns "/storage/emulated/0/Pictures/myphoto/" below android 6 and on android 6 it returns null.
I have permission <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
buildToolVersion 23
targetSdkVersion 23
How to fix?
As #CommonsWare answered, there is run-time permission asking concept on Android M, so in new approach, permissions are not asked when installing the app but when trying to use specific feature of phone which requests permission, at run-time. User later can disable permission from phone settings->app->yourapp->permissions as well. So you have to check before doing something with that permission, and ask user:
int REQUEST_WRITE_EXTERNAL_STORAGE=1;
////...
File storageDir = null;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
//RUNTIME PERMISSION Android M
if(PackageManager.PERMISSION_GRANTED==ActivityCompat.checkSelfPermission(context,Manifest.permission.WRITE_EXTERNAL_STORAGE)){
storageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "myPhoto");
}else{
requestPermission(context);
}
}
return storageDir;
////...
private static void requestPermission(final Context context){
if(ActivityCompat.shouldShowRequestPermissionRationale((Activity)context,Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
// Provide an additional rationale to the user if the permission was not granted
// and the user would benefit from additional context for the use of the permission.
// For example if the user has previously denied the permission.
new AlertDialog.Builder(context)
.setMessage(context.getResources().getString(R.string.permission_storage))
.setPositiveButton(R.string.tamam, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions((Activity) context,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_WRITE_EXTERNAL_STORAGE);
}
}).show();
}else {
// permission has not been granted yet. Request it directly.
ActivityCompat.requestPermissions((Activity)context,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_WRITE_EXTERNAL_STORAGE);
}
}
///...
#Override
public void onRequestPermissionsResult(int requestCode,String permissions[], int[] grantResults) {
switch (requestCode) {
case UtilityPhotoController.REQUEST_WRITE_EXTERNAL_STORAGE: {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(context,
getResources().getString(R.string.permission_storage_success),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context,
getResources().getString(R.string.permission_storage_failure),
Toast.LENGTH_SHORT).show();
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
return;
}
}
}
You are running this on an Android 6.0+ environment and you have a targetSdkVersion of 23.
In that case, WRITE_EXTERNAL_STORAGE is part of the Android 6.0 runtime permission system. Either revise your app to participate in this system, or drop your targetSdkVersion below 23.
You must get permission for this work like:
for do it impliment this code:
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},23
);
}
}
good luck!!!
Try this code.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkPermission()) {
//do your work
} else {
requestPermission();
}
}
}
protected boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
protected void requestPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(this, "Write External Storage permission allows us to do store images. Please allow this permission in App Settings.", Toast.LENGTH_LONG).show();
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 100:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//do your work
} else {
Log.e("value", "Permission Denied, You cannot use local drive .");
}
break;
}
}