Call camera to take photos
Keywords:
FileProvider
Android
Call camera to take photos:
@Override
public void onClick(View v) {
File outputImage = new File(getExternalCacheDir(),"output_image.jpg");
try {
if (outputImage.exists()) {
outputImage.delete();
}
outputImage.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
if (Build.VERSION.SDK_INT >= 24){
imageUri = FileProvider.getUriForFile(MainActivity.this,"com.eventstest.fileprovider",outputImage);
}else {
imageUri = Uri.fromFile(outputImage);
}
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
startActivityForResult(intent,TAKE_PHOTO);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case TAKE_PHOTO :
if (resultCode == RESULT_OK) {
try {
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
picture.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
break;
default:
break;
}
}
- Reading and writing SD card requires permission processing at run time. Instead, you can skip this step with the associated directory
- If it is lower than Android 7.0, call Uri's fromFile() to convert the File object to a Uri object. Otherwise, call the getUriForFile() method of FileProvider to convert the File object into a encapsulated Uri object.
- getUriForFile() takes three parameters 1.Context 2. It can be any unique string 3. The File object just created. Because it is considered unsafe for 7.0 to start using local real URIs directly. A FileExposedException exception will be thrown. FileProvider is a special content provider, which protects the data and can selectively share the encapsulated Uri to the outside, thus improving the security.
Posted by okuto1973 on Mon, 30 Mar 2020 22:04:32 -0700