I want to request permission to read external storage on runtime. When I click on a Button the app should ask for permission, but the dialog does not show up when button is clicked. Code (This is from a Fragment):
private Button photo;
//Constants
private static final int GALLERY_INTENT = 2339;
private static final int REQUEST_EXTERNAL_STORAGE = 4435;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_profile, container, false);
photo = (Button) rootView.findViewById(R.id.photoButton);
photo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//start permission check for gallery
//check if permission is granted
if(ActivityCompat.checkSelfPermission(getContext(),
Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED){
//if permission is not granted, ask for permission.
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_EXTERNAL_STORAGE);
}else{
//if permission already granted, start gallery intent.
uploadPhotoToFirebase();
}
}
});
return rootView;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY_INTENT && resultCode == RESULT_OK){
Uri uri = data.getData();
StorageReference storageReference = FirebaseStorage
.getInstance()
.getReference("profile_images/"+FirebaseAuth
.getInstance()
.getCurrentUser()
.getUid()
);
storageReference.putFile(uri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
//File successfully uploaded
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
//File upload not successful
}
});
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case REQUEST_EXTERNAL_STORAGE:
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
//Permission to read external storage GRANTED
uploadPhotoToFirebase();
}else{
//Permission to read external storage DENIED
}
}
}
private void uploadPhotoToFirebase(){
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, GALLERY_INTENT);
}
}
Anyone knows why the dialog requesting permission does not show up here?
For the dialog to appear, you need to:
Have a targetSdkVersion of 23 or higher
Have the permission(s) that you are requesting also in the manifest, with <uses-permission> elements
Be running on Android 6.0 or higher
Related
I want to create android application where should be a way to upload file on firebase. But Even after giving runtime permissions to storage, somehow Video is not being uploaded.
Here is my MainActivity.java file code
public class MainActivity extends AppCompatActivity implements
ActivityCompat.OnRequestPermissionsResultCallback{
private static final int PERMISSION_REQUEST_STORAGE = 0;
private final String[] REQUIRED_PERMISSIONS = new String[]{
"android.permission.WRITE_EXTERNAL_STORAGE",
"android.permission.READ_EXTERNAL_STORAGE",
"android.permission.INTERNET"
};
FireBaseHandler fb;
private View mLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fb = new FireBaseHandler();
mLayout = findViewById(R.id.main_layout);
// Check if the permission has been granted
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
// Permission is already available, start camera preview
Snackbar.make(mLayout,
"Permission_Available",
Snackbar.LENGTH_SHORT).show();
fb.upload();
} else {
// Permission is missing and must be requested.
requestPermission();
}
/*
if(allPermissionsGranted()){
fb.Upload(); //start upload if permission has been granted by user
} else{
ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS);
}
*/
}
/*
private boolean allPermissionsGranted(){
for(String permission : REQUIRED_PERMISSIONS){
if(ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED){
return false;
}
}
return true;
}
*/
private void requestPermission() {
// Permission has not been granted and must be requested.
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
// Provide an additional rationale to the user if the permission was not granted
// and the user would benefit from additional context for the use of the permission.
// Display a SnackBar with cda button to request the missing permission.
Snackbar.make(mLayout, "camera_access_required",
Snackbar.LENGTH_INDEFINITE).setAction("OK", new View.OnClickListener() {
#Override
public void onClick(View view) {
// Request the permission
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
PERMISSION_REQUEST_STORAGE);
}
}).show();
} else {
Snackbar.make(mLayout, "Storage_unavailable", Snackbar.LENGTH_SHORT).show();
// Request the permission. The result will be received in onRequestPermissionResult().
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_STORAGE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
// BEGIN_INCLUDE(onRequestPermissionsResult)
if (requestCode == PERMISSION_REQUEST_STORAGE) {
// Request for camera permission.
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission has been granted. Start camera preview Activity.
Snackbar.make(mLayout, "camera_permission_granted",
Snackbar.LENGTH_SHORT)
.show();
fb.upload();
} else {
// Permission request was denied.
Snackbar.make(mLayout, "Storage_permission_denied",
Snackbar.LENGTH_SHORT)
.show();
}
}
// END_INCLUDE(onRequestPermissionsResult)
}
/*
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(requestCode == REQUEST_CODE_PERMISSIONS){
if(allPermissionsGranted()){
fb.Upload();
} else{
Toast.makeText(this, "Permissions not granted by the user.", Toast.LENGTH_SHORT).show();
this.finish();
}
}
}
*/
}
And here is code for uploading file
public class FireBaseHandler {
private static final String TAG = "MyFirebase";
FirebaseStorage storage; // = FirebaseStorage.getInstance();
// Create a storage reference from our app
StorageReference storageRef; // = storage.getReference();
UploadTask uploadTask;
public FireBaseHandler() {
storage = FirebaseStorage.getInstance();
storageRef = storage.getReference();
}
public void upload(){
Uri file = Uri.fromFile(new File(getWhatsAppVideoDirectory()+"Abc.mp4"));
StorageReference vidRef = storageRef.child("videos/"+file.getLastPathSegment());
uploadTask = vidRef.putFile(file);
// Register observers to listen for when the download is done or if it fails
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
Log.i(TAG,"onFailure");
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, etc.
// ...
Log.i(TAG,"onSuccess");
}
});
}
private String getWhatsAppVideoDirectory() {
String folder_path = (Environment.getExternalStorageDirectory().getAbsolutePath() +
"/WhatsApp/Media/WhatsApp Video/Sent/");
//new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/WhatsApp/Media");
return folder_path;
}
}
Error is something like Access denied, Kindly tell me where am I doing it wrong way.
I have ran this code using Lower version of android that is 6.0.1 and it is working fine. I don't know if Google has some changes for newer android versions?
I just found that you are not asking permission properly;
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
PERMISSION_REQUEST_STORAGE);
Here you are just asking for reading permission, Read permission is always true when you declare in manifest, but at runtime you should ask for WRITE_EXTERNAL_STORAGE. So there is no meaning of above code, because it will be always true. You have to ask permission like this:
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
PERMISSION_REQUEST_STORAGE);
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'm writting a code that the user can upload video from his phone.
My only problem is that i dont know how to get/save the file.
With the intent the user access to his libary and choose his video.
But then i dont know how to get what he choose
Here is my code
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
btnVideo.setOnClickListener(this);
btnAudio.setOnClickListener(this);
}
#Override
public void onClick(View view) {
int id = view.getId();
switch (id){
case R.id.btnUploadVideo:
if(!checkStoragePermission())return;
uploadVideo();
break;
case R.id.btnUploadAudio:
break;
}
}
private void uploadVideo() {
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Video"),OPEN_MEDIA_PICKER);
}
private boolean checkStoragePermission(){
int resultCode = ActivityCompat.checkSelfPermission(getContext(),
android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
boolean granted = resultCode == PackageManager.PERMISSION_GRANTED;
if (!granted){
ActivityCompat.requestPermissions(
getActivity(),
new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},
PICK_VIDEO_REQUEST /*Constant Field int*/
);
}
return granted;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PICK_VIDEO_REQUEST && grantResults[0] == PackageManager.PERMISSION_GRANTED){
uploadVideo();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == PICK_VIDEO_REQUEST) {
Uri selectedImageUri = data.getData();
}
}
}
What should i do on the "onActivityResult"? How should i save/get the user choose.
My only problem is that i dont know how to get/save the file.
Your code has nothing to do with a file.
If you want the use to pick a file, use a third-party file-chooser library.
Your code is having the user choose a piece of content, and that content does not have to be a file, let alone a file that you have direct filesystem access to.
You are welcome to use data.getData() to get the Uri to the content, then use ContentResolver and openInputStream() to get an InputStream on that content, if that meets your needs.
I was just trying to write a code to capture an image and save that image in default directory with a name test.jpg. My device do capture the image but it runs the else part of the test case and shows error capturing image.In xml file there is only a button and android:onClick is set to process
public class MainActivity extends Activity {
private File imagefile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void process(View v)
{
Toast.makeText(this,"Inside the process",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
imagefile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"test.jpg");
Uri temp = Uri.fromFile(imagefile);
intent.putExtra(MediaStore.EXTRA_OUTPUT,temp);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY,1);
startActivityForResult(intent,0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==0)
{
switch (resultCode){
case Activity.RESULT_OK:
if(imagefile.exists())
{
Toast.makeText(this,"File was saved at "+imagefile.getAbsolutePath(),Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(this,"Error captureing image",Toast.LENGTH_SHORT).show();
}
break;
case Activity.RESULT_CANCELED:
break;
}
}
}
}
1.Use checkSelfPermission
2.Use requestPermissions
3.Use onRequestPermissionsResult
If permission is granted , you can do something you want ,else you should do requestPermissions in your code .
If you request permissions,you can deal with result in onRequestPermissionsResult method .And if permissions granted , you can do something you want ,else deal with that permission Denied .
Try this .
public static final int MY_PERMISSIONS_REQUEST_CAMERA = 0;
// process in your code
public void process(View view) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CAMERA},
MY_PERMISSIONS_REQUEST_CAMERA);
} else {
// permission_granted
callMethod();
}
}
/**
* do something you want
*/
public void callMethod() {
Toast.makeText(this, "Inside the process", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
imagefile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "test.jpg");
Uri temp = Uri.fromFile(imagefile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, temp);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, 0);
}
/**
* onRequestPermissionsResult
*
* #param requestCode
* #param permissions
* #param grantResults
*/
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == MY_PERMISSIONS_REQUEST_CALL_PHONE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission granted
callMethod();
} else {
// Permission Denied
Toast.makeText(MainActivity.this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
return;
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
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();
}
}
}