I have a method that should check if some permission that I need to have are Granted or not :
public boolean checkCamera(){
String[] permissions= new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.CAMERA};
int result;
List<String> listPermissionsNeeded = new ArrayList<>();
for (String p:permissions) {
result = ContextCompat.checkSelfPermission(getApplicationContext(),p);
if (result != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(p);
}
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),MULTIPLE_PERMISSIONS );
return false;
}
return true;
}
If not, it request these permissions. The problem is, if I denied one of them it pass as valid Permission.
private void requestPermissionCamera(){
if(checkCamera()){
values.put(MediaStore.Images.Media.TITLE, "New Picture");
values.put(MediaStore.Images.Media.DESCRIPTION, "From your Camera");
imageUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent,requestCodeCamera);
}
}
In the moment that checks, it's not returning false as it should and on RequestResult the same thing.
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case MULTIPLE_PERMISSIONS:
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
values.put(MediaStore.Images.Media.TITLE, "New Picture");
values.put(MediaStore.Images.Media.DESCRIPTION, "From your Camera");
imageUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent,requestCodeCamera);
} else {
Toast.makeText(this, "Not All permissions are granted", Toast.LENGTH_SHORT).show();
}
break;
case READ_STORAGE:
Related
My Topic,
i am trying to take storage permission in android, my permission code works in below andoid 11 ,
but problem is when i try to take storage permission in android 11 then code not works , so please help me..
This is my code:-
This is my AndroidManifest.xml Code
android:requestLegacyExternalStorage="true"
This is my JavaCode Code
#Override
protected void onActivityResult(int _requestCode, int _resultCode, Intent _data) {
super.onActivityResult(_requestCode, _resultCode, _data);
if (_resultCode == RESULT_OK){
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.R){
if (Environment.isExternalStorageManager()){
Toast.makeText(this,"Permission Granted",Toast.LENGTH_SHORT).show();
i.setClass(getApplicationContext(), Main2Activity.class);
startActivity(i);
} else {
_takePermission();
}
}
}
switch (_requestCode) {
default:
break;
}
}
public boolean _isPermissionGranted() {
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.R){
return Environment.isExternalStorageManager();
} else {
int readexternalStoragePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
return readexternalStoragePermission == PackageManager.PERMISSION_GRANTED;
}
}
public void _takePermission() {
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.R) {
try {
Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
intent.addCategory("android.intent.category.DEFAULT");
intent.setData(Uri.parse(String.format("package:%s",getApplicationContext().getPackageName())));
startActivityForResult(intent,100);
} catch (Exception exception){
Intent intent = new Intent();
intent.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
startActivityForResult(intent,100);
}
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},101);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0){
if (requestCode == 101){
boolean readExternalStorage = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if (readExternalStorage){
Toast.makeText(this,"Permission Granted",Toast.LENGTH_SHORT).show();
i.setClass(getApplicationContext(), Main2Activity.class);
startActivity(i);
} else {
_takePermission();
}
}
}
Above is the complete code, please check and tell me what my mistake is, and what is the correct bridge.
Thanks for watching..
android:requestLegacyExternalStorage="true" will not affect if your app targetSdk > 30 (Android 11 and above).
Must add this to manifest:
Request to permission:
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.MANAGE_EXTERNAL_STORAGE}, 1);
Check whether app can access storage:
if (!Environment.isExternalStorageManager())
Request to access "All files and media" access:
Intent intent = new Intent();
intent.setAction(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
Uri uri = Uri.fromParts("package", this.getPackageName(), null);
intent.setData(uri);
startActivity(intent);
I search on google for onactivityresult() is deprecated. but my problem was not solve . here is the code of fragment
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull #NotNull String[] permissions, #NonNull #NotNull int[] grantResults) {
switch (requestCode){
case CAMERA_REQUEST_CODE:{
if (grantResults.length >0 ){
boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean writeStorageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if (cameraAccepted && writeStorageAccepted){
pickFromCamera();
}
else {
Toast.makeText(getActivity(), "Please enable camera & storage permission first ", Toast.LENGTH_SHORT).show();
}
}
}
private void pickFromCamera() {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE,"Temp Pic");
values.put(MediaStore.Images.Media.DESCRIPTION,"Temp Description");
// put image uri
image_uri = requireActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
// intent tom start camera
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
startActivityForResult(cameraIntent, IMAGE_PICK_CAMERA_CODE);
}
private void pickFromGallery() {
// pick from gallery
Intent galleryIntent = new Intent(Intent .ACTION_PICK);
galleryIntent.setType("Images/*");
startActivityForResult(galleryIntent, IMAGE_PICK_GALLERY_CODE);
}
}
Kotlin - Below code instead of startActivityForResult deprecation
this method gives the result itself and returns a value.
val resultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
when (result.resultCode) {
Activity.RESULT_OK -> {
// logic
}
else -> {
// logic
}
}
}
I am trying to get access to the camera from within the app. I have the following code and all is working except it's not giving the user the option to grant permissions. Not quite sure what has gone wrong with it.
public void takePicture (View view) {
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
{
//requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_CAMERA_PERMISSION_CODE);
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.CAMERA}, MY_CAMERA_PERMISSION_CODE);
}
else
{
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
}
public void saveButton (View view) {
Log.i("info", "stuff");
}
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults)
{
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MY_CAMERA_PERMISSION_CODE)
{
if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show();
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
else
{
Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show();
}
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}
Once the button is clicked the toast comes up to show that permissions have not been granted but no option to grant them in the first place?
Please make sure you have added camera permission in Androidmanifeast.xml
and minor change in your code replace below line
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
with
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
I'm trying to get access to the system settings, but it seems my method that requests the permission always returns false. My knowledge is limited so I don't really know where to start to fix it
private void getPermissions(){
boolean value;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
value = Settings.System.canWrite(getApplicationContext());
if(value) {
success = true;
}else{
Intent intent = new
Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
intent.setData(Uri.parse("package:" +
getApplicationContext().getPackageName()));
startActivity(intent);
}
}
}
the getPermission() is called upon the creation of the app.
Try this
String[] permissionsRequired = new String{Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.RECORD_AUDIO};
//on button click
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivityForResult(intent, REQUEST_PERMISSION_SETTING);
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getApplicationContext(), "Permission Granted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Permission Denied", Toast.LENGTH_SHORT).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if ((ContextCompat.checkSelfPermission(this, permissionsRequired[0])
!= PackageManager.PERMISSION_GRANTED) ||
(ContextCompat.checkSelfPermission(this, permissionsRequired[1])
!= PackageManager.PERMISSION_GRANTED) ||
(ContextCompat.checkSelfPermission(this, permissionsRequired[2])
!= PackageManager.PERMISSION_GRANTED)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermission();
}
}
}
}
break;
}
}
public void requestPermission() {
ActivityCompat.requestPermissions((Activity) this, permissionsRequired, REQUEST_PERMISSION_SETTING);
}
I am trying to attach a pdf file with my Gmail. But the problem is, it always shows a toast message which says "PERMISSION DENIED FOR THE ATTACHMENT". I tried on some different emails like Yahoo, but the file is still not being attached.
This is my Code for the Attachment:
case R.id.emailPdf:
try {
String filename = "SampleFile1.pdf";
File filelocation = new File(Environment.getDataDirectory() + "/data/" + getPackageName() + "/files/", filename);
filelocation.setReadable(true, false);
Uri path = Uri.fromFile(filelocation);
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setType("vnd.android.cursor.dir/email");
String to[] = {""};
emailIntent.putExtra(Intent.EXTRA_EMAIL, to);
emailIntent.putExtra(Intent.EXTRA_STREAM, path);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivityForResult(Intent.createChooser(emailIntent, "Send email..."), 12);
break;
}catch (Exception e){
e.printStackTrace();
}
These are the permissions in the AndroidManifest.xml file
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
I used the debugger, and I observed that the file is being read from the file location but dont know why its not getting attached.
Any help would be appreciated.
Thanks in advance.
Try like below:
Create method to check runtime permission.
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public boolean checkExternalPermission() {
int currentAPIVersion = Build.VERSION.SDK_INT;
if (currentAPIVersion >= android.os.Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(getActivity());
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Permission necessary");
alertBuilder.setMessage("Write external storage permission is necessary to read gallery pictures!!!");
alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions((Activity) getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
} else {
ActivityCompat.requestPermissions((Activity) getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
}
return false;
} else {
return true;
}
} else {
return true;
}
}
Now on attach button click:
boolean result = checkExternalPermission();
if (result) {
activeGallery();
}
Create method to open gallery like below:
/**
* to gallery
*/
private void activeGallery() {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RESULT_LOAD_IMAGE);
}
Now handle permission result like below:
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
activeGallery();
} else {
Toast.makeText(getActivity(), "Permission not granted", Toast.LENGTH_LONG).show();
//code for deny
}
break;
}
}
Now handle activity result like below for your selected attachment:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_LOAD_IMAGE:
if (resultCode == RESULT_OK && null != data) {
try {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver()
.query(selectedImage, filePathColumn, null, null,
null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
// MyImage image = new MyImage();
// image.setTitle("Test");
// image.setDescription(
// "test choose a photo from gallery and add it to " +
// "list view");
// image.setDatetime(System.currentTimeMillis());
File file = new File(picturePath);
Uri imageUri = Uri.fromFile(file);
Product product = new Product(catID, "custom", "#1111", imageUri.toString(), "15000", "30%", 0);
dBhelper.createPRODUCT(product);
imageList.add(0, product);
// imageList.add(0, imageUri);
setimage(imageUri.toString(), imgview, true);
// imageList.add(0, picturePath);
adapter.notifyDataSetChanged();
} catch (Exception e) {
e.printStackTrace();
}
// images.add(image);
}
break;
}
}
And finally declare below global variable:
private static final int RESULT_LOAD_IMAGE = 1;
public static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 3;
Make sure below permission you have define in manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />