Android multiple runtime permission in single dialog - android

I am trying to get all permission in a single dialog file and I followed the below link which provided me with an example
http://inthecheesefactory.com/blog/things-you-need-to-know-about-android-m-permission-developer-edition/en
This is my code
public class MActivity extends AppCompatActivity {
final private int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS = 124;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_m);
insertDummyContactWrapper();
}
#TargetApi(Build.VERSION_CODES.M)
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();
}
#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;
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(MActivity.this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", null)
.create()
.show();
}
private static final String TAG = "Contacts";
private void insertDummyContact() {
// Two operations are needed to insert a new contact.
ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>(2);
// First, set up a new raw contact.
ContentProviderOperation.Builder op =
ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null);
operations.add(op.build());
// Next, set the name for the contact.
op = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,
"__DUMMY CONTACT from runtime permissions sample");
operations.add(op.build());
// Apply the operations.
ContentResolver resolver = getContentResolver();
try {
resolver.applyBatch(ContactsContract.AUTHORITY, operations);
} catch (RemoteException e) {
Log.d(TAG, "Could not add a new contact: " + e.getMessage());
} catch (OperationApplicationException e) {
Log.d(TAG, "Could not add a new contact: " + e.getMessage());
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS: {
Map<String, Integer> perms = new HashMap<String, Integer>();
// Initial
perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.READ_CONTACTS, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.WRITE_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(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.WRITE_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
// All Permissions Granted
insertDummyContact();
} else {
// Permission Denied
Toast.makeText(MActivity.this, "Some Permission is Denied", Toast.LENGTH_SHORT)
.show();
}
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
I got the dialog box which asked for the permission and after given ok I checked the setting-->apps-->myappname-->permission, but permission was not set ?
Can some one please help me in this matter.

When I added permission in my mainfest file it worked perfectly.
Note : But I did anotherway
public class RecursionActivity extends AppCompatActivity {
Context context;
private static final int PERMISSION_REQUEST_CODE = 1;
String p1 = android.Manifest.permission.READ_CONTACTS, p2 = android.Manifest.permission.ACCESS_FINE_LOCATION,
p3 = android.Manifest.permission.WRITE_CONTACTS, p4 = Manifest.permission.CAMERA;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_recursion);
permissionAccess();
}
private void permissionAccess() {
if (!checkPermission(p1)) {
Log.e("TAG",p1);
requestPermission(p1);
} else if (!checkPermission(p2)) {
Log.e("TAG",p2);
requestPermission(p2);
} else if (!checkPermission(p3)) {
Log.e("TAG",p3);
requestPermission(p3);
} else if (!checkPermission(p4)) {
Log.e("TAG",p4);
requestPermission(p4);
} else {
Toast.makeText(context, "All permission granted", Toast.LENGTH_LONG).show();
}
}
private boolean checkPermission(String permission) {
int result = ContextCompat.checkSelfPermission(context, permission);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
private void requestPermission(String permission) {
if (ContextCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(RecursionActivity.this, new String[]{permission}, PERMISSION_REQUEST_CODE);
} else {
//Do the stuff that requires permission...
Log.e("TAG","Not say request");
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
Log.e("TAG", "val " + grantResults[0]);
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
permissionAccess();
} else {
Toast.makeText(context, "Bye bye", Toast.LENGTH_LONG).show();
}
break;
}
}
}
I don't know whether this is an optimized solution or not but I hope it will be helpful for someone.

In your addPermission method add required permissions as follows:
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.READ_PHONE_STATE,android.Manifest.permission.ACCESS_FINE_LOCATION,android.Manifest.permission.ACCESS_COARSE_LOCATION}, 1);

Related

Splashscreen with runtime permissions

I have a splash screen on launching my app. So when showing the splash screen run time permission should show. I got this code below from github. But runtime permissions are not showing. Splash screen works fine, but runtime permission is not working when add this code below. I have added permissions read sms, read external storage, access location. I have given all these permissions in the manifest file also.
public class SplashActivity extends AppCompatActivity {
String loginstatus;
final private int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS = 124;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splashfile);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(SplashActivity.this, LoginActivity.class);
startActivity(i);
finish();
}
}, 3000);
/* Thread background = new Thread() {
public void run() {
try {
// Thread will sleep for 10 seconds
sleep(4*1000);
startActivity(new Intent(SplashScreen.this,HomeActivity.class));
finish();
} catch (Exception e) {
}
}
};
// start thread
background.start();*/
}
private void permissioncheck() {
List<String> permissionsNeeded = new ArrayList<String>();
final List<String> permissionsList = new ArrayList<String>();
if (!addPermission(permissionsList, Manifest.permission.READ_EXTERNAL_STORAGE))
permissionsNeeded.add("READ");
if (!addPermission(permissionsList, Manifest.permission.ACCESS_COARSE_LOCATION))
permissionsNeeded.add("COURLOC");
if (!addPermission(permissionsList, Manifest.permission.ACCESS_FINE_LOCATION))
permissionsNeeded.add("FINELOC");
if (!addPermission(permissionsList, Manifest.permission.READ_SMS))
permissionsNeeded.add("SMS");
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) {
if (Build.VERSION.SDK_INT >= 23) {
// Marshmallow+
requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
} else {
// Pre-Marshmallow
}
}
});
return;
}
if (Build.VERSION.SDK_INT >= 23) {
// Marshmallow+
requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
} else {
// Pre-Marshmallow
}
return;
}else
{
// Toast.makeText(this,"Permission",Toast.LENGTH_LONG).show();
LaunchApp();
}
//insertDummyContact();
}
private boolean addPermission(List<String> permissionsList, String permission) {
Boolean cond;
if (Build.VERSION.SDK_INT >= 23) {
// Marshmallow+
if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
permissionsList.add(permission);
// Check for Rationale Option
if (!shouldShowRequestPermissionRationale(permission))
// return false;
cond = false;
}
// return true;
cond = true;
} else {
// Pre-Marshmallow
cond = true;
}
return cond;
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(SplashActivity.this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", null)
.create()
.show();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//Checking the request code of our request
if (requestCode == 23) {
//If permission is granted
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Displaying a toast
Toast.makeText(this, "Permission granted", Toast.LENGTH_LONG).show();
} else {
//Displaying another toast if permission is not granted
Toast.makeText(this, "Permission Needed To Run The App", Toast.LENGTH_LONG).show();
}
}
if (requestCode == REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS) {
Map<String, Integer> perms = new HashMap<String, Integer>();
// Initial
perms.put(Manifest.permission.READ_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.ACCESS_COARSE_LOCATION, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.READ_SMS, PackageManager.PERMISSION_GRANTED);
//Toast.makeText(SplashScreen.this, " Permissions are jddddd", Toast.LENGTH_SHORT).show();
// 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(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
perms.get(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
perms.get(Manifest.permission.READ_SMS) == PackageManager.PERMISSION_GRANTED) {
// All Permissions Granted
// insertDummyContact();
//Toast.makeText(SplashScreen.this, " Permissions are l", Toast.LENGTH_SHORT).show();
LaunchApp();
} else {
// Permission Denied
Toast.makeText(SplashActivity.this, "Some Permission is Denied", Toast.LENGTH_SHORT)
.show();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Do something after 100
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivityForResult(intent, REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
finish();
}
}, 3000);
}
}
}
public void LaunchApp()
{
Thread background = new Thread() {
public void run() {
try {
// Thread will sleep for 10 seconds
sleep(4*1000);
startActivity(new Intent(getApplicationContext(),LoginActivity.class));
finish();
} catch (Exception e) {
}
}
};
// start thread
background.start();
}
}
You need to call permissioncheck() on onCreate() method after setContentView(). Replace the code provided below with your onCreate() method.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splashfile);
permissioncheck();
}
I removed Handler codes on onCreate() method. Instead, use onRequestPermissionResult() and start LoginActivity from it. Replace the following code to your onRequestPermissionResult().
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//Checking the request code of our request
if (requestCode == 23) {
//If permission is granted
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Displaying a toast
Toast.makeText(this, "Permission granted", Toast.LENGTH_LONG).show();
} else {
//Displaying another toast if permission is not granted
Toast.makeText(this, "Permission Needed To Run The App", Toast.LENGTH_LONG).show();
}
}
if (requestCode == REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS) {
Map<String, Integer> perms = new HashMap<String, Integer>();
// Initial
perms.put(Manifest.permission.READ_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.ACCESS_COARSE_LOCATION, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.READ_SMS, PackageManager.PERMISSION_GRANTED);
//Toast.makeText(SplashScreen.this, " Permissions are jddddd", Toast.LENGTH_SHORT).show();
// 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(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
perms.get(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
perms.get(Manifest.permission.READ_SMS) == PackageManager.PERMISSION_GRANTED) {
// All Permissions Granted
// Here start the activity
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(SplashActivity.this, LoginActivity.class);
startActivity(i);
finish();
}
}, 3000);
} else {
// Permission Denied
Toast.makeText(SplashActivity.this, "Some Permission is Denied", Toast.LENGTH_SHORT)
.show();
finish();
}
}
}
Please carefully read comments in the code provided above.
Best Code
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
public class Firstclass extends AppCompatActivity {
private int timeoutMillis = 5000;
/** The time when this {#link AppCompatActivity} was created. */
private long startTimeMillis = 0;
/** The code used when requesting permissions */
private static final int PERMISSIONS_REQUEST = 1234;
public int getTimeoutMillis() {
return timeoutMillis;
}
#SuppressWarnings("rawtypes")
public Class getNextActivityClass() {
return SecondActivity.class;
};
public String[] getRequiredPermissions() {
String[] permissions = null;
try {
permissions = getPackageManager().getPackageInfo(getPackageName(),
PackageManager.GET_PERMISSIONS).requestedPermissions;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
if (permissions == null) {
return new String[0];
} else {
return permissions.clone();
}
}
#TargetApi(23)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startTimeMillis = System.currentTimeMillis();
if (Build.VERSION.SDK_INT >= 23) {
checkPermissions();
} else {
startNextActivity();
}
}
#TargetApi(23)
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
if (requestCode == PERMISSIONS_REQUEST) {
checkPermissions();
}
}
private void startNextActivity() {
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
long delayMillis = getTimeoutMillis() - (System.currentTimeMillis() - startTimeMillis);
if (delayMillis < 0) {
delayMillis = 0;
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(Firstclass.this, getNextActivityClass()));
finish();
}
}, delayMillis);
}
private void checkPermissions() {
String[] ungrantedPermissions = requiredPermissionsStillNeeded();
if (ungrantedPermissions.length == 0) {
startNextActivity();
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(ungrantedPermissions, PERMISSIONS_REQUEST);
}
}
}
#TargetApi(23)
private String[] requiredPermissionsStillNeeded() {
Set<String> permissions = new HashSet<String>();
for (String permission : getRequiredPermissions()) {
permissions.add(permission);
}
for (Iterator<String> i = permissions.iterator(); i.hasNext();) {
String permission = i.next();
if (checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED) {
Log.d(Firstclass.class.getSimpleName(),
"Permission: " + permission + " already granted.");
i.remove();
} else {
Log.d(Firstclass.class.getSimpleName(),
"Permission: " + permission + " not yet granted.");
}
}
return permissions.toArray(new String[permissions.size()]);
}
}
Manifest xml permission
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />

Best way to handle runtime permission in android

i have an old project with target sdk 21, now i have to put run time permission in that so can anyone suggest me any best and simple way to do that.
Create two variables like
private static final int REQUEST_CODE_PERMISSION = 1;
String mPermission = Manifest.permission.ACCESS_FINE_LOCATION;
after create method like this
private void getPermission() {
if(Build.VERSION.SDK_INT>= 23) {
if (checkSelfPermission(mPermission) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{mPermission,
},
REQUEST_CODE_PERMISSION);
return;
}
else
{
/* your code if permission already access
}
}
}
After override onRequestPermissionsResult method like this
#Override
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 == 1 &&
grantResults[0] == MockPackageManager.PERMISSION_GRANTED ) {
methodRedirect();
}
else{
this.getPermission();
}
}
}
In this way even user deny permission, it will show again.
You can manage multiple permission like this.
You can handle permission on Splash Screen or First Screen.
if multiple permission then handle all one time.
if user denied any permission then it show message some permission required.
hope it will help you.
Here is example how to handle multiple permission.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
if(checkAndRequestPermissions()){
//all permission granted
}else{
//require all permission.
}
}
private boolean checkAndRequestPermissions() {
int camerapermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
int phonestate = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE);
int location = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
int recordaudio = ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO);
int permissionLocation = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
List<String> listPermissionsNeeded = new ArrayList<>();
if (camerapermission != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.CAMERA);
}
if (phonestate != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.READ_PHONE_STATE);
}
if (location != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
}
if (recordaudio != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.RECORD_AUDIO);
}
if (permissionLocation != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
return false;
}
return true;
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case REQUEST_ID_MULTIPLE_PERMISSIONS: {
Map<String, Integer> perms = new HashMap<>();
perms.put(Manifest.permission.CAMERA, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.READ_PHONE_STATE, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.RECORD_AUDIO, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
// Fill with actual results from user
if (grantResults.length > 0) {
for (int i = 0; i < permissions.length; i++)
perms.put(permissions[i], grantResults[i]);
// Check for both permissions
if (perms.get(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
) {
Log.d(TAG, "camera & location services permission granted");
// here you can do your logic all Permission Success Call
moveToNxtScreen();
} else {
Log.d(TAG, "Some permissions are not granted ask again ");
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
showDialogOK("Some Permissions are required for Open Camera",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
checkAndRequestPermissions();
break;
case DialogInterface.BUTTON_NEGATIVE:
// proceed with logic by disabling the related features or quit the app.
dialog.dismiss();
break;
}
}
});
} else {
explain("You need to give some mandatory permissions to continue. Do you want to go to app settings?");
}
}
}
}
}
}
private void showDialogOK(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", okListener)
.create()
.show();
}
private void explain(String msg) {
final android.support.v7.app.AlertDialog.Builder dialog = new android.support.v7.app.AlertDialog.Builder(this);
dialog.setMessage(msg)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
Utils.startInstalledAppDetailsActivity(LoginActivity.this);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
dialog.create().dismiss();
finish();
}
});
dialog.show();
}

Having trouble in asking multiple permission in android Marshmallow

I am working on an app in which I want to ask multiple permission at run time.
My code is worked fine for one Permission. However when I want to ask for multiple permission my code does nothing .
Can anyone tell me what wrong with my code?
package saleskit.orbitsys.com.androidpermissiondemo;
import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_INTERNET = 200;
private static final int REQUEST_CODE_INTERNET = 110;
private static final int PERMISSION_REQUEST_CODE_GPS = 111;
public static final int PERMISSION_REQUEST_CODE_CONTACT = 112;
public static final int PERMISSION_REQUEST_CODE_CAMARA = 113;
public static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 201;
private WebView htmlWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar
= getSupportActionBar();
if (null != actionBar) {
actionBar.hide();
}
checkMultiplePermission();
/* if (ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{ Manifest.permission.RECORD_AUDIO}, REQUEST_INTERNET);
}*/
htmlWebView = (WebView) findViewById(R.id.webView);
assert htmlWebView != null;
WebSettings webSetting = htmlWebView.getSettings();
webSetting.setJavaScriptEnabled(true);
webSetting.setDisplayZoomControls(true);
htmlWebView.setWebViewClient(new CustomWebViewClient());
htmlWebView.loadUrl("https://inducesmile.com/blog");
}
public boolean checkMultiplePermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int permissionFineLocation = ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION);
int permissionCorseLocation = ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.ACCESS_COARSE_LOCATION);
int permissioncamera = ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.CAMERA);
int permissioncall = ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.CALL_PHONE);
int permissionSDCARD = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
int permissionSDCARD2 = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE);
int readSms = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_SMS);
List<String> listPermissionsNeeded = new ArrayList<>();
if (permissioncall != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.CALL_PHONE);
}
if (permissionCorseLocation != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.ACCESS_COARSE_LOCATION);
}
if (permissionFineLocation != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
}
if (permissioncamera != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.CAMERA);
}
if (permissionSDCARD != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
if (permissionSDCARD2 != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.READ_EXTERNAL_STORAGE);
}
if (readSms != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.READ_SMS);
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(MainActivity.this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
return false;
}
return true;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] listPermissionsNeeded, #NonNull int[] grantResults) {
if(listPermissionsNeeded.length == 0){
return;
}
boolean allPermissionsGranted = true;
if(grantResults.length>0){
for(int grantResult: grantResults){
if(grantResult != PackageManager.PERMISSION_GRANTED){
allPermissionsGranted = false;
break;
}
}
}
if(!allPermissionsGranted){
boolean somePermissionsForeverDenied = false;
for(String permission: listPermissionsNeeded){
if(ActivityCompat.shouldShowRequestPermissionRationale(this, permission)){
ActivityCompat.requestPermissions(MainActivity.this, new String[]{ permission}, requestCode);
//denied
Log.e("denied", permission);
}else{
if(ActivityCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(MainActivity.this, new String[]{ permission}, requestCode);
//allowed
Log.e("allowed", permission);
} else{
somePermissionsForeverDenied = true;
}
}
}
if(somePermissionsForeverDenied){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("Permissions Required")
.setMessage("You have forcefully denied some of the required permissions " +
"for this action. Please open settings, go to permissions and allow them.")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.fromParts("package", getPackageName(), null));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
})
.show();
}
} else {
switch (requestCode) {
//act according to the request code used while requesting the permission(s).
}
}
}
private class CustomWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}
Any kind of help is appreciate by me thanks.
First check permission is already granted or not.
Here you can check more then one permissions.
if (checkForPermission(getActivity(), CAMERA_PERMISSION) && checkForPermission(getActivity(), GALLERY_PERMISSION)) {
//Permission granted here
//TODO
} else {
requestPermissions(new String[]{CAMERA_PERMISSION, GALLERY_PERMISSION}, 1);
}
checkForPermission method.
/***
* Method is checking permission for Marshmallow
*
* #param context
* #param permission
* #return
*/
private static boolean checkForPermission(final Context context, String permission) {
int result = ContextCompat.checkSelfPermission(context, permission);
//If permission is granted then it returns 0 as result
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
onRequestPermissionsResult method its like onActivityResult.
/***
* This is call when user allow or deny permissions in the Marshmallow
*
* #param requestCode
* #param permissions
* #param grantResults
*/
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 1:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
//Permission granted here
//TODO
}
break;
}
}
In your activity:
private static final int MY_PERMISSIONS = 111;
in onCreate method:
String[] mPermissionToRequest = new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.CAMERA,Manifest.permission.CALL_PHONE};
ActivityCompat.requestPermissions(this, mPermissionsToRequest, MY_PERMISSIONS);
#Override
public void onRequestPermissionsResult( int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
}
Check for your AndroidManifest.xml file:
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
For Multiple Permisions:
public abstract class AbsRuntimePermission extends Activity {
private SparseIntArray mErrorString;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mErrorString = new SparseIntArray();
}
public abstract void onPermissionsGranted(int requestCode);
public void requestAppPermissions(final String[]requestedPermissions, final int stringId, final int requestCode) {
mErrorString.put(requestCode, stringId);
int permissionCheck = PackageManager.PERMISSION_GRANTED;
boolean showRequestPermissions = false;
for(String permission: requestedPermissions) {
permissionCheck = permissionCheck + ContextCompat.checkSelfPermission(this, permission);
showRequestPermissions = showRequestPermissions || ActivityCompat.shouldShowRequestPermissionRationale(this, permission);
}
if (permissionCheck!=PackageManager.PERMISSION_GRANTED) {
if(showRequestPermissions) {
Snackbar.make(findViewById(android.R.id.content), stringId, Snackbar.LENGTH_INDEFINITE).setAction("GRANT", new View.OnClickListener() {
#Override
public void onClick(View v) {
ActivityCompat.requestPermissions(AbsRuntimePermission.this, requestedPermissions, requestCode);
}
}).show();
} else {
ActivityCompat.requestPermissions(this, requestedPermissions, requestCode);
}
} else {
onPermissionsGranted(requestCode);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
int permissionCheck = PackageManager.PERMISSION_GRANTED;
for(int permisson : grantResults) {
permissionCheck = permissionCheck + permisson;
}
if( (grantResults.length > 0) && PackageManager.PERMISSION_GRANTED == permissionCheck) {
onPermissionsGranted(requestCode);
} else {
//Display message when contain some Dangerous permisson not accept
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(new ContextThemeWrapper(this, android.R.style.Theme_Holo_Light_Dialog));
alertDialogBuilder
.setMessage("Please enble permisions")
.setTitle("Please enble permisions")
.setCancelable(false)
.setPositiveButton(" Enable",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent();
i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
i.setData(Uri.parse("package:" + getPackageName()));
i.addCategory(Intent.CATEGORY_DEFAULT);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
startActivity(i);
}
});
alertDialogBuilder.setNegativeButton(" Cancel ", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
}
}
And In Your Main Activity:
public class MainActivity extends AbsRuntimePermission {
private static final int REQUEST_PERMISSION = 10;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestAppPermissions(new String[]{
Manifest.permission.READ_CONTACTS,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.WRITE_CONTACTS},
R.string.msg,REQUEST_PERMISSION);
}
#Override
public void onPermissionsGranted(int requestCode) {
//Do anything when permisson granted
Toast.makeText(getApplicationContext(), "Permission granted", Toast.LENGTH_LONG).show();
}
}
try this:
final private int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS = 124;
public boolean checkMultiplePermission() {
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;
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(MainActivity.this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", null)
.create()
.show();
}
When every single permission got its grant result, the result will be sent to the same callback method, onRequestPermissionsResult()
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS:
{
Map<String, Integer> perms = new HashMap<String, Integer>();
// Initial
perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.READ_CONTACTS, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.WRITE_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(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.WRITE_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
// All Permissions Granted
//do your task..
} else {
// Permission Denied
Toast.makeText(MainActivity.this, "Some Permission is Denied", Toast.LENGTH_SHORT)
.show();
}
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
Hope this helps u..
do this...
on on create
int PERMISSION_ALL = 1;
String[] PERMISSIONS = {Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE};
if(!hasPermissions(this, PERMISSIONS)){
//ask user for granting permissions on api22+
ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
}
Checking if already permission...
public static boolean hasPermissions(Context context, String... permissions) {
//checaking if the application has permission
if (android.os.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;
}
This is for camera and read storage, you can add whatever you want...
you can achieve this by this way
private static final int MY_PERMISSIONS_REQUEST_CALL = 7;
private static String[] PERMISSIONS = {
Manifest.permission.CALL_PHONE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
now create a method
public void checkSmsPermission() {
try {
if (Build.VERSION.SDK_INT >= 23) {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED
|| ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED ||
ActivityCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE)
!= PackageManager.PERMISSION_GRANTED
) {
requestPermission();
} else
checkLogin();
} else {
checkLogin();
}
} catch (Exception e) {
e.printStackTrace();
}
}
you can check grants result array for checking which permission is granted
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
try {
boolean flagDenied = false;
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_CALL:
if (grantResults.length > 0
) {
for (int i : grantResults)
if (i == -1) {
flagDenied = true;
break;
}
if (!flagDenied)
doJob();
else showPermissionDialog();
}
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
My code is worked fine for one Permission. However when I want to ask
for multiple permission my code does nothing.
Leaving aside that your code is too verbose and makes it harder to read, the checkMultiplePermission() method works fine. I have copied it into a test project and when I started the app I was asked for the 5 permissions.
(5 because WRITE_EXTERNAL_STORAGE/READ_EXTERNAL_STORAGE and ACCESS_FINE_LOCATION/ACCESS_COARSE_LOCATION are merged each into a single permission request)
Please double check that you updated your AndroidManifest.xml file with the new permissions.
It can be that previously when you were testing your code with only one permission, you accepted it, then more permissions were added to the request logic but forgotten to be listed in the AndroidManifest.xml. In this case Android will ignore your request, nor will throw it an exception, it will simply do nothing.

App is not moving to next activity while all the permission is granted

I am properly allowing and denying permission and app is running properly first time but when all permission is granted and next time when user launches the app, it shows only splash screen and become stable and do not move to next activity , and it also not give any error , what i am trying is below.
private static final int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS = 5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
splashIcon = (ImageView) findViewById(R.id.splashIcon);
new Thread(new Runnable()
{
#Override
public void run()
{
Animation anim1 = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.bounce);
splashIcon.setAnimation(anim1);
anim1.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {}
#Override
public void onAnimationEnd(Animation animation) {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
checkMultiplePermissions();
}else{
startActivity(new Intent(Splash.this,UserGuideActivity.class));
finish();
}
}
#Override
public void onAnimationRepeat(Animation animation)
{
}
});
}
}).start();
}
private void checkMultiplePermissions() {
if (Build.VERSION.SDK_INT >= 23) {
List<String> permissionsNeeded = new ArrayList<String>();
List<String> permissionsList = new ArrayList<String>();
if (!addPermission(permissionsList, android.Manifest.permission.ACCESS_FINE_LOCATION))
{
permissionsNeeded.add("GPS");
}
if (!addPermission(permissionsList, android.Manifest.permission.READ_EXTERNAL_STORAGE))
{
permissionsNeeded.add("Read Storage");
}
if(!addPermission(permissionsList, Manifest.permission.READ_SMS))
{
permissionsNeeded.add("Read Sms");
}
if(!addPermission(permissionsList, Manifest.permission.READ_CONTACTS))
{
permissionsNeeded.add("Read Contacts");
}
if(!addPermission(permissionsList, Manifest.permission.READ_CALL_LOG))
{
permissionsNeeded.add("Read Calllogs");
}
if (permissionsList.size() > 0)
{
requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
}
}
}
private boolean addPermission(List<String> permissionsList, String permission) {
if (Build.VERSION.SDK_INT >= 23)
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, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS: {
Map<String, Integer> perms = new HashMap<String, Integer>();
// Initial
perms.put(android.Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED);
perms.put(android.Manifest.permission.READ_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.READ_SMS,PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.READ_CONTACTS,PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.READ_CALL_LOG,PackageManager.PERMISSION_GRANTED);
// Fill with results
for (int i = 0; i < permissions.length; i++)
perms.put(permissions[i], grantResults[i]);
if (perms.get(android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
&& perms.get(android.Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.READ_SMS)==PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.READ_CONTACTS)==PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.READ_CALL_LOG)==PackageManager.PERMISSION_GRANTED)
{
// All Permissions Granted
startActivity(new Intent(this,UserGuideActivity.class));
finish();
return;
} else {
// Permission Denied
if (Build.VERSION.SDK_INT >= 23) {
Toast.makeText(getApplicationContext(), "Please permit all the permissions", Toast.LENGTH_LONG).show();
finish();
}
}
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
because if all permissions are granted then this will be false and there is no else case to do anything
if (permissionsList.size() > 0)
{
requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
}
so it should be like this
if (permissionsList.size() > 0)
{
requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
}
else{
startActivity(new Intent(Splash.this,UserGuideActivity.class));
finish();
}
Improvements : you can eliminate creating map and loop by making reuse of checkMultiplePermissions function but modification will be required at other places accordingly
Check this condition :
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
checkMultiplePermissions();
}else{
startActivity(new Intent(Splash.this,UserGuideActivity.class));
finish();
}
Nothing will happen after checkMultiplePermissions() is run, so you need to add startActivity there only when permissions are granted.
Hope this helps !
As you described in your question that it is working first time and you are giving all permissions. So according to your code if all permissions are granted it will not go to onRequestPermissionsResult. And you have written your Intent part in that method so it will stick to same screen.
Add else statement as stated by Pavneet
Try to create method to check is all permission is granted or not if not granted then it will automatically ask each permission additional pass isAllPermissionRequired flag to use same method on onRequestPermissionsResult if you not required all permission move another screen
private static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 121;
private boolean checkAndRequestPermissions(boolean isAllPermissionRequired) {
int locationPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
int readStoragePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
int readSmsPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS);
int readContactPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS);
int readCallLogPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CALL_LOG);
List<String> listPermissionsNeeded = new ArrayList<>();
if (locationPermission != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
}
if (readStoragePermission != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.READ_EXTERNAL_STORAGE);
}
if (readSmsPermission != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.READ_SMS);
}
if (readContactPermission != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.READ_CONTACTS);
}
if (readCallLogPermission != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.READ_CALL_LOG);
}
if (!listPermissionsNeeded.isEmpty()) {
if(isAllPermissionRequired) {
ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
return false;
}else {
return true;
}
}
return true;
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
if (requestCode == REQUEST_ID_MULTIPLE_PERMISSIONS) {
if (checkAndRequestPermissions(false)) {
startActivity(new Intent(Splash.this,UserGuideActivity.class));
finish();
}
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(checkAndRequestPermissions(true)){
startActivity(new Intent(Splash.this,UserGuideActivity.class));
finish();
}
}
Note : Above sample i have pass isAllPermissionRequired = true from onCreate to ask for each permission and isAllPermissionRequired = false from onRequestPermissionsResult to not ask any permission even user not grant but you need to pass isAllPermissionRequired = true in onRequestPermissionsResult if required all permission mandatory.

Set all permissions for android app

What is the easiest/shortest way to assign all permissions to Android app ?
I need this because:
We are developing a proprietary app for android plug pc, which will be the only app that runs on the device on foreground. As we are planning for non-interrupting updates on the device I want to assign all permissions on the device during the very first installation itself.
It is better to manually give permissions to all in manifest file.
The link have all the permissions needed for an android app.
In recent time, from Marshmallow version ,android has provided requesting permission at runtime. So as soon as app starts for the first time you can ask for permissions from the user required for your app.So in your activity you can do this :
#Override
protected void onStart() {
super.onStart();
checkPermissionsAtOnce();
}
Then
private void checkPermissionsAtOnce(){
List<String> permissionsNeeded = new ArrayList<>();
final List<String> permissionsList = new ArrayList<>();
if (!addPermission(permissionsList, Manifest.permission.ACCESS_FINE_LOCATION))
permissionsNeeded.add(getString(R.string.gps));
if(!addPermission(permissionsList, Manifest.permission.SEND_SMS))
permissionsNeeded.add(getString(R.string.send_sms));
if (!addPermission(permissionsList, Manifest.permission.WRITE_EXTERNAL_STORAGE))
permissionsNeeded.add(getString(R.string.write_external_storage));
if(!addPermission(permissionsList, Manifest.permission.READ_PHONE_STATE))
permissionsNeeded.add(getString(R.string.read_phone_state));
if(!addPermission(permissionsList, Manifest.permission.CAMERA))
permissionsNeeded.add(getString(R.string.use_camera));
if (permissionsList.size() > 0) {
if (permissionsNeeded.size() > 0) {
String message = getString(R.string.grad_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) {
ActivityCompat.requestPermissions(MainActivity.this,permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
}
});
return;
}
ActivityCompat.requestPermissions(MainActivity.this, permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
return;
}
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener listener){
new AlertDialog.Builder(MainActivity.this)
.setMessage(message)
.setPositiveButton(R.string.ok, listener)
.setNegativeButton(R.string.cancel, null)
.create()
.show();
}
private boolean addPermission(List<String> permissionsList, String permission) {
if (ContextCompat.checkSelfPermission(MainActivity.this,permission) != PackageManager.PERMISSION_GRANTED) {
permissionsList.add(permission);
if (!ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, permission))
return false;
}
return true;
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS:
{
Map<String, Integer> perms = new HashMap<>();
perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.SEND_SMS, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.READ_PHONE_STATE, PackageManager.PERMISSION_GRANTED);
for (int i = 0; i < permissions.length; i++)
perms.put(permissions[i], grantResults[i]);
if(perms.get(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED){
permissionPhoneStateGranted = true;
}
/* if (perms.get(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED){
}*/
}
break;
case REQUEST_CODE_ASK_PERMISSIONS_FOR_PHONE_STATE:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission Granted
permissionPhoneStateGranted = true;
} else {
// Permission Denied
permissionPhoneStateGranted = false;
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
You can take this sample as a reference and do implement in your application.Hope it helps you..

Categories

Resources