Android camera intent
private static final int TAKE_PICTURE = 1;
private Uri imageUri;
public void takePhoto(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File photo = new File(Environment.getExternalStorageDirectory(), "Pic.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
startActivityForResult(intent, TAKE_PICTURE);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case TAKE_PICTURE:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ImageView imageView = (ImageView) findViewById(R.id.ImageView);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
try {
bitmap = android.provider.MediaStore.Images.Media
.getBitmap(cr, selectedImage);
imageView.setImageBitmap(bitmap);
Toast.makeText(this, selectedImage.toString(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
.show();
Log.e("Camera", e.toString());
}
}
}
}
Android Camera Intent not working in OnePlus devices
Disclaimer: I am not good at explaining
As @CommonsWare suggested, here is what I did.
I basically avoided the usage of resolveActivity()
and did it in my own style instead of just copy-paste from Official Google Documentation
Here is my final call for camera app:
private fun dispatchTakePictureIntent() {
val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
val photoFile: File? = try {
createImageFile()
} catch (ex: IOException) {
// Error occurred while creating the File
ex.printStackTrace()
null
}
if (photoFile != null){
val photoURI: Uri = FileProvider.getUriForFile(
this,
"com.example.android.fileprovider",
photoFile
)
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE)
}
}
private fun createImageFile(): File {
// Create an image file name
val timeStamp: String = SimpleDateFormat("yy-MM-dd-HH-mm-ss-SS",Locale.getDefault()).format(System.currentTimeMillis())
val storageDir: File? = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
return File.createTempFile(
"FNL_${timeStamp}_",
".jpg",
storageDir /* directory */
).apply {
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = absolutePath
currentPhotoName = name
}
}
At last, thank you very much @CommonsWare
Capture Image from Camera and Display in Activity
Here's an example activity that will launch the camera app and then retrieve the image and display it.
package edu.gvsu.cis.masl.camerademo;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MyCameraActivity extends Activity
{
private static final int CAMERA_REQUEST = 1888;
private ImageView imageView;
private static final int MY_CAMERA_PERMISSION_CODE = 100;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.imageView = (ImageView)this.findViewById(R.id.imageView1);
Button photoButton = (Button) this.findViewById(R.id.button1);
photoButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
{
requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_CAMERA_PERMISSION_CODE);
}
else
{
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
}
});
}
@Override
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();
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK)
{
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}
}
Note that the camera app itself gives you the ability to review/retake the image, and once an image is accepted, the activity displays it.
Here is the layout that the above activity uses. It is simply a LinearLayout containing a Button with id button1 and an ImageView with id imageview1:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/photo"></Button>
<ImageView android:id="@+id/imageView1" android:layout_height="wrap_content" android:src="@drawable/icon" android:layout_width="wrap_content"></ImageView>
</LinearLayout>
And one final detail, be sure to add:
<uses-feature android:name="android.hardware.camera"></uses-feature>
and if camera is optional to your app functionality. make sure to set require to false in the permission. like this
<uses-feature android:name="android.hardware.camera" android:required="false"></uses-feature>
to your manifest.xml.
Why does my app keep crashing when launching the camera intent in a new activity?
you are occuring java.lang.SecurityException: Permission Denial ... with revoked permission android.permission.CAMERA
- your app don't have camera access permission
use runtime permissions for acquire
Picture file captured with camera intent empty for a while in onActivityResult
Do not create that file already. Remove the File.createTempFile()
.
The only thing you need is a file name. A file path. The Camera app will create the file on its own. So change your function to create new file name. E.g. new File(storageDir, imageFileName + ".jpg")
Related Topics
Error "The Connection to Adb Is Down, and a Severe Error Has Occurred."
Include .So Library in APK in Android Studio
How to Create PDFs in an Android App
What's the Best Way to Iterate an Android Cursor
Why Does Android Webview Sporadically Not Sending My Session Cookie
Manifest Merger Failed:Uses-Sdk:Minsdkversion 14
Disabling the Fullscreen Editing View for Soft Keyboard Input in Landscape
Adding Local .Aar Files to Gradle Build Using "Flatdirs" Is Not Working
Notification Icon with the New Firebase Cloud Messaging System
Deleting a Gallery Image After Camera Intent Photo Taken
How to Inflate One View with a Layout
Android- Error:Execution Failed for Task ':App:Transformclasseswithdexforrelease'
Where Does Android Emulator Store SQLite Database
The Setmobiledataenabled Method Is No Longer Callable as of Android L and Later
Using Intent in an Android Application to Show Another Activity