i try to copy a sqlite database from file in my external storage this worked fine in android version ( 4 and 5 ) but doesn't work in android 6 (marshmallow) why ?? please help , As required, in its manifest, the following permissions are requested :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
here is my code :
if (Build.VERSION.SDK_INT >= 23) {
if (ContextCompat.checkSelfPermission(Main2ActivityAdmin.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(Main2ActivityAdmin.this, android.Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(Main2ActivityAdmin.this,
new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE},
1);
} else {
Toast.makeText(Main2ActivityAdmin.this, "permission erreur", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(Main2ActivityAdmin.this, "ok", Toast.LENGTH_LONG).show();
}
private boolean copyDatabase(Context context) {
try {
//InputStream inputStream = context.getAssets().open(DatabaseHelper.DBNAME);
File sdcard = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File file = new File(sdcard, "sample.sqlite");
InputStream inputStream = null;
inputStream = new BufferedInputStream(new FileInputStream(file.getAbsolutePath()));
String outFileName = DatabaseHelper.DBLOCATION + DatabaseHelper.DBNAME;
OutputStream outputStream = new FileOutputStream(outFileName);
byte[]buff = new byte[1024];
int length = 0;
while ((length = inputStream.read(buff)) > 0) {
outputStream.write(buff, 0, length);
}
outputStream.flush();
outputStream.close();
Log.w("MainActivity","DB copied");
return true;
}catch (Exception e) {
e.printStackTrace();
return false;
}
Try this to put the permission
Also change WRITE_EXTERNAL_STORAGE to READ_EXTERNAL_STORAGE for Read permission
public class MyActivity extends AppCompatActivity {
private static final int REQUEST_RUNTIME_PERMISSION = 123;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (CheckPermission(MyActivity .this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
// you have permission go ahead
} else {
// you do not have permission go request runtime permissions
RequestPermission(MyDevIDS.this, Manifest.permission.WRITE_EXTERNAL_STORAGE, REQUEST_RUNTIME_PERMISSION);
}
}
#Override
public void onRequestPermissionsResult(int permsRequestCode, String[] permissions, int[] grantResults) {
switch (permsRequestCode) {
case REQUEST_RUNTIME_PERMISSION: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// you have permission go ahead
} else {
// you do not have permission show toast.
}
return;
}
}
}
public void RequestPermission(MyActivity thisActivity, String Permission, int Code) {
if (ContextCompat.checkSelfPermission(thisActivity,
Permission)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Permission)) {
} else {
ActivityCompat.requestPermissions(thisActivity,
new String[]{Permission},
Code);
}
}
}
public boolean CheckPermission(MyActivity context, String Permission) {
if (ContextCompat.checkSelfPermission(context,
Permission) == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
}
Related
I want to show whatsapp statuses in my app.
Till now I have done following:
public final String getStatusPath(boolean z) {
if (Build.VERSION.SDK_INT < 30) {
if (z) {
return Environment.getExternalStorageDirectory().getAbsolutePath() + "/WhatsApp Business/Media/.Statuses";
}
return Environment.getExternalStorageDirectory().getAbsolutePath() + "/WhatsApp/Media/.Statuses";
} else if (z) {
return Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/media/com.whatsapp.w4b/WhatsApp Business/Media/.Statuses";
} else {
return Environment.getExternalStorageDirectory().getAbsolutePath()+ "/Android/media/com.whatsapp/WhatsApp/Media/.Statuses";
}
}
private ArrayList<WhatStatusData> getStatusList() {
ArrayList<WhatStatusData> arrayList = new ArrayList<>();
File[] listFiles = new File(FileConstants.INSTANCE.getStatusPath(isBusiness)).listFiles();
int i = 0;
if (listFiles != null) {
if (listFiles.length == 0) {
Arrays.sort(listFiles);
}
int length = listFiles.length;
while (i < length) {
File file = listFiles[i];
i++;
String absolutePath = file.getAbsolutePath();
Uri fromFile = Uri.fromFile(file);
String name = file.getName();
if (!name.equals(".nomedia")) {
arrayList.add(new WhatStatusData(absolutePath, fromFile, name));
}
}
}
return arrayList;
}
In manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
But I am not getting data in android 11.In other versions code is working properly.
Got the solution
There are two possibility for getting hidden files access in android 11
give MANAGE_EXTERNAL_STORAGE permission as said by #Subarata Talukder
give particular folder access permission using storage manager as explained below (without using MANAGE_EXTERNAL_STORAGE permission)
Here I am showing how to access whatsapp statuses programmatically
//give permissions in manifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
//give run time permissions
static final int REQUEST_PERMISSION_KEY = 1;
int REQUEST_ACTION_OPEN_DOCUMENT_TREE = 101;
SharedPreferences sharedPreferences;
check if run time permissions are given or not on button click
if(sharedPreferences.getString("WATREE","").equals("")){
if(checkAndRequestPermissions()){
if (SDK_INT >= Build.VERSION_CODES.Q) {
askPermission();
}else {
callActivity();
}
}
}else{
callActivity();
}
private boolean checkAndRequestPermissions() {
int writePerm = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE);
int readPerm = ContextCompat.checkSelfPermission(getApplicationContext(),Manifest.permission.READ_EXTERNAL_STORAGE);
List<String> listPermissionsNeeded = new ArrayList<>();
if (writePerm != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
if(readPerm != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.READ_EXTERNAL_STORAGE);
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(GBV_StartActivity.this,
listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),
REQUEST_PERMISSION_KEY);
return false;
}
return true;
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSION_KEY) {
try {
Map<String, Integer> permsLogin = new HashMap<>();
// Initialize the map with both permissions
permsLogin.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
permsLogin.put(Manifest.permission.READ_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
// Fill with actual results from user
if (grantResults.length > 0) {
for (int i = 0; i < permissions.length; i++)
permsLogin.put(permissions[i], grantResults[i]);
// Check for both permissions
if (permsLogin.get(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
&& permsLogin.get(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
if (SDK_INT >= Build.VERSION_CODES.Q) {
askPermission();
}else {
callActivity();
}
// process the normal flow
//else any one or both the permissions are not granted
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)
|| shouldShowRequestPermissionRationale(Manifest.permission.READ_EXTERNAL_STORAGE)) {
showDialogOK((dialog, 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.
break;
}
});
}
//permission is denied (and never ask again is checked)
//shouldShowRequestPermissionRationale will return false
else {
Toast.makeText(getApplicationContext(), "Go to settings and enable permissions.", Toast.LENGTH_LONG)
.show();
finish();
//proceed with logic by disabling the related features or quit the app.
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void showDialogOK(DialogInterface.OnClickListener okListener) {
android.app.AlertDialog.Builder alertDialogBuilder = new android.app.AlertDialog.Builder(GBV_StartActivity.this);
alertDialogBuilder.setMessage("You need to allow access to the permissions.")
.setCancelable(false)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", okListener);
android.app.AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
public void callActivity(){
startActivity(new Intent(GBV_StartActivity.this, MainActivity.class));
}
private String getWhatsupFolder() {
String oldPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/WhatsApp/Media/.Statuses";
String oldBusinessPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/WhatsApp Business/Media/.Statuses";
String newPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/media/com.whatsapp/WhatsApp/Media/.Statuses";
String newBusinessPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/media/com.whatsapp.w4b/WhatsApp Business/Media/.Statuses";
String finalPath;
if(new File(newBusinessPath).exists()){
finalPath = "Android%2Fmedia%2Fcom.whatsapp.w4b%2FWhatsApp Business%2FMedia%2F.Statuses";
}else if(new File(newPath).exists()){
finalPath = "Android%2Fmedia%2Fcom.whatsapp%2FWhatsApp%2FMedia%2F.Statuses";
}else if(new File(oldBusinessPath).exists()){
finalPath = "WhatsApp Business%2FMedia%2F.Statuses";
}else {
finalPath = "WhatsApp%2FMedia%2F.Statuses";
}
return finalPath;
}
#RequiresApi(Build.VERSION_CODES.Q)
private void askPermission() {
StorageManager storageManager = (StorageManager) getSystemService(STORAGE_SERVICE);
Intent intent = storageManager.getPrimaryStorageVolume().createOpenDocumentTreeIntent();
String targetDirectory = getWhatsupFolder(); // add your directory to be selected by the user
Uri uri = intent.getParcelableExtra("android.provider.extra.INITIAL_URI");
String scheme = uri.toString();
scheme = scheme.replace("/root/", "/document/");
scheme += "%3A"+targetDirectory;
uri = Uri.parse(scheme);
Log.w("TAG", "askPermission: uri::"+uri );
intent.putExtra("android.provider.extra.INITIAL_URI", uri);
startActivityForResult(intent, REQUEST_ACTION_OPEN_DOCUMENT_TREE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == this.REQUEST_ACTION_OPEN_DOCUMENT_TREE && resultCode == -1) {
Uri data = intent.getData();
try {
getContentResolver().takePersistableUriPermission(data, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
} catch (Exception e) {
e.printStackTrace();
}
SharedPreferences.Editor editor2 = sharedPreferences.edit();
editor2.putString("WATREE", data.toString());
editor2.apply();
callActivity();
}
}
now after giving all permissions try to get images or videos from storage like below:
if (SDK_INT >= Build.VERSION_CODES.Q) {
DocumentFile[] allFiles = getFromSdcard();
if (allFiles != null) {
for(int i = 0 ; i <allFiles.length ; i++){
if (!allFiles[i].getUri().toString().contains(".nomedia")) {
Log.e("path:",allFiles[i].getUri().toString());
//add data in your arraylist
}
}
}
}else {
String oldPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/WhatsApp/Media/.Statuses";
String oldBusinessPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/WhatsApp Business/Media/.Statuses";
String newPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/media/com.whatsapp/WhatsApp/Media/.Statuses";
String newBusinessPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/media/com.whatsapp.w4b/WhatsApp Business/Media/.Statuses";
String finalPath;
if (!new File(oldPath).exists()) {
if (!new File(oldBusinessPath).exists()) {
if (!new File(newPath).exists()) {
if (!new File(newBusinessPath).exists()) {
finalPath = oldPath;
} else {
finalPath = newBusinessPath;
}
} else {
finalPath = newPath;
}
} else {
finalPath = oldBusinessPath;
}
} else {
finalPath = oldPath;
}
File file2 = new File(finalPath);
if (file2.exists()) {
File[] listFiles = file2.listFiles();
if (listFiles != null) {
for (int i = 0; i < listFiles.length; i++) {
Log.e("path:",listFiles[i].getPath()+"");
//add data in your arraylist
}
}
}
}
public DocumentFile[] getFromSdcard() {
DocumentFile fromTreeUri = DocumentFile.fromTreeUri(getContext(), Uri.parse(sharedPreferences.getString("WATREE","")));
if (fromTreeUri == null || !fromTreeUri.exists() || !fromTreeUri.isDirectory() || !fromTreeUri.canRead() || !fromTreeUri.canWrite()) {
return null;
}
return fromTreeUri.listFiles();
}
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" />
In Android the Camera action show a error:
java.lang.SecurityException: Permission Denial: starting Intent { act=android.media.action.IMAGE_CAPTURE cmp=android/com.android.internal.app.ResolverActivity } from ProcessRecord{beb99ec 32121:com.android.hawee/u0a369} (pid=32121, uid=10369) with revoked permission android.permission.CAMERA
at android.os.Parcel.readException(Parcel.java:1620)
I request permission on manifest as follows
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
And on chooserDialog on click of camera
if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, Constants.CAMERA_CAPTURE_PERMISSIONS_REQUEST_CODE);
} else {
Intent camera = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
activity.startActivityForResult(camera, Constants.IMAGE_CAPTURE_CAMERA);
}
On activity
#SuppressLint("NewApi")
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.frameContainer);
fragment.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
And on Fragment
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
if (requestCode == Constants.CAMERA_CAPTURE_PERMISSIONS_REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
Intent camera = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(camera, Constants.IMAGE_CAPTURE_CAMERA);
} else {
new CommonDialogOK(getActivity(), getString(R.string.Sorry), getString(R.string.Permissions_Not_Granted));
}
} else if (requestCode == Constants.PICK_IMAGE_PERMISSIONS_REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Intent gallery = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(gallery, Constants.IMAGE_CAPTURE_GALLERY);
} else {
new CommonDialogOK(getActivity(), getString(R.string.Sorry), getString(R.string.Permissions_Not_Granted));
}
}
}
But on click from ChooserDialog always get above error.
How can i ask permission for write to external and Image capture at same time.
If camera n external storage both are required for your app you should || them in if condition.
if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, Constants.CAMERA_CAPTURE_PERMISSIONS_REQUEST_CODE);
} else {
Intent camera = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
activity.startActivityForResult(camera, Constants.IMAGE_CAPTURE_CAMERA);
}
Try this :-
public static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 1;
in onCreate()
private void checkAndroidVersion() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkAndRequestPermissions();
}
}
This method
private boolean checkAndRequestPermissions() {
int camera = ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.CAMERA);
int wtite = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE);
int read = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE);
List<String> listPermissionsNeeded = new ArrayList<>();
if (wtite != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
if (camera != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.CAMERA);
}
if (read != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.READ_EXTERNAL_STORAGE);
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(getActivity(), listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
return false;
}
return true;
}
then use this
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
Log.d("in fragment on request", "Permission callback called-------");
switch (requestCode) {
case REQUEST_ID_MULTIPLE_PERMISSIONS: {
Map<String, Integer> perms = new HashMap<>();
// Initialize the map with both permissions
perms.put(Manifest.permission.CAMERA, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.READ_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.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED && perms.get(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
Log.d("in fragment on request", "CAMERA & WRITE_EXTERNAL_STORAGE READ_EXTERNAL_STORAGE permission granted");
// process the normal flow
//else any one or both the permissions are not granted
} else {
Log.d("in fragment on request", "Some permissions are not granted ask again ");
//permission is denied (this is the first time, when "never ask again" is not checked) so ask again explaining the usage of permission
// // shouldShowRequestPermissionRationale will return true
//show the dialog or snackbar saying its necessary and try again otherwise proceed with setup.
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.CAMERA) || ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) || ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)) {
showDialogOK("Camera and Storage Permission required for this app",
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.
break;
}
}
});
}
//permission is denied (and never ask again is checked)
//shouldShowRequestPermissionRationale will return false
else {
Toast.makeText(getActivity(), "Go to settings and enable permissions", Toast.LENGTH_LONG)
.show();
// //proceed with logic by disabling the related features or quit the app.
}
}
}
}
}
}
private void showDialogOK(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(getActivity())
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", okListener)
.create()
.show();
}
And Finally on button click when u save profile or so
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!checkAndRequestPermissions()) {
}
else {
// do your stuff here
}
} else {
// do your stuff here
}
Try this code:
For Checking permission I created a separate class as below:
public class MarshMallowPermission {
public static final int RECORD_PERMISSION_REQUEST_CODE = 1;
public static final int EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE = 2;
public static final int CAMERA_PERMISSION_REQUEST_CODE = 3;
Activity activity;
public MarshMallowPermission(Activity activity) {
this.activity = activity;
}
public boolean checkPermissionForRecord(){
int result = ContextCompat.checkSelfPermission(activity, Manifest.permission.RECORD_AUDIO);
if (result == PackageManager.PERMISSION_GRANTED){
return true;
} else {
return false;
}
}
public boolean checkPermissionForExternalStorage(){
int result = ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (result == PackageManager.PERMISSION_GRANTED){
return true;
} else {
return false;
}
}
public boolean checkPermissionForCamera(){
int result = ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA);
if (result == PackageManager.PERMISSION_GRANTED){
return true;
} else {
return false;
}
}
public void requestPermissionForRecord(){
if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.RECORD_AUDIO)){
Toast.makeText(activity, "Microphone permission needed for recording. Please allow in App Settings for additional functionality.", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(activity,new String[]{Manifest.permission.RECORD_AUDIO},RECORD_PERMISSION_REQUEST_CODE);
}
}
public void requestPermissionForExternalStorage(){
if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)){
Toast.makeText(activity, "External Storage permission needed. Please allow in App Settings for additional functionality.", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(activity,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE);
}
}
public void requestPermissionForCamera(){
if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.CAMERA)){
Toast.makeText(activity, "Camera permission needed. Please allow in App Settings for additional functionality.", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(activity,new String[]{Manifest.permission.CAMERA},CAMERA_PERMISSION_REQUEST_CODE);
}
}
}
Then
MarshMallowPermission marshMallowPermission = new
MarshMallowPermission(this);
public void getPhotoFromCamera() {
if (!marshMallowPermission.checkPermissionForCamera()) {
marshMallowPermission.requestPermissionForCamera();
} else {
if (!marshMallowPermission.checkPermissionForExternalStorage()) {
marshMallowPermission.requestPermissionForExternalStorage();
} else {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File mediaStorageDir = new File(
Environment.getExternalStorageDirectory()
+ File.separator
+ getString(R.string.directory_name_corp_chat)
+ File.separator
+ getString(R.string.directory_name_images)
);
if (!mediaStorageDir.exists()) {
mediaStorageDir.mkdirs();
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
try {
mediaFile = File.createTempFile(
"IMG_" + timeStamp, /* prefix */
".jpg", /* suffix */
mediaStorageDir /* directory */
);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mediaFile));
startActivityForResult(takePictureIntent, PICK_FROM_CAMERA);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
The answer needs more upvotes and should be the official answer about permissions with camera, the other answers don't solved the problem on Android 10.
And how we know, the answers/codes that work on new versions works on olders.
Help us to index this answer:
if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, Constants.CAMERA_CAPTURE_PERMISSIONS_REQUEST_CODE);
} else {
Intent camera = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
activity.startActivityForResult(camera, Constants.IMAGE_CAPTURE_CAMERA);
}
Android Version on Phone : 6.0.1 ( Android marshmallow )
Android target SDK Version 25
I Calling the ActivityCompat.requestPermissions in Android button but doesn't show dialog to Procced it
Button
printrequest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
try{
verifyStoragePermissions(SickFragmentId.this);
}
catch(Exception e ){
Log.e("LoginActv: Save Block", e.getMessage());
e.getStackTrace();
}
String req = textViewReqNo.getText().toString();
String name = Name.getText().toString();
String branch = Branch.getText().toString();
String departement_position = Departement_Position.getText().toString();
String status = Status.getText().toString();
String description = Description.getText().toString();
String type = Status.getText().toString();
String date = Date.getText().toString();
Intent showId = new Intent(SickFragmentId.this, print.class);
startActivity(showId);
}
});
And i put the code in Print.java
public class print extends Activity {
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
public static void verifyStoragePermissions(Activity activity) {
int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
Log.e("Permission value", permission + " ");
if (permission != 1) {
Log.e("Permission ask", "Asking, permission not granted");
ActivityCompat.requestPermissions(
activity,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 200) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.e("PERResult", "Granted");
String FILE = Environment.getExternalStorageDirectory().toString()
+ "/PDF/" + "AldanRIZKISANTOSA.pdf";
Document document = new Document(PageSize.A4);
// Create Directory in External Storage
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/PDF");
myDir.mkdirs();
// Create Pdf Writer for Writting into New Created Document
try {
PdfWriter.getInstance(document, new FileOutputStream(FILE));
// Open Document for Writting into document
document.open();
// User Define Method
addMetaData(document);
addTitlePage(document);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Close Document after writting all content
document.close();
Toast.makeText(this, "PDF File is Created. Location : " + FILE,
Toast.LENGTH_LONG).show();
} else {
Log.e("PERResult", "Denied");
Toast.makeText(getApplicationContext(), "PERMISSION_DENIED", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
// Set PDF document Properties
public void addMetaData(Document document)
{
document.addTitle("RESUME");
document.addSubject("Person Info");
document.addKeywords("Personal, Education, Skills");
document.addAuthor("TAG");
document.addCreator("TAG");
}
public void addTitlePage(Document document) throws DocumentException {
// Font Style for Document
Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD);
Font titleFont = new Font(Font.FontFamily.TIMES_ROMAN, 22, Font.BOLD
| Font.UNDERLINE, BaseColor.GRAY);
Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD);
Font normal = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.NORMAL);
// Start New Paragraph
Paragraph prHead = new Paragraph();
// Set Font in this Paragraph
prHead.setFont(titleFont);
// Add item into Paragraph
prHead.add("RESUME – Name\n");
// Create Table into Document with 1 Row
PdfPTable myTable = new PdfPTable(1);
// 100.0f mean width of table is same as Document size
myTable.setWidthPercentage(100.0f);
// Create New Cell into Table
PdfPCell myCell = new PdfPCell(new Paragraph(""));
myCell.setBorder(Rectangle.BOTTOM);
// Add Cell into Table
myTable.addCell(myCell);
prHead.setFont(catFont);
prHead.add("\nName1 Name2\n");
prHead.setAlignment(Element.ALIGN_CENTER);
// Add all above details into Document
document.add(prHead);
document.add(myTable);
document.add(myTable);
// Now Start another New Paragraph
Paragraph prPersinalInfo = new Paragraph();
prPersinalInfo.setFont(smallBold);
prPersinalInfo.add("Address 1\n");
prPersinalInfo.add("Address 2\n");
prPersinalInfo.add("City: SanFran. State: CA\n");
prPersinalInfo.add("Country: USA Zip Code: 000001\n");
prPersinalInfo
.add("Mobile: 9999999999 Fax: 1111111 Email: john_pit#gmail.com \n");
prPersinalInfo.setAlignment(Element.ALIGN_CENTER);
document.add(prPersinalInfo);
document.add(myTable);
document.add(myTable);
Paragraph prProfile = new Paragraph();
prProfile.setFont(smallBold);
prProfile.add("\n \n Profile : \n ");
prProfile.setFont(normal);
prProfile
.add("\nI am Mr. XYZ. I am Android Application Developer at TAG.");
prProfile.setFont(smallBold);
document.add(prProfile);
// Create new Page in PDF
document.newPage();
}
}
But the Dialog for permission doesn't show
Before i use ActivityCompat.requestPermissions i have error
java.io.FileNotFoundException: /storage/emulated/0/PDF/Name.pdf (Permission denied)
After i use ActivityCompat.requestPermission i have error
E/Permission value: -1
E/Permission ask: Asking, permission not granted
if( hasPermissionWriteExternalStorage()){
//do smth
}
public boolean hasPermissionWriteExternalStorage() {
if (Build.VERSION.SDK_INT >= 23) {
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_WRITE_EXTERNAL_STORAGE);
return false;
}
} else { //permission is automatically granted on sdk<23 upon installation
return true;
}
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {case PERMISSION_WRITE_EXTERNAL_STORAGE: {
if (getActivity().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
//do smth
} else {
Toast.makeText(getActivity(), "Access Denied", Toast.LENGTH_SHORT).show();
}
break;
}
}
}
in onCreate() method;
requestStoragePermission();
and define this method;
private void requestStoragePermission() {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
return;
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
return;
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
return;
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.GET_ACCOUNTS) == PackageManager.PERMISSION_GRANTED)
return;
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED)
return;
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED)
return;
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED)
return;
if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.READ_EXTERNAL_STORAGE)) {
//If the user has denied the permission previously your code will come to this block
//Here you can explain why you need this permission
//Explain here why you need this permission
}
if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
}
if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.ACCESS_FINE_LOCATION)) {
}
if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.GET_ACCOUNTS)) {
}
if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.READ_CONTACTS)) {
}
if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.CAMERA)) {
}
if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.READ_PHONE_STATE)) {
}
//And finally ask for the permission
ActivityCompat.requestPermissions(this, new String[]
{
android.Manifest.permission.READ_EXTERNAL_STORAGE,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.GET_ACCOUNTS,
android.Manifest.permission.READ_CONTACTS,
android.Manifest.permission.CAMERA,
android.Manifest.permission.READ_PHONE_STATE
}, STORAGE_PERMISSION_CODE);
}
//This method will be called when the user will tap on allow or deny
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//Checking the request code of our request
if (requestCode == STORAGE_PERMISSION_CODE) {
//If permission is granted
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Displaying a toast
Toast.makeText(this, "Permission granted now you can read the storage", Toast.LENGTH_LONG).show();
} else {
//Displaying another toast if permission is not granted
Toast.makeText(this, "Oops you just denied the permission", Toast.LENGTH_LONG).show();
}
}
}
I have some confusion for the android cache, at run time android app cache required external storage read and write permissions or not. can any one help me for this confusion. For example,
File tempFile = File.createTempFile("img", ".png", getExternalCacheDir());
String imgPath = tempFile.getAbsolutePath();
Try this,
Storage permission
private static final int REQUEST_STORAGE = 112;
if (Build.VERSION.SDK_INT >= 23) {
String[] PERMISSIONS = {android.Manifest.permission.WRITE_EXTERNAL_STORAGE,android.Manifest.permission.READ_EXTERNAL_STORAGE};
if (!hasPermissions(mContext, PERMISSIONS)) {
ActivityCompat.requestPermissions((Activity) mContext, PERMISSIONS, REQUEST_STORAGE );
} else {
File tempFile = File.createTempFile("img", ".png", getExternalCacheDir());
imgPath = tempFile.getAbsolutePath();
}
} else {
File tempFile = File.createTempFile("img", ".png", getExternalCacheDir());
imgPath = tempFile.getAbsolutePath();
}
get Permissions Result
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_STORAGE: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
File tempFile = File.createTempFile("img", ".png", getExternalCacheDir());
imgPath = tempFile.getAbsolutePath();
}
}
}
}
check permissions for marshmallow
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;
}
You have to ask permission at runtime https://developer.android.com/training/permissions/requesting.html, Example,
public void requestPermissionForExternalStorage() {
if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(activity, "External Storage permission needed. Please allow in App Settings for additional functionality.", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE);
}
}