How To Use Camera API For Android N And Above Devices In Android

Introduction

In my previous article, we learned how to handle “android.os.FileUriExposedException” if we have an app that shares files with other apps using a URI on API 24+. In this article, we will learn how to use Camera Intent in Android N and above devices.
Creating a New Project with Android Studio
  1. Open Android Studio and select "Create new project".
  2. Name the project as per your wish and select your activity template.
    How To Use Camera API For Android N And Above Devices In Android
  3. Click the finish button to create a new project in Android Studio.

Steps to use Camera API

Full Code
The following code shows how to access an image from Gallery, how to take pictures from the camera, and how to open a file using intent in Android N & above devices.
  1. public class MainActivity extends AppCompatActivity {
  2. ImageView imgPreview;
  3. TextView imgPath;
  4. Button btnPickCamera;
  5. Button btnPickGallery;
  6. Button btnOpenFile;
  7. Uri outputFileUri;
  8. private static final int PICK_FROM_CAMERA = 1;
  9. private static final int PICK_FROM_GALLERY = 2;
  10. @Override
  11. protected void onCreate(Bundle savedInstanceState) {
  12. super.onCreate(savedInstanceState);
  13. setContentView(R.layout.activity_main);
  14. initViews();
  15. initOperations();
  16. }
  17. private void initViews() {
  18. imgPreview = findViewById(R.id.imgPreview);
  19. imgPath = findViewById(R.id.imgPath);
  20. btnPickCamera = findViewById(R.id.btnCapture);
  21. btnPickGallery = findViewById(R.id.btnGallery);
  22. btnOpenFile = findViewById(R.id.btnOpenImg);
  23. }
  24. private void initOperations() {
  25. btnPickGallery.setOnClickListener(new View.OnClickListener() {
  26. @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
  27. @Override
  28. public void onClick(View view) {
  29. // Checking Permission for Android M and above
  30. if (ActivityCompat.checkSelfPermission(MainActivity.this,
  31. Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
  32. ActivityCompat.requestPermissions(MainActivity.this,
  33. new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PICK_FROM_GALLERY);
  34. return;
  35. }
  36. Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
  37. // Start the Intent
  38. startActivityForResult(galleryIntent, PICK_FROM_GALLERY);
  39. }
  40. });
  41. btnPickCamera.setOnClickListener(new View.OnClickListener() {
  42. @Override
  43. public void onClick(View view) {
  44. // Checking Permission for Android M and above
  45. if (ActivityCompat.checkSelfPermission(MainActivity.this,
  46. Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
  47. || ActivityCompat.checkSelfPermission(MainActivity.this,
  48. Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
  49. ActivityCompat.requestPermissions(MainActivity.this,
  50. new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE}, PICK_FROM_CAMERA);
  51. return;
  52. }
  53. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
  54. ContentValues values = new ContentValues(1);
  55. values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpg");
  56. outputFileUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
  57. Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
  58. captureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
  59. captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
  60. startActivityForResult(captureIntent, PICK_FROM_CAMERA);
  61. } else {
  62. Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
  63. File file = new File(Environment.getExternalStorageDirectory(), "MyPhoto.jpg");
  64. outputFileUri = Uri.fromFile(file);
  65. captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
  66. startActivityForResult(captureIntent, PICK_FROM_CAMERA);
  67. }
  68. }
  69. });
  70. btnOpenFile.setOnClickListener(new View.OnClickListener() {
  71. @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
  72. @Override
  73. public void onClick(View v) {
  74. // Checking Permission for Android M and above
  75. if (ActivityCompat.checkSelfPermission(MainActivity.this,
  76. Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
  77. ActivityCompat.requestPermissions(MainActivity.this,
  78. new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PICK_FROM_GALLERY);
  79. return;
  80. }
  81. File file = new File(imgPath.getText().toString());
  82. Intent intent = new Intent(Intent.ACTION_VIEW);
  83. intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
  84. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
  85. Uri apkURI = FileProvider.getUriForFile(getApplicationContext(), getPackageName() + ".provider", file);
  86. intent.setDataAndType(apkURI, "image/jpg");
  87. intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
  88. } else {
  89. intent.setDataAndType(Uri.fromFile(file), "image/jpg");
  90. }
  91. startActivity(intent);
  92. }
  93. });
  94. }
  95. @Override
  96. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  97. super.onActivityResult(requestCode, resultCode, data);
  98. Bitmap bitmap;
  99. switch (requestCode) {
  100. case PICK_FROM_CAMERA:
  101. if (resultCode == Activity.RESULT_OK) {
  102. Uri selectedImage = outputFileUri;
  103. ContentResolver cr = getContentResolver();
  104. getContentResolver().notifyChange(selectedImage, null);
  105. try {
  106. bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr, selectedImage);
  107. int nh = (int) ( bitmap.getHeight() * (512.0 / bitmap.getWidth()) );
  108. bitmap = Bitmap.createScaledBitmap(bitmap, 512, nh, true);
  109. imgPreview.setImageBitmap(bitmap);
  110. imgPath.setText(outputFileUri.getPath());
  111. } catch (Exception e) {
  112. Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
  113. .show();
  114. }
  115. }
  116. break;
  117. case PICK_FROM_GALLERY:
  118. if (resultCode == Activity.RESULT_OK) {
  119. //pick image from gallery
  120. Uri selectedImage = data.getData();
  121. String[] filePathColumn = {MediaStore.Images.Media.DATA};
  122. // Get the cursor
  123. assert selectedImage != null;
  124. Cursor cursor = getContentResolver().query(selectedImage, filePathColumn,
  125. null, null, null);
  126. // Move to first row
  127. assert cursor != null;
  128. cursor.moveToFirst();
  129. int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
  130. String imgDecodableString = cursor.getString(columnIndex);
  131. cursor.close();
  132. bitmap = BitmapFactory.decodeFile(imgDecodableString);
  133. imgPreview.setImageBitmap(bitmap);
  134. imgPath.setText(imgDecodableString);
  135. }
  136. break;
  137. }
  138. }
  139. }
Reference
How to handle “android.os.FileUriExposedException”.
Download
You can download the code from GitHub. If you like this article do like & share the article and star the repo in GitHub.