Read_EXTERNAL_STORAGE Permission Target sdk 29 - android

Ask Permission, Am Asking for permission in My simple music app to read external Storage
It Asks for permission but doesn't list the Songs in the ListView
minSdkVersion 27
targetSdkVersion 29
It Shows the list of song after i terminate the app and start it again.
Here is my code:
public class MainActivity extends AppCompatActivity {
private int STORAGE_PERMISSION_CODE = 1;
ListView lvMusic;
MediaPlayer mp;
String name[],path[];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvMusic = (ListView) findViewById(R.id.lvMusic);
mp = new MediaPlayer();
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
null,null,null,null);
name = new String[cursor.getCount()];
path = new String[cursor.getCount()];
int i = 0;
while(cursor.moveToNext()){
name[i] =cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
path[i] = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
i++;
}
ArrayAdapter arrayAdapter =new ArrayAdapter(this, android.R.layout.simple_list_item_1,name);
if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
requestStoragePermission();
}
lvMusic.setAdapter(arrayAdapter);
}
private void requestStoragePermission(){
if(ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.READ_EXTERNAL_STORAGE)){
new AlertDialog.Builder(this)
.setTitle("Permission Needed")
.setMessage("This Permission is needed to Read Files")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
})
.setNegativeButton("Cancle", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.create().show();
}else{
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(requestCode == STORAGE_PERMISSION_CODE ){
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Toast.makeText(this,"Permission Granted",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this,"Permission not Granted",Toast.LENGTH_SHORT).show();
}
}
}
}
Thanks in advance!

Create a function loadSongs() and call it when the permission is granted.
void loadSongs(){
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
null,null,null,null);
name = new String[cursor.getCount()];
path = new String[cursor.getCount()];
int i = 0;
while(cursor.moveToNext()){
name[i] =cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
path[i] = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
i++;
}
ArrayAdapter arrayAdapter =new ArrayAdapter(this, android.R.layout.simple_list_item_1,name);
lvMusic.setAdapter(arrayAdapter);
)
Now in your on create, check if the permission is granted or not, if granted call loadSongs()
if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
requestStoragePermission();
else
loadSongs();
Now in onRequestPermission results call loadSongs if permission is granted:
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(requestCode == STORAGE_PERMISSION_CODE ){
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
loadSongs();
Toast.makeText(this,"Permission Granted",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this,"Permission not Granted",Toast.LENGTH_SHORT).show();
}
}
}

Related

Application not working in android nougat

this is my code for get permissions...but still its stop when user perform permission action(target api is 25). any other way?
boolean isMdevice;
boolean pstatus;
int code=1;
String[] perms = { android.Manifest.permission.RECEIVE_SMS, Manifest.permission.CALL_PHONE, Manifest.permission.SEND_SMS};
/////then in oncreate
isMdevice=isMarshmallowPlusDevice();
pstatus= isPermissionRequestRequired(MainActivity.this, perms, code);
////then methods
public static boolean isMarshmallowPlusDevice() {
return Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1;
}
#TargetApi(Build.VERSION_CODES.M)
public static boolean isPermissionRequestRequired(Activity activity, #NonNull String[] permissions, int requestCode) {
if (isMarshmallowPlusDevice() && permissions.length > 0) {
List<String> newPermissionList = new ArrayList<>();
for (String permission : permissions) {
if (PERMISSION_GRANTED != activity.checkSelfPermission(permission)) {
newPermissionList.add(permission);
}
}
if (newPermissionList.size() > 0) {
activity.requestPermissions(newPermissionList.toArray(new String[newPermissionList.size()]), requestCode);
return true;
}
}
return false;
}
try this code for Check permission and ask for runtime permission:
Add this class to your project
public class PermissionUtils {
public static boolean checkPermission(Context context, String permission) {
return ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED;
}
public static void requestPermissions(Activity activity, String messageInCaseOfCustomDialog, int permissionId, String... permissions) {
/* if (o instanceof Fragment) {
FragmentCompat.requestPermissions((Fragment) o, permissions, permissionId);
} else */
if (ActivityCompat.shouldShowRequestPermissionRationale(activity,
permissions[0])) {
showCustomDialogForAskPermission(activity, messageInCaseOfCustomDialog, permissionId, permissions);
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else if (/*MySharedPreference.getSharedPrefrence(activity).getBoolean(permissions[0], false)*/) { //Use your Shared Preference
// No explanation needed, we can request the permission.
showCustomDialogForGoToTheSettings(activity, messageInCaseOfCustomDialog);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
} else {
ActivityCompat.requestPermissions(activity, permissions, permissionId);
}
/*MySharedPreference.getSharedPrefrence(activity).edit().putBoolean(permissions[0], true).commit();*/ //Use your Shared Preference
}
private static void showCustomDialogForGoToTheSettings(final Activity activity, String message) {
AlertDialog.Builder dialog = new AlertDialog.Builder(activity);
dialog.setTitle("Permission Required");
dialog.setMessage(message);
dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", activity.getPackageName(), null);
intent.setData(uri);
activity.startActivity(intent);
}
});
dialog.show();
}
private static void showCustomDialogForAskPermission(final Activity activity, String message, final int permissionId, final String... permissions) {
AlertDialog.Builder dialog = new AlertDialog.Builder(activity);
dialog.setTitle("Permission Required");
dialog.setMessage(message);
dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(activity, permissions, permissionId);
}
});
dialog.show();
}
}
Now you can directly check if you have that permission or not,Suppose you want to check for READ_EXTERNAL_STORAGE permission
if (PermissionUtils.checkPermission(RegisterScreenActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
//Do your work
} else {PermissionUtils.requestPermissions(RegisterScreenActivity.this, "You need to provide storage permission for this service", 101, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE});//ask for permission
}
You can also track its result in onRequestPermissionsResult() methods like
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 101:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//permission granted, can do your work
} else {
//permission not granted
}
break;
}
}

Start the Activity After Multiple Permission?android 6+

I have Given this to Req Multiple permission at my splash screen
public class Main_MulPer extends Activity {
public static final int R_PERM = 321;
Context context = this;
public static boolean hasPermissions(Context context, String... permissions) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rcssa);
int PERMISSION_ALL = 1;
String[] PERMISSIONS = {Manifest.permission.CAMERA,
Manifest.permission.READ_PHONE_STATE,
Manifest.permission.INTERNET,
Manifest.permission.ACCESS_NETWORK_STATE,
Manifest.permission.ACCESS_WIFI_STATE,
Manifest.permission.NFC,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
};
if (!hasPermissions(this, PERMISSIONS)) {
ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
Main_MulPer.this.finish();
Intent ss = new Intent(Main_MulPer.this, Main_acti.class);
ss.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
ss.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ss.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
ss.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(ss);
} else {
if (!hasPermissions(this, PERMISSIONS)) ;
{
ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Main_MulPer.this.finish();
Intent i = new Intent(Main_MulPer.this, Splash_two.class);
startActivity(i);
}
}, 3000);
}
}
}
}
So here My problem is that Its Asking two Permission at a time...
If I try to grant them its moving to another Activity... So I have Given Similar 3 activities with 2 Permission on Each..
But Due to Handler its Opening new activities..
Then I removed Delay Handler... Now It opening Last activity... Directly...
Can Any one Suggest Me How to Start The Main Activity after All Permissions only...
Without permission It should Exit app... Please Help me on this
Update
Insted of Multiple permissions I have Splited the 3 activities with two permission each... But here It should Go to next activity after permission But its Going to last activity every time first two activity permission are missing
So I need to exit app and give them...
All I need is that without permission don't move to next screen
Can any one suggest me after permission only move to next activity....
Try this,
public class Main_nPRC extends Activity {
public static final String MainPP_SP = "MainPP_data";
public static final int R_PERM = 2822;
private static final int REQUEST= 112;
Context mContext = this;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rcssa);
SharedPreferences settings = getSharedPreferences(MainPP_SP, 0);
HashMap<String, String> map = (HashMap<String, String>) settings.getAll();
if (Build.VERSION.SDK_INT >= 23) {
Log.d("TAG","### IN IF Build.VERSION.SDK_INT >= 23");
String[] PERMISSIONS = {android.Manifest.permission.CAMERA,
android.Manifest.permission.READ_PHONE_STATE,
android.Manifest.permission.INTERNET,
android.Manifest.permission.ACCESS_NETWORK_STATE,
android.Manifest.permission.ACCESS_WIFI_STATE,
android. Manifest.permission.NFC,
android.Manifest.permission.READ_EXTERNAL_STORAGE,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
};
if (!hasPermissions(mContext, PERMISSIONS)) {
Log.d("TAG","### IN IF hasPermissions");
ActivityCompat.requestPermissions((Activity) mContext, PERMISSIONS, REQUEST );
} else {
Log.d("TAG","### IN ELSE hasPermissions");
callNextActivity();
}
} else {
Log.d("TAG","### IN ELSE Build.VERSION.SDK_INT >= 23");
callNextActivity();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d("TAG","### PERMISSIONS grant");
callNextActivity();
} else {
Log.d("TAG","### PERMISSIONS Denied");
Toast.makeText(mContext, "PERMISSIONS Denied", Toast.LENGTH_LONG).show();
}
}
}
}
private static boolean hasPermissions(Context context, String... permissions) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
public void callNextActivity()
{
Intent ss = new Intent(Main_nPRC.this, NMainSS.class);
ss.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
ss.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ss.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
ss.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(ss);
finish();
}
#Override
public void onBackPressed() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("ⓘ Exit ! " + getString(R.string.app_name));
alertDialogBuilder
.setMessage(Html.fromHtml("<p style='text-align:center;'>Please Fill the required details</p><h3 style='text-align:center;'>Click Yes to Exit !</h4>"))
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
moveTaskToBack(true);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
final int PERMISSION_REQUEST_CODE = 111;
if (Build.VERSION.SDK_INT >= 23) {
if (!checkReadContactPermission() ||!checkReadPhoneStatePermission()
|| !checkWriteExternalStorage() || !checkReadExternalStorage() ||
!checkSystemAlertWindowPermission() || !checkWriteContactPermission()) {
requestPermission();
} else {
// Move to main act
}
} else {
// Move to main act
}
You have to make method for check permission for each
for ex. this is for READ CONTACT, same way add all other
private boolean checkReadContactPermission() {
int result = ContextCompat.checkSelfPermission(activity, Manifest.permission.READ_CONTACTS);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
Method for request permissions
private void requestPermission() {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_CONTACTS,
Manifest.permission.WRITE_CONTACTS,
Manifest.permission.READ_PHONE_STATE,
/* Manifest.permission.CAMERA,*/
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE},
PERMISSION_REQUEST_CODE);
}
finally RequestPermissionResult
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
// if granted then 0 else -1
// i have 5 permisson to check so 0,1,2,3,4..
if (grantResults[0] == PackageManager.PERMISSION_GRANTED &&
grantResults[1] == PackageManager.PERMISSION_GRANTED &&
grantResults[2] == PackageManager.PERMISSION_GRANTED &&
grantResults[3] == PackageManager.PERMISSION_GRANTED &&
grantResults[4] == PackageManager.PERMISSION_GRANTED) {
// means all permission are granted..move to Main activity
} else {
// show alert
}
break;
}
}
When you request for permission(s) you'll receive results in onRequestPermissionsResult handle results from inside as google docs says here
Updated
The permissions you mentioned are grouped ones example
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
it will ask only one permission for that and one will be for calls(Reading phone state) and you don't need to ask for permission for accessing network state and internet

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.

Android: Function is not excuting with runtime permissions in Android

In the below code,getInfoFromDevice is not being executed, I also tried with a Log.d() but it could not be of further help.
In the code I am using runtime permissions to check if the user has granted permission to access external storage and if yes the function getInfoFromDevice() is called. I am not sure if the placement of the function is correct or not ? But this function is not executing. what could be the reason ?
It does not throw any error,
public class MainActivity extends Activity implements ActivityCompat.OnRequestPermissionsResultCallback {
ArrayList<String> listOfSongs = new ArrayList<String>();
ListView liststructure;
final private int REQUEST_CODE_ASK_PERMISSIONS = 123;
String MUSIC_STRING = MediaStore.Audio.Media.IS_MUSIC + "!=0";
String[] STAR = {"*"};
String orderColumns = MediaStore.Audio.AudioColumns.TITLE + " COLLATE LOCALISED ASC";
private final int REQUEST_GRANTED_BY_USER = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkPermissions();
liststructure = (ListView) findViewById(R.id.listView);
SongsList list = new SongsList(MainActivity.this, listOfSongs);
liststructure.setAdapter(list);
}
private void checkPermissions() {
int permissionCheck = ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_GRANTED_BY_USER);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if(requestCode == REQUEST_GRANTED_BY_USER )
{
getInfoFromDevice();
} else {
// Permission Denied
Toast.makeText(MainActivity.this, "EXTERNAL_STORAGE Denied", Toast.LENGTH_SHORT)
.show();
}
}
void getInfoFromDevice() {
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor cursor = getContentResolver().query(uri, STAR, MUSIC_STRING, null, null);
if (cursor != null)
{
if (cursor.moveToFirst()) {
do {
String name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
String data = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
String album = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
String albumID = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
listOfSongs.add(album + " " + name + " " + albumID);
} while (cursor.moveToNext());
}
}
}
}
Please let me know if you need more details.
EDIT 1
The code will look for mp3 files with the help of MediaStore library and will check if it has a permission to access external storage and if yes it will call the function getInfoFromDevice()
just change you code like below:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
liststructure = (ListView) findViewById(R.id.listView);
SongsList list = new SongsList(MainActivity.this, listOfSongs);
liststructure.setAdapter(list);
checkPermissions();
}
private void checkPermissions() {
if (Build.VERSION.SDK_INT >= 23) {
int permissionCheck = ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_GRANTED_BY_USER);
}else{
getInfoFromDevice();
}
}else{
getInfoFromDevice();
}
}
First check permission as below,
public void checkPermission(String permission) {
if (ContextCompat.checkSelfPermission(BaseActivity.this,
permission)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(BaseActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
ActivityCompat.requestPermissions(BaseActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
10);
} else {
ActivityCompat.requestPermissions(BaseActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
10);
}
}
}
then,
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case 10: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
// permission granted call your function
getInfoFromDevice();
} else {
// permission denied.
}
return;
}
}
}
You can also use below plugin to easily add run time permission without more effort,
https://android-arsenal.com/details/1/3571

Understanding the Android 6 permission method

I am trying to take an image from Gallery and set it to an imageview but in Android 6 there are some permission problems. Below is the method to ask for the permission. Should I ask for read external storage or write external storage?
Here is what I have done so far:
private static final int READ_CONTACTS_PERMISSIONS_REQUEST = 1;
public void getPermissionToReadExternalStorage() {
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
if (shouldShowRequestPermissionRationale(
Manifest.permission.READ_EXTERNAL_STORAGE)) {
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
READ_CONTACTS_PERMISSIONS_REQUEST);
}}}
#Override
public void onRequestPermissionsResult(int requestCode,
#NonNull String permissions[],
#NonNull int[] grantResults){
// Make sure it's our original READ_CONTACTS request
if (requestCode == READ_CONTACTS_PERMISSIONS_REQUEST) {
if (grantResults.length == 1 &&
grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getActivity(), "Read Contacts permission granted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), "Read Contacts permission denied", Toast.LENGTH_SHORT).show();
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
Now my on click listener to pick data from the Gallery:
pro.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
if (android.os.Build.VERSION.SDK_INT >= 23) {
getPermissionToReadExternalStorage();
if (getPermissionToReadExternalStorage () this???? <==)
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 0);
} else {
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 0);
}}
});
return v;
}
Now I want to get result of the method getPermissionToReadExternalStorage() so I can start the Activity for picking gallery for Android 6. How can I get the result of the void class?
And another thing is do I have to write method for every permission my app asks for?
So I have completely rewritten the code to request permissions.
Now it supports requesting for multiple permissions and running code with proper result.
Also it works with preMarshmallow devices, so you don't have to check and copy the code in that case.
First, create an Activity class with this code (You can extend any king of activity you need, e.g. AppCompatActivity):
public abstract class PermissionActivity extends AppCompatActivity {
private final ArrayList<PermissionListener> permissionListeners = new ArrayList<>();
#SuppressWarnings("unused")
public void requestPermissions(int requestCode, String[] requestPermissions, PermissionListener permissionListener) {
requestPermissions(requestCode, requestPermissions, null, permissionListener);
}
#SuppressWarnings("unused")
public void requestPermissions(final int requestCode, String[] requestPermissions, String message, final PermissionListener permissionListener) {
final int[] grantResults = new int[requestPermissions.length];
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
ArrayList<String> list_notGranted = new ArrayList<>();
for (String requestPermission : requestPermissions)
if (ContextCompat.checkSelfPermission(this, requestPermission) != PackageManager.PERMISSION_GRANTED)
list_notGranted.add(requestPermission);
if (list_notGranted.size() > 0) {
permissionListeners.add(permissionListener);
requestPermissions = list_notGranted.toArray(new String[list_notGranted.size()]);
if (message != null) {
boolean shouldShowRequestPermissionRationale = false;
for (String permission : requestPermissions)
if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
shouldShowRequestPermissionRationale = true;
break;
}
if (shouldShowRequestPermissionRationale) {
final String[] f_requestPermissions = requestPermissions;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message);
DialogInterface.OnClickListener onClickListener = new DialogInterface.OnClickListener() {
#TargetApi(Build.VERSION_CODES.M)
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
PermissionActivity.super.requestPermissions(f_requestPermissions, requestCode);
break;
default:
for (int i = 0; i < grantResults.length; i++)
grantResults[i] = PackageManager.PERMISSION_DENIED;
if (permissionListener != null)
permissionListener.onResult(requestCode, f_requestPermissions, grantResults);
break;
}
}
};
builder.setPositiveButton("OK", onClickListener);
builder.setNegativeButton("Cancel", onClickListener);
builder.show();
} else {
super.requestPermissions(requestPermissions, requestCode);
}
} else {
super.requestPermissions(requestPermissions, requestCode);
}
} else {
for (int i = 0; i < grantResults.length; i++)
grantResults[i] = PackageManager.PERMISSION_GRANTED;
if (permissionListener != null)
permissionListener.onResult(requestCode, requestPermissions, grantResults);
}
} else {
if (permissionListener != null) {
for (int i = 0; i < grantResults.length; i++)
grantResults[i] = PackageManager.PERMISSION_GRANTED;
permissionListener.onResult(requestCode, requestPermissions, grantResults);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[], #NonNull int[] grantResults) {
for (Iterator<PermissionListener> it = permissionListeners.iterator(); it.hasNext(); ) {
PermissionListener permissionListener = it.next();
if (permissionListener.onResult(requestCode, permissions, grantResults)) {
it.remove();
}
}
}
public interface PermissionListener {
boolean onResult(int requestCode, String[] requestPermissions, int[] grantResults);
}
}
If you want to request permissions from Fragments, add this class:
public class PermissionFragment extends Fragment {
#SuppressWarnings("unused")
public void requestPermissions(int requestCode, String[] requestPermissions, PermissionActivity.PermissionListener permissionListener) {
requestPermissions(requestCode, requestPermissions, null, permissionListener);
}
#SuppressWarnings("unused")
public void requestPermissions(final int requestCode, String[] requestPermissions, String message, PermissionActivity.PermissionListener permissionListener) {
((PermissionActivity) getActivity()).requestPermissions(requestCode, requestPermissions, message, permissionListener);
}
}
Your Activities and Fragments should extend these classes instead of the standart ones.
Now you are ready to request the permissions by calling a method:
requestPermissions(int requestCode, String[] requestPermissions, PermissionListener permissionListener)
If the permission is required for the app to work, you should call this method and specify the message saying why the permission is required.
requestPermissions(int requestCode, String[] requestPermissions, String message, PermissionListener permissionListener)
DONT MISSCALL THE DEFAULT METHOD, WHICH IS
// DON'T USE THIS ONE!
requestPermissions(String[] requestPermissions, int requestCode)
// DON'T USE THIS ONE!
Here is the example of requesting contacts:
private void requestAndLoadContacts() {
String[] permissions = new String[]{Manifest.permission.READ_CONTACTS};
requestPermissions(REQUEST_PERMISSIONS_CONTACTS, permissions, "Read contacts permission is required for the app to work!", new PermissionListener() {
#Override
public boolean onResult(int requestCode, String[] requestPermissions, int[] grantResults) {
// Check if the requestCode is ours
if (requestCode == REQUEST_PERMISSIONS_CONTACTS) {
// Check if the permission is correct and is granted
if (requestPermissions[0].equals(Manifest.permission.READ_CONTACTS) && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission granted
// Calling a method to actually load the contacts
loadContacts();
} else {
// Permission not granted
Toast.makeText(MainActivity.this, "Access denied!", Toast.LENGTH_SHORT).show();
}
return true;
}
return false;
}
});
}
NOTE:
When you implement the PermissionListener, don't forget to return true when the requestCode is the correct one, otherwise the PermissionListener won't be removed from the ArrayList and you'll most likely get a small memory leak.
EDIT
I have rewritted the code and posted in another answer.
Old answer:
Yes, you have to check and ask for permission every time.
Usually I write the code like this:
private int requestPermissionCode;
private Runnable requestPermissionRunnable;
private void runPermissionCode(String requestPermission, int requestCode, Runnable codeToRun) {
if (android.os.Build.VERSION.SDK_INT >= 23) {
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissionCode = requestCode;
requestPermissionRunnable = codeToRun;
requestPermissions(new String[]{requestPermission},
requestCode);
}
} else {
codeToRun.run();
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
#NonNull String permissions[],
#NonNull int[] grantResults) {
if (requestCode == requestPermissionCode) {
if (grantResults.length == 1 &&
grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (requestPermissionRunnable != null)
requestPermissionRunnable.run();
} else {
Toast.makeText(getActivity(), "Permission denied", Toast.LENGTH_SHORT).show();
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
and run it like this:
runPermissionCode(Manifest.permission.READ_EXTERNAL_STORAGE, READ_CONTACTS_PERMISSIONS_REQUEST, new Runnable() {
#Override
public void run() {
// your code here
}
});
I am sure it is not a best way, but at least it gives a possibility to request permission and make actions easier.
Initialize Your Permission
private static final int INITIAL_REQUEST = 1337;
private static final int GET_ACCOUNTS = INITIAL_REQUEST+2;
private static final int LOCATION_REQUEST =INITIAL_REQUEST+3;
private static final String[] INITIAL_PERMS = {
Manifest.permission.GET_ACCOUNTS,
Manifest.permission.INTERNET,
Manifest.permission.ACCESS_FINE_LOCATION
};
Check for device and Request for permissions
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!canAccessAccounts()|| !canAccessLocation() ||!canAccessInternet()) {
requestPermissions(INITIAL_PERMS, INITIAL_REQUEST);
}
}
Check Permission is granted Or not
private boolean canAccessAccounts() {
return (hasPermission(Manifest.permission.GET_ACCOUNTS));
}
private boolean canAccessLocation() {
return (hasPermission(Manifest.permission.ACCESS_FINE_LOCATION));
}
private boolean canAccessInternet() {
return (hasPermission(Manifest.permission.INTERNET));
}
private boolean hasPermission(String perm) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return (PackageManager.PERMISSION_GRANTED == checkSelfPermission(perm));
}
return (true);
}
Update Permissions and Check method for permissions onRequestPermissionsResult
void UpdatePermissions(){
canAccessInternet();
canAccessLocation();
canAccessInternet();
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
UpdatePermissions();
switch(requestCode) {
case GET_ACCOUNTS:
if (canAccessAccounts()) {
}
else {
}
break;
case LOCATION_REQUEST:
if (canAccessLocation()) {
}
else {
}
break;
case INITIAL_REQUEST:
if(canAccessInternet()){
}else {
}
break;
}
}

Categories

Resources