I'm developing app in which we pick image from Camera OR Gallery using intents and set to ImageView. The camera button feature is working perfect.
The problem is when first time I click Gallery button it asks permission when I allow the permission it the app crashes but gallery opens. Then second time when I open app and click the Gallery button again then works fine.
Here is my code:
The WRITE_EXTERNAL_STORAGE permission is used for both taking image from camera intent and also taking image from Galley intent may be that is causing the problem. But I'm new in android development so don't know how to solve it.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.blogspot.atifsoftwares.myapplication">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.CAMERA"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<ImageView
android:id="#+id/imageIv"
android:layout_width="match_parent"
android:layout_height="300dp"
android:scaleType="fitCenter"
android:src="#drawable/ic_launcher_background" />
<Button
android:id="#+id/galleryBtn"
android:text="Gallery"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/cameraBtn"
android:text="Camera"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
MainActivity.java
package com.blogspot.atifsoftwares.myapplication;
import android.Manifest;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private static final int IMAGE_PICK_GALLERY_CODE = 1000;
private static final int IMAGE_PICK_CAMERA_CODE = 1001;
private static final int PERMISSION_WRITE_STORAGE_CODE = 1002;
private static final int PERMISSION_CAMERA_CODE = 1003;
Uri image_uri;
ImageView mImageView;
Button mGalleryBtn, mCameraBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImageView = findViewById(R.id.imageIv);
mGalleryBtn = findViewById(R.id.galleryBtn);
mCameraBtn = findViewById(R.id.cameraBtn);
//Gallery button click listener to pick image from gallery
mGalleryBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
//System OS is Marshmallow or above
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_DENIED){
//permission not granted, request it.
String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
//show popup for runtime permission
requestPermissions(permissions, PERMISSION_WRITE_STORAGE_CODE);
}
else {
//permission already granted
pickGallery();
}
}
else {
//System OS is less then Marshmallow
pickGallery();
}
}
});
//Camera button click listener to pick image from gallery
mCameraBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
//System OS is Marshmallow or above
if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED ||
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED){
//permission not granted, request it.
String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
//show popup for runtime permission
requestPermissions(permissions, PERMISSION_CAMERA_CODE);
}
else {
//permission already granted
pickCamera();
}
}
else {
//System OS is less than Marshmallow
pickCamera();
}
}
});
}
public void pickCamera(){
//take image from default camera
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "New Picture");
values.put(MediaStore.Images.Media.DESCRIPTION, "From Camera");
image_uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
startActivityForResult(cameraIntent, IMAGE_PICK_CAMERA_CODE);
}
public void pickGallery(){
//pick image from gallery
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, IMAGE_PICK_GALLERY_CODE);
}
//handle result of runtime permission
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case PERMISSION_WRITE_STORAGE_CODE:{
if (grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
//permission was granted
Toast.makeText(this, "Gallery Granted", Toast.LENGTH_SHORT).show();
pickGallery();
}
else {
//permission was denied
Toast.makeText(this, "Permission denied...!", Toast.LENGTH_SHORT).show();
}
}
case PERMISSION_CAMERA_CODE:{
if (grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
//permission was granted
Toast.makeText(this, "Camera Granted", Toast.LENGTH_SHORT).show();
pickCamera();
}
else {
//permission was denied
Toast.makeText(this, "Permission denied...!", Toast.LENGTH_SHORT).show();
}
}
}
}
//handle result of picked image
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK){
if (requestCode == IMAGE_PICK_GALLERY_CODE){
//set image to image view
mImageView.setImageURI(data.getData());
}
if (requestCode == IMAGE_PICK_CAMERA_CODE){
//set image to image view
mImageView.setImageURI(image_uri);
}
}
}
}
Here is logcat report:
FATAL EXCEPTION: main
Process: com.blogspot.atifsoftwares.myapplication, PID: 24672
java.lang.RuntimeException: Failure delivering result ResultInfo{who=#android:requestPermissions:, request=1002, result=-1, data=Intent { act=android.content.pm.action.REQUEST_PERMISSIONS (has extras) }} to activity {com.blogspot.atifsoftwares.myapplication/com.blogspot.atifsoftwares.myapplication.MainActivity}: java.lang.SecurityException: Permission Denial: starting Intent { act=android.media.action.IMAGE_CAPTURE flg=0x3 cmp=com.oppo.camera/.Camera clip={text/uri-list U:content://media/external/images/media/58337} (has extras) } from ProcessRecord{f4a4aee 24672:com.blogspot.atifsoftwares.myapplication/u0a427} (pid=24672, uid=10427) with revoked permission android.permission.CAMERA
at android.app.ActivityThread.deliverResults(ActivityThread.java:4339)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4382)
at android.app.ActivityThread.-wrap20(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1679)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:186)
at android.app.ActivityThread.main(ActivityThread.java:6509)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:914)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:804)
Caused by: java.lang.SecurityException: Permission Denial: starting Intent { act=android.media.action.IMAGE_CAPTURE flg=0x3 cmp=com.oppo.camera/.Camera clip={text/uri-list U:content://media/external/images/media/58337} (has extras) } from ProcessRecord{f4a4aee 24672:com.blogspot.atifsoftwares.myapplication/u0a427} (pid=24672, uid=10427) with revoked permission android.permission.CAMERA
at android.os.Parcel.readException(Parcel.java:1702)
at android.os.Parcel.readException(Parcel.java:1655)
at android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:3229)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1520)
at android.app.Activity.startActivityForResult(Activity.java:4434)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:767)
at android.app.Activity.startActivityForResult(Activity.java:4369)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:754)
at com.blogspot.atifsoftwares.myapplication.MainActivity.pickCamera(MainActivity.java:98)
at com.blogspot.atifsoftwares.myapplication.MainActivity.onRequestPermissionsResult(MainActivity.java:128)
at android.app.Activity.dispatchRequestPermissionsResult(Activity.java:7404)
at android.app.Activity.dispatchActivityResult(Activity.java:7256)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4335)
Your app is crashed when we click on camera button and it asks for camera permission and storage permissions. And we allow camera permission but deny the storage permission. The reason for crash is this: We allowed camera permission to capture image but we also have to give permission to store that image as well. Otherwise it crashes..
I tried to rewrite code to take permissions effectively. Try this code and tell me if it works.
MainActivity.java
public class MainActivity extends AppCompatActivity {
public static final int CAMERA_REQUEST_CODE = 200;
public static final int STORAGE_REQUEST_CODE = 400;
private static final int IMAGE_PICK_GALLERY_CODE = 1000;
private static final int IMAGE_PICK_CAMERA_CODE = 1001;
Uri image_uri;
ImageView mImageView;
Button mGalleryBtn, mCameraBtn;
String cameraPermission[];
String storagePermission[];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImageView = findViewById(R.id.imageIv);
mGalleryBtn = findViewById(R.id.galleryBtn);
mCameraBtn = findViewById(R.id.cameraBtn);
cameraPermission = new String [] {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
storagePermission = new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE};
//Gallery button click listener to pick image from gallery
mGalleryBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!checkStoragePermission()) {
requestStoragePermission();
} else {
pickGallery();
}
}
});
//Camera button click listener to pick image from gallery
mCameraBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!checkCameraPermission()) {
requestCameraPermission();
} else {
pickCamera();
}
}
});
}
public void pickCamera() {
//take image from default camera
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "New Picture");
values.put(MediaStore.Images.Media.DESCRIPTION, "From Camera");
image_uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
startActivityForResult(cameraIntent, IMAGE_PICK_CAMERA_CODE);
}
public void pickGallery() {
//pick image from gallery
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, IMAGE_PICK_GALLERY_CODE);
}
public boolean checkStoragePermission() {
boolean result = ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED);
return result;
}
public void requestStoragePermission() {
ActivityCompat.requestPermissions(this, storagePermission, STORAGE_REQUEST_CODE);
}
public boolean checkCameraPermission() {
boolean result = ContextCompat.checkSelfPermission(this,
Manifest.permission.CAMERA) == (PackageManager.PERMISSION_GRANTED);
boolean result1 = ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED);
return result && result1;
}
public void requestCameraPermission() {
ActivityCompat.requestPermissions(this,cameraPermission, CAMERA_REQUEST_CODE);
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, 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) {
Toast.makeText(this, "Thank you", Toast.LENGTH_SHORT).show();
pickCamera();
}
else {
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)) {
showMessageOkCancel("You need to allow storage permissions.",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(cameraPermission, CAMERA_REQUEST_CODE);
}
}
});
return;
}
}
}
}
break;
case STORAGE_REQUEST_CODE:
if (grantResults.length > 0) {
boolean writeStorageAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if (writeStorageAccepted) {
Toast.makeText(this, "Thank you", Toast.LENGTH_SHORT).show();
pickGallery();
}
else {
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
showMessageOkCancel("You need to allow storage permissions.",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(storagePermission, STORAGE_REQUEST_CODE);
}
}
});
return;
}
}
}
}
break;
}
}
private void showMessageOkCancel(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(this).setMessage(message).setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", null).create().show();
}
//handle result of picked image
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == IMAGE_PICK_GALLERY_CODE) {
//set image to image view
mImageView.setImageURI(data.getData());
}
if (requestCode == IMAGE_PICK_CAMERA_CODE) {
//set image to image view
mImageView.setImageURI(image_uri);
}
}
}
}
Hopefully app should run this time!
Now whenever you click gallery button, app asks for Storage Permission and when click camera button, app will ask for both camera and storage permissions.
Related
this is my .java class
package com.example.gas4u;
private void showImagePickDialog() {
//options to display in dialog
String[] options = {"Camera","Gallery"};
//dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick Image")
.setItems(options, new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which){
//handle items clicks
if (which == 0){
//camera clicked
if (checkCameraPermission()){
//permission granted
pickFromCamera();
}
else{
//permission not granted, request
requestCameraPermission();
}
}
else{
//gallery clicked
if (checkStoragePermission()){
//permission granted
pickFromGallery();
}
else{
//permission not granted
requestStoragePermission();
}
}
}
}).show();
}
// You can do the assignment inside onAttach or onCreate, i.e, before the activity is displayed
ActivityResultLauncher<Intent> someActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result ) {
if (result.getResultCode() == Activity.RESULT_OK) {
// There are no request codes
Intent data = result.getData();
if (result.getResultCode() == IMAGE_PICK_GALLERY_CODE){
//image picked from gallery
//save picked image uri
image_uri = data.getData();
//set image
productIconIv.setImageURI(image_uri);
}
else if (result.getResultCode() == IMAGE_PICK_CAMERA_CODE){
//image picked from camera
productIconIv.setImageURI(image_uri);
}
}
}
});
private void pickFromGallery(){
//intent to pick image from gallery
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
someActivityResultLauncher.launch(intent);
//(intent, IMAGE_PICK_GALLERY_CODE);
}
private void pickFromCamera(){
//intent to pick image from camera
//using media store to pick high/original quality image
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.Images.Media.TITLE, "Temp_Image_Title");
contentValues.put(MediaStore.Images.Media.DESCRIPTION, "Temp_Image_Description");
image_uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
Intent intent= new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
someActivityResultLauncher.launch(intent);
//startActivityForResult(intent, IMAGE_PICK_CAMERA_CODE);
}
private boolean checkStoragePermission(){
boolean result = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) ==
(PackageManager.PERMISSION_GRANTED);
return result; //returns true or false
}
private void requestStoragePermission(){
ActivityCompat.requestPermissions(this, storagePermission, STORAGE_REQUEST_CODE);
}
private boolean checkCameraPermission(){
boolean result = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) ==
(PackageManager.PERMISSION_GRANTED);
boolean result1 = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) ==
(PackageManager.PERMISSION_GRANTED);
return result && result1;
}
private void requestCameraPermission(){
ActivityCompat.requestPermissions(this, cameraPermissions, CAMERA_REQUEST_CODE);
}
//handle permission results
public void onRequestPermissionResult(int requestCode, #NonNull String[] permission, #NonNull int[] grantResults){
switch (requestCode){
case CAMERA_REQUEST_CODE:{
if (grantResults.length>0){
boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean storageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if (cameraAccepted && storageAccepted){
//both permission granted
pickFromCamera();
}
else{
//both or one permissions denied
Toast.makeText(this, "Camera & Storage permissions are required...", Toast.LENGTH_SHORT).show();
}
}
}
case STORAGE_REQUEST_CODE:{
if (grantResults.length>0){
boolean storageAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if (storageAccepted){
//permission granted
pickFromGallery();
}else{
//permission denied
Toast.makeText(this, "Storage permissions is required...", Toast.LENGTH_SHORT).show();
}
}
}
}
super.onRequestPermissionsResult(requestCode, permission, grantResults);
I do not know how to upload an image into Android Studio, I have looked into many videos in Youtube but I am not sure if I implement it correctly, since StartActivityForResult has been fabricated I try to follow the video in the Youtube how to implement it the new way, however it is not working. Can anyone help me with this?
I want to open camera when clicking an item on my dialog box, but I get an error like below. I've been adding a camera permission to manifest.xml.
java.lang.SecurityException: Permission Denial: starting Intent { act=android.media.action.IMAGE_CAPTURE cmp=com.sonyericsson.android.camera/.MultiWindowActivity } from ProcessRecord{b42fcde 29884:ukmutilizer.project.com.ukm_utilizer/u0a273} (pid=29884, uid=10273) with revoked permission android.permission.CAMERA
this is my function
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.personal_data_step, container, false);
ButterKnife.bind(this, view);
imageEktp.setClickable(true);
imageEktp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Log.d("test : ", "testing");
CharSequence menu[] = new CharSequence[]{"Take From Galery", "Open Camera"};
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Pick a Picture");
builder.setItems(menu, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(i == 0){
Toast.makeText(getActivity(), "galery", Toast.LENGTH_SHORT).show();
}else{
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivity(intent);
}
}
});
builder.show();
}
});
return view;
}
Ensure you request Runtime Camera Permission from the user.
private static final int CAMERA_REQUEST_CODE = 100;
Request permission if not granted.
if (checkSelfPermission(Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CAMERA},
CAMERA_REQUEST_CODE);
}
Do stuff inside onRequestPermissionsResult.
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == CAMERA_REQUEST_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Camera permission granted.", Toast.LENGTH_LONG).show();
// Do stuff here for Action Image Capture.
} else {
Toast.makeText(this, "Camera permission denied.", Toast.LENGTH_LONG).show();
}
}
}
Also this should be declared inside Manifest as well.
You have to get runtime permission then only access your camera
like
in manifest
<uses-permission android:name="android.permission.CAMERA" />
in Java
private static final int MY_CAMERA_REQUEST_CODE = 100;
private void processPickImage() {
if(hasCameraPermission()) {
pickImage();
}
else
{
requestCameraPermission();
}
}
private boolean hasCameraPermission() {
return ContextCompat.checkSelfPermission(context,
Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED;
}
#TargetApi(Build.VERSION_CODES.M)
private void requestCameraPermission() {
requestPermissions(new String[]{Manifest.permission.CAMERA},
MY_CAMERA_REQUEST_CODE );
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
switch (requestCode) {
case MY_CAMERA_REQUEST_CODE :
processPickImage();
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
The user has to confirm the permission request.
Try
public class ActivityMain extends AppCompatActivity
{
public static final int MY_PERMISSIONS_REQUEST = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
if (ContextCompat.checkSelfPermission(ActivityMain.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
{ ActivityCompat.requestPermissions(ActivityMain.this, new String[]{Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUEST);
}
[...]
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults)
{ switch (requestCode)
{ case MY_PERMISSIONS_REQUEST:
[...]
}
}
}
when you run your app in 6.0 above like marshmallow device then need permission other wise no need to permission.
that time your code work..
if run marshmallow device that time need permission then make below code ..
private void alertDialog(){
CharSequence menu[] = new CharSequence[]{"Take From Galery", "Open Camera"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick a Picture");
builder.setItems(menu, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(i == 0){
Toast.makeText(getApplicationContext(), "galery", Toast.LENGTH_SHORT).show();
}else{
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivity(intent);
}
}
});
builder.show();
}
then above method put in permission code like below ..
if (ContextCompat.checkSelfPermission(webView.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(webView.this, Manifest.permission.CAMERA)) {
alertDialog();
}
else{
ActivityCompat.requestPermissions(webView.this, new String[] { Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0);
}
}
add two permission into manifest file ..
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
your error main problem is permission if you add this below line is work.
if (ContextCompat.checkSelfPermission(webView.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(webView.this, Manifest.permission.CAMERA)) {
alertDialog();
}
else{
ActivityCompat.requestPermissions(webView.this, new String[] { Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0);
}
}
I have tried everything I could find by researching. Nothing is working. I have an Activity with a FragmentDialog. In this dialog, I have an image view with a button. When this button is pressed, an alert pops up to take pic, choose pic from gallery or cancel. Both the cancel and the gallery buttons work great, but when I try to take a photo, I get the error message in the title:
FATAL EXCEPTION: java.lang.SecurityException: Permission Denial: starting Intent { act=android.media.action.IMAGE_CAPTURE cmp=com.lge.camera/.app.CameraActivity } from ProcessRecord{c6d8bdf 7649:com.devhopes.ryde/u0a152} (pid=7649, uid=10152) with revoked permission android.permission.CAMERA
Below is my DialogFragment and Manifest Code:
UsernameDialogFragment
public static class UsernameDialogFragment extends DialogFragment {
Context applicationContext = bDriverRegistrationActivity.getContextOfApplication();
private ImageView profilePic;
private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
private Button btnSelect;
private String userChosenTask;
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if(userChosenTask.equals("Take Photo"))
cameraIntent();
else if(userChosenTask.equals("Choose from Library"))
galleryIntent();
} else {
//code for deny
}
break;
}
}
private void galleryIntent() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
startActivityForResult(Intent.createChooser(intent, "Select File"),SELECT_FILE);
}
private void cameraIntent() {
Intent intent = new Intent(ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
profilePic.setImageBitmap(thumbnail);
}
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Bitmap bm=null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(contextOfApplication
.getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
profilePic.setImageBitmap(bm);
}
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result=Utility.checkPermission(getActivity());
if (items[item].equals("Take Photo")) {
userChosenTask ="Take Photo";
if(result) {
cameraIntent();
}
} else if (items[item].equals("Choose from Library")) {
userChosenTask ="Choose from Library";
if(result) {
galleryIntent();
}
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
super.onCreateDialog(savedInstanceState);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.username_dialog, null);
// Select button
btnSelect = (dialogView).findViewById(R.id.btnSelectPhoto);
btnSelect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
// profile pic
profilePic = dialogView.findViewById(R.id.profile_pic);
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(dialogView);
// ... Add action buttons ...
builder.setPositiveButton(R.string.action_register, new DialogInterface.OnClickListener() {
#Override
public final void onClick(final DialogInterface dialog, int id) {
// save the username to Firebase and sign in user ...
// ... casting dialog interface to an alert dialog and casting
// the result of the findView to an EditText
EditText usernameField = (EditText)((AlertDialog) dialog).findViewById(username);
String username = usernameField.getText().toString();
// year
EditText yearField = (EditText)((AlertDialog) dialog).findViewById(R.id.year);
String year = yearField.getText().toString();
// color, make and model
EditText cmmField = (EditText)((AlertDialog) dialog).findViewById(R.id.cmm);
String cmm = cmmField.getText().toString();
// cell
EditText cellField = (EditText)((AlertDialog) dialog).findViewById(R.id.cell);
String cell = cellField.getText().toString();
// license plate no.
EditText plateField = (EditText)((AlertDialog) dialog).findViewById(R.id.licenseNo);
String licenseNo = plateField.getText().toString();
// profic pic
ImageView profil_pic = (ImageView)((AlertDialog) dialog).findViewById(R.id.profile_pic);
// TODO: set up profile pic to save to firebase
// ... get user's unique id
String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
User aUser = new User(username, year, cmm, cell, licenseNo);
/* https://android-chat-af94c.firebaseio.com/android-chat-af94c/
users/pRsxsToJZPTzCdtft69f1grIJC13/profile/username
getInstance -> grabbing the url:
https://android-chat-af94c.firebaseio.com/android-chat-af94c/
*/
// above is the same as below ...
FirebaseDatabase.getInstance().getReference("drivers").child(userId).setValue(aUser);
Intent intent = new Intent(getActivity().getBaseContext(), PoliciesActivity.class);
startActivity(intent);
}
});
return builder.create();
}
} // UsernameDialogFragment
AndroidManifest permissions
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA"
android:requiredFeature="true"/>
<uses-permission android:name="android.permission.STORAGE"/>
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
In the Android Monitor, it seems to point at 3 lines in particular:
startActivityForResult(intent, REQUEST_CAMERA);
public static class UsernameDialogFragment extends DialogFragment {
cameraIntent();
If you are targeting API Level 23 or more, then you should force get permissions like below(contains several permissions, you can add or remove based on your requirement). Put this in a separate class:
public static List<String> checkAndRequestPermissions(Context context) {
int camera = ContextCompat.checkSelfPermission(context, android.Manifest.permission.CAMERA);
int readStorage = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE);
int writeStorage = ContextCompat.checkSelfPermission(context, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
int fineLoc = ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION);
int coarseLoc = ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_COARSE_LOCATION);
List<String> listPermissionsNeeded = new ArrayList<>();
if (camera != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(android.Manifest.permission.CAMERA);
}
if (readStorage != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(android.Manifest.permission.READ_EXTERNAL_STORAGE);
}
if (writeStorage != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
if (fineLoc != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(android.Manifest.permission.ACCESS_FINE_LOCATION);
}
if (coarseLoc != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(android.Manifest.permission.ACCESS_COARSE_LOCATION);
}
return listPermissionsNeeded;
}
And in your activity:
public static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 1; // Declare this integer globally
Add this method(to retrieve permissions):
private boolean permissions(List<String> listPermissionsNeeded) {
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray
(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
return false;
}
return true;
}
And force get permissions like this:
// In my case I've put the 'checkAndRequestPermissions' method in a separate class named 'PermissionUtils'
List<String> permissionList = PermissionUtils.checkAndRequestPermissions(this);
if (permissions(permissionList)) {
dispatchTakePictureIntent(); // call your camera instead of this method
}
If you are testing your app with Android 6.x or 7.x version you need to grant some permission (Location,camera etc..) at run time.You can find how to achieve this in here.
https://developer.android.com/training/permissions/requesting.html
Request the permissions you need at runtime. Code is from here so check it out
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Manifest.permission.READ_CONTACTS)) {
// 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 {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.READ_CONTACTS},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
I am making an application to capture image once and then save it in SD card and display it on the application's MainActivity's ImageView(image_view)(which is handled in onRequestPermissionsResult() method). The application also helps to send email the picture clicked by user. Now for this I have requested 2 permssions:
1.) Camera Request
2.) External Storage Request
When the app launches the Camera Request dialog box appears but the External Storage Request Dialog box is not appearing and the app crashes displaying the toast as External write permissions has not been granted. Cannot Save File.
I have mentioned the requests in Manifest also
<uses-permission android:name="android.permissions.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
Code for requesting permissions
public void requestPermissions() {
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
} else {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(this,
"External storage permission required to save images",
Toast.LENGTH_SHORT).show();
}
ActivityCompat.requestPermissions(this,new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_WRITE_EXTERNAL_STORAGE);
}
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
launchCamera();
} else {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,android.Manifest.permission.CAMERA)) {
Toast.makeText(this,
"External storage permission required to save images",
Toast.LENGTH_SHORT).show();
}
ActivityCompat.requestPermissions(this,new String[]{android.Manifest.permission.CAMERA},
REQUEST_CAMERA);
}
}
Here is the Full Code
public class MainActivity extends AppCompatActivity {
Button clickPhotoButton;
private static final String FILE_NAME="image01.jpg";
private static final int CAMERA_PIC_REQUEST = 100;
private static final int REQUEST_WRITE_EXTERNAL_STORAGE = 1;
private static final int REQUEST_CAMERA = 2;
File pictureDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Prakhar");
Uri fileUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
clickPhotoButton = (Button) findViewById(R.id.click_photo_button);
makeFolder();
}
public void makeFolder(){
if(!pictureDir.exists()) {
pictureDir.mkdirs();
}
Log.e("Prakhar", pictureDir.getAbsolutePath());
}
public void requestPermissions() {
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
} else {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(this,
"External storage permission required to save images",
Toast.LENGTH_SHORT).show();
}
ActivityCompat.requestPermissions(this,new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_WRITE_EXTERNAL_STORAGE);
}
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
launchCamera();
} else {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,android.Manifest.permission.CAMERA)) {
Toast.makeText(this,
"External storage permission required to save images",
Toast.LENGTH_SHORT).show();
}
ActivityCompat.requestPermissions(this,new String[]{android.Manifest.permission.CAMERA},
REQUEST_CAMERA);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if(requestCode == REQUEST_WRITE_EXTERNAL_STORAGE ) {
if(grantResults[0] == PackageManager.PERMISSION_GRANTED) {
launchCamera();
} else {
Toast.makeText(this,
"External write permission has not been granted, cannot saved images",
Toast.LENGTH_SHORT).show();
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
if(requestCode == REQUEST_CAMERA) {
if(grantResults[0] == PackageManager.PERMISSION_GRANTED) {
launchCamera();
} else {
Toast.makeText(this,
"External write permission has not been granted, cannot saved images",
Toast.LENGTH_SHORT).show();
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
public void onPhotoClicked(View view) {
requestPermissions();
}
public void launchCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File image = new File(pictureDir, FILE_NAME);
fileUri = Uri.fromFile(image);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == CAMERA_PIC_REQUEST && resultCode == RESULT_OK) {
ImageView imageView = (ImageView) findViewById(R.id.image_view);
File image = new File(pictureDir, FILE_NAME);
fileUri = Uri.fromFile(image);
imageView.setImageURI(fileUri);
}
}
}
Found it. It was really a waste of time. In the manifest file I have written
android.permissions.WRITE_EXTERNAL_STORAGE
however it should have been
android.permission.WRITE_EXTERNAL_STORAGE
Try like this
public void requestPermissions() {
boolean hasStoragePermission = ContextCompat.checkSelfPermission(this,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
boolean hasCameraPermission = ContextCompat.checkSelfPermission(this,
android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED;
ArrayList<String> permissonList = new ArrayList();
if (!hasCameraPermission) {
permissonList.add(android.Manifest.permission.CAMERA)
}
if (!hasStoragePermission) {
permissonList.add(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
}
if (permissonList.size() > 0) {
String [] permissionArray = permissonList.toArray(new String[]{});
ActivityCompat.requestPermissions(this,permissionArray,
REQUEST_PERMISSION);
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
if (requestCode == REQUEST_PERMISSION) {
boolean allPermissionGranted = true;
for (int i =0; i < grantResults.length; i++) {
boolean permissionGranted = grantResults[i] == PackageManager.PERMISSION_GRANTED;
if (!permisssionGranted) {
allPermissionGranted = false;
break;
}
}
if (allPermissionGranted) {
launchCamera();
}
}
}
I'm trying to select the image from gallery , but my application is getting exception of 'Something went wrong' message . I thought i set up the android WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE permission correctly, but i keep getting errors What should i do to have it working?
Here is my Log cat error
06-07 12:07:27.567 1692-1711/? E/DatabaseUtils﹕ Writing exception to parcel
java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media/359 from pid=2818, uid=10057 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
at android.content.ContentProvider.enforceReadPermissionInner(ContentProvider.java:605)
at android.content.ContentProvider$Transport.enforceReadPermission(ContentProvider.java:480)
at android.content.ContentProvider$Transport.query(ContentProvider.java:211)
at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:112)
at android.os.Binder.execTransact(Binder.java:453)
Here is my Activity code
public class MainActivity extends Activity {
private static int RESULT_LOAD_IMG = 1;
String imgDecodableString;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void loadImagefromGallery(View view) {
// Create intent to Open Image applications like Gallery, Google Photos
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
// When an Image is picked
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&& null != data) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
ImageView imgView = (ImageView) findViewById(R.id.imgView);
// Set the Image in ImageView after decoding the String
imgView.setImageBitmap(BitmapFactory
.decodeFile(imgDecodableString));
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
}
Here is my Menifest.xml file code
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tazeen.image_fromgallery" >
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
For checking manual permissions for API level 23 and above i use this code.
public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 123;
public boolean checkPermissionREAD_EXTERNAL_STORAGE(
final Context context) {
int currentAPIVersion = Build.VERSION.SDK_INT;
if (currentAPIVersion >= android.os.Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(context,
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(
(Activity) context,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
showDialog("External storage", context,
Manifest.permission.READ_EXTERNAL_STORAGE);
} else {
ActivityCompat
.requestPermissions(
(Activity) context,
new String[] { Manifest.permission.READ_EXTERNAL_STORAGE },
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
return false;
} else {
return true;
}
} else {
return true;
}
}
showDialog()
public void showDialog(final String msg, final Context context,
final String permission) {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Permission necessary");
alertBuilder.setMessage(msg + " permission is necessary");
alertBuilder.setPositiveButton(android.R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions((Activity) context,
new String[] { permission },
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
}
in your activity check like this.
if (checkPermissionREAD_EXTERNAL_STORAGE(this)) {
// do your stuff..
}
And don't forget to add onRequestPermissionsResult.
#Override
public void onRequestPermissionsResult(int requestCode,
String[] permissions, int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// do your stuff
} else {
Toast.makeText(Login.this, "GET_ACCOUNTS Denied",
Toast.LENGTH_SHORT).show();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions,
grantResults);
}
}
Happy Coding..
You have two solutions for your problem. The quick one is to lower targetApi to 22 (build.gradle file). Second is to use the new runtimePermission model: Since your target api is 23 you should add the permissions on runtime too.
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.READ_EXTERNAL_STORAGE) {
// Should we show an explanation?
if (shouldShowRequestPermissionRationale(
Manifest.permission.READ_EXTERNAL_STORAGE)) {
// Explain to the user why we need to read the contacts
}
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
// MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE is an
// app-defined int constant
return;
}
Sniplet found here: https://developer.android.com/training/permissions/requesting.html
You need to set permissions explicitly to all packages match your intent.
you can use this utility to do that :
List<ResolveInfo> resInfoList = getContext().getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
getContext().grantUriPermission(packageName, imageFileUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
There is an easy way, set an action to your "galleryIntent" so the OS will not panick (I test this on Andorid Emulator API 23 and it works):
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
Also, don't forget to set a type too:
galleryIntent.setType("image/*");
Change:
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
To:Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
=> done !