In my app, I want to use Camera option, so i am using below code to capture the videos.
public class CameraDemoActivity extends Activity
{
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200;
private Uri fileUri;
public static final int MEDIA_TYPE_VIDEO = 2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Context context = this;
PackageManager packageManager = context.getPackageManager();
// if device support camera?
if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
//yes
Log.i("camera", "This device has camera!");
Toast.makeText(getBaseContext(), "Camera device", Toast.LENGTH_LONG).show();
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO); // create a file to save the video
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT,2);
intent.putExtra(MediaStore.INTENT_ACTION_VIDEO_CAMERA, true);
intent.putExtra(MediaStore.MEDIA_SCANNER_VOLUME, 100);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); // set the video image quality to high
// start the Video Capture Intent
startActivityForResult(intent, CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);
}else{
//no
Log.i("camera", "This device has no camera!");
Toast.makeText(getBaseContext(), "No Camera device", Toast.LENGTH_LONG).show();
}
}
private static Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type)
{
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "MyCameraApp");
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
System.out.println("MyCameraApp");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if(type == MEDIA_TYPE_VIDEO)
{
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_"+ timeStamp + ".mp4");
}
else
{
return null;
}
return mediaFile;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// Video captured and saved to fileUri specified in the Intent
Toast.makeText(this, "Video saved to:\n" +
data.getData(), Toast.LENGTH_LONG).show();
System.out.println("Video saved to:"+data.getData());
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "video cancel", Toast.LENGTH_LONG).show();
// User cancelled the video capture
} else {
System.out.println("video capyured failed.>.1!!!!");
// Video capture failed, advise user
}
}
}
}
In above code, i am getting video screen in emulator,
but its like recording as squares of boxes, which is black and white boxes...!!!!!!!!!!!
In emulator, i can't get the live videos, it also not enabling web cam also.
Interesting is,
this code has successfully run in another computer,(dell webcam). In that machine its enabling web cam and recording videos very slowly, but this is recognsing and enabling camera in emulator.
Another machine is Compaq, unfortunately it has not working and not recognising web cam.
PLEASE ANY Help to activate this webcam facilities.
Old thread but just adding info for anyone who is working on this problem. All you need to do is start the emulator via command line replace with your avd where you want to use the camera:
emulator -camera-front webcam0 -avd <your_avd_name>
Related
I am creating an app in which I'm using front camera.Please tell me how to open front camera when click on button using following code.My app is crashed when i click on button to open the camera.
public class MakePhotoActivity extends Activity {
// LogCat tag
private static final String TAG = MainActivity.class.getSimpleName();
// Camera activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
private Uri fileUri; // file url to store image/video
private Button btnCapturePicture, btnRecordVideo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_make_photo);
// Changing action bar background color
// These two lines are not needed
// getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor(getResources().getString(R.color.action_bar))));
btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);
btnRecordVideo = (Button) findViewById(R.id.btnRecordVideo);
/**
* Capture image button click event
*/
btnCapturePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// capture picture
captureImage();
}
});
/**
* Record video button click event
*/
btnRecordVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// record video
recordVideo();
}
});
// Checking camera availability
if (!isDeviceSupportCamera()) {
Toast.makeText(getApplicationContext(),
"Sorry! Your device doesn't support camera",
Toast.LENGTH_LONG).show();
// will close the app if the device does't have camera
finish();
}
}
/**
* Checking device has camera hardware or not
* */
private boolean isDeviceSupportCamera() {
if (getApplicationContext().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
/**
* Launching camera app to capture image
*/
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
//intent.putExtra("android.intent.extras.CAMERA_FACING", 1);
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
/**
* Launching camera app to record video
*/
private void recordVideo() {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
// set video quality
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file
// name
// start the video capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
}
/**
* Here we store the file url as it will be null after returning from camera
* app
*/
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on screen orientation
// changes
outState.putParcelable("file_uri", fileUri);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}
/**
* Receiving activity result method will be called after closing the camera
* */
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
// launching upload activity
launchUploadActivity(true);
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
} else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// video successfully recorded
// launching upload activity
launchUploadActivity(false);
} else if (resultCode == RESULT_CANCELED) {
// user cancelled recording
Toast.makeText(getApplicationContext(),
"User cancelled video recording", Toast.LENGTH_SHORT)
.show();
} else {
// failed to record video
Toast.makeText(getApplicationContext(),
"Sorry! Failed to record video", Toast.LENGTH_SHORT)
.show();
}
}
}
private void launchUploadActivity(boolean isImage){
/* Intent i = new Intent(MakePhotoActivity.this, UploadActivity.class);
i.putExtra("filePath", fileUri.getPath());
i.putExtra("isImage", isImage);
startActivity(i);*/
}
/**
* ------------ Helper Methods ----------------------
* */
/**
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
Config.IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(TAG, "Oops! Failed create " + Config.IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
}
when i click on button to open the camera app is crashed. i am get this error
07-12 14:02:50.028 15360-15360/com.camerimageuploadd E/AndroidRuntime: FATAL >EXCEPTION: main
Process: com.camerimageuploadd, PID: 15360
java.lang.NullPointerException: file
at android.net.Uri.fromFile(Uri.java:453)
at
com.camerimageuploadd.MakePhotoActivity.getOutputMediaFileUri(MakePhotoActivity.java:228)
at
com.camerimageuploadd.MakePhotoActivity.captureImage(MakePhotoActivity.java:110)
at
com.camerimageuploadd.MakePhotoActivity.access$000(MakePhotoActivity.java:27)
at
com.camerimageuploadd.MakePhotoActivity$1.onClick(MakePhotoActivity.java:64)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Please help how can i resolved this.
Thanks
its throwing null ponter exception because your code is trying to acces file which is not yet captured by camera
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
and
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
i suggest to use this both lines in onActivityResult
your updated methods is
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
and
private void recordVideo() {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
}
Your OnActivityResult
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
Toast.makeText(getApplicationContext(),""+fileUri,Toast.LENGTH_LONG).show();
// fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
// successfully captured the image
// launching upload activity
launchUploadActivity(true);
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
} else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
Toast.makeText(getApplicationContext(),""+fileUri,Toast.LENGTH_LONG).show();
// video successfully recorded
// launching upload activity
launchUploadActivity(false);
} else if (resultCode == RESULT_CANCELED) {
// user cancelled recording
Toast.makeText(getApplicationContext(),
"User cancelled video recording", Toast.LENGTH_SHORT)
.show();
} else {
// failed to record video
Toast.makeText(getApplicationContext(),
"Sorry! Failed to record video", Toast.LENGTH_SHORT)
.show();
}
}
}
I'm creating a basic app which starts the camera activity and then retrieves the image clicked.
I have necessary permissions in the manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
My problem is the app was working fine in api level 22. I updated my phone to level 23 a few days ago and now the same source code is giving me this error:
E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0/Pictures/SAT Practice App/IMG_20160113_123753.jpg: open failed: EACCES (Permission denied)
There are a lot of similar questions in stackoverflow, but most of them only talk about granting permissions which I already have in my manifest.
I personally checked the folder and found that the file exists. What I might be missing?
Here's my activity class for the reference:
public class MainActivity extends Activity {
// Activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
public static final int MEDIA_TYPE_IMAGE = 1;
// directory name to store captured images
private static final String IMAGE_DIRECTORY_NAME = "SAT Practice";
private Uri fileUri; // file url to store image
private ImageView imgPreview;
private Button btnCapturePicture;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgPreview = (ImageView) findViewById(R.id.imgPreview);
btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);
/**
* Capture image button click event
*/
btnCapturePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// capture picture
captureImage();
}
});
}
/**
* Capturing Camera Image will lauch camera app requrest image capture
*/
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
/**
* Here we store the file url as it will be null after returning from camera
* app
*/
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on scren orientation
// changes
outState.putParcelable("file_uri", fileUri);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}
/**
* Receiving activity result method will be called after closing the camera
* */
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
// display it in image view
previewCapturedImage();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),"User cancelled image capture", Toast.LENGTH_SHORT).show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),"Sorry! Failed to capture image", Toast.LENGTH_SHORT).show();
}
}
}
/**
* Display image from a path to ImageView
*/
private void previewCapturedImage() {
try {
imgPreview.setVisibility(View.VISIBLE);
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
imgPreview.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
/**
* Creating file uri to store image
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.i(IMAGE_DIRECTORY_NAME, "Oops! Failed create "+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
}
So, as Jörn pointed out, for API level 23 and higher, here's what the documentation says:
If the device is running Android 6.0 or higher, and your app's target SDK is 23 or higher: The app has to list the permissions in the manifest, and it must request each dangerous permission it needs while the app is running.
In this answer, we can see the list of permissions that are dangerous (like reading/writing to external storage, calendars, location access etc). In my case, I the dangerous permissions are reading and writing to the external storage. Therefore, in my clicklistener to start the camera, I asked user for the permissions as:
int MY_PERMISSIONS_REQUEST_READ_AND_WRITE_EXTERNAL_STORAGE;
btnCapturePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if((ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
|| (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED))
{
ActivityCompat.requestPermissions
(MainActivity.this, new String[]{
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
},MY_PERMISSIONS_REQUEST_READ_AND_WRITE_EXTERNAL_STORAGE);
}
//captureImage() method will start the camera. All reading/writing stuff is implemented in this method
captureImage();
}
});
When the app calls requestPermissions(), the system shows a standard dialog box to the user asking whether to allow the permissions or not.
As user5038993 has described for target sdk 23 or higher we have to take permission for reading and writing any thing in device..once you click on allow you can do your stuff...
#Override
public void onClick(View v) {
if((ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE)!=PackageManager.PERMISSION_GRANTED)
|| (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED))
{
ActivityCompat.requestPermissions
(MainActivity.this, new String[]{
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
},MY_PERMISSIONS_REQUEST_READ_AND_WRITE_EXTERNAL_STORAGE);
}
}
I am creating an app where I want the user to pick which folder to save their images in. I first want to see if I could figure out how to save the images in another folder besides the default folder but I keep getting an error and can't figure out why.
Here is the code I have to start the camera intent and to get the file directory name
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_smart_wardrobe);
camera = (Button)findViewById(R.id.cameraBtn);
camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
file = getOutputMediaFileUri();
intent.putExtra(MediaStore.EXTRA_OUTPUT, file);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE );
}
});
}
Here is the code for the uriFileDirectory
private static Uri getOutputMediaFileUri(){
return Uri.fromFile(getOutputMediaFile());
}
private static File getOutputMediaFile(){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
if (! mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
return mediaFile;
}
Here is my onActivityResult method
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// Image captured and saved to fileUri specified in the Intent
Toast.makeText(this, "Image saved to:\n" +
data.getData(), Toast.LENGTH_LONG).show();
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the image capture
} else {
Toast.makeText(this, "There is someting wrong with your code", Toast.LENGTH_LONG).show();
}
}
if (requestCode == SELECT_PICTURE){
if (resultCode == RESULT_OK) {
images = data.getData();
selectedImagePath = getPath(images);
}
}
}
Can someone please help fix my code?
Check first your permission in Manifest.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
and onActivityResult method check that is it returning a file path or not. add the line in this method
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// Image captured and saved to fileUri specified in the Intent
Toast.makeText(this, "Image saved to:\n" +
file, Toast.LENGTH_LONG).show();
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the image capture
} else {
Toast.makeText(this, "There is someting wrong with your code", Toast.LENGTH_LONG).show();
}
}
the problem was in your toast. In Camera Intent we get intent as null and you are trying to taking data from there. you have to use Uri.
This works fine on almost every device but reopens camera once the image captured and user presses save.
Launch Camera:
private void launchCamera() {
try
{
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = getFilePath(2);
imageUri = Uri.fromFile(file);
cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,imageUri);
startActivityForResult(cameraIntent, 1);
}catch(Exception e){
Log.v("Exception ", e.toString());
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
try {
if (resultCode == RESULT_OK){
switch (requestCode) {
case 1:
try{
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
imgView.setImageBitmap(bitmap);
break;
}catch (Exception e) {
Log.v("Exception ", e.toString());
}
default:
break;
}
}
}
catch(Exception e){
Log.v("Exception ", e.toString());
}
}
Create Temp File path:
private File getFilePath(int type) {
File mediaFile = null;
try{
File mediaStorageDir = null;
Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
if(isSDPresent) {
String path = Environment.getExternalStorageDirectory()+"/MyFolder";
mediaStorageDir = new File(path);
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.v("Exception ", "failed to create directory");
return mediaFile;
}
}
} else {
mediaStorageDir = appContext.getDir("MyFolder", Context.MODE_PRIVATE);
}
if (type == 2){
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "MyFolder_IMG_"+ String.valueOf(UUID.randomUUID()) + ".png");
}
} catch(Exception e){
Log.v("Exception ", e.toString());
}
return mediaFile;
}
This works fine on almost every device
At best, it "works fine" for the devices that you have tried, and for the camera apps that you have tried on those devices. There are over 10,000 Android device models, and there are hundreds of camera apps on the Play Store. That leads to millions of combinations.
Ideally, the activity launched by MediaStore.ACTION_IMAGE_CAPTURE would return control to your app, via setResult() and finish(), after the user has taken a picture. However, there is no requirement, validated by any sort of approval process, that forces developers of camera apps to return control to you after the user has taken a picture.
Your options are either to live with the behavior as it stands, advising users to press BACK if needed to return to your app, or to skip MediaStore.ACTION_IMAGE_CAPTURE and implement your own logic to take a picture with the camera.
How to use camera in android so that the user can toggle between the camera mode and recorder mode whilst in the same camera app, as you can see the small slide control in the center of the right side of the image below.
The stock camera app is open source. Why not just take a look at how it is implemented?
Use Tow Button One For Image and Other for Video in UI....
/**** Camera / Video Demo ****************/
public class CameraDemoActivity extends Activity {
// Activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
// directory name to store captured images and videos
private static final String IMAGE_DIRECTORY_NAME = "Hello Camera";
private Uri fileUri; // file url to store image/video
private ImageView imgPreview;
private VideoView videoPreview;
private Button btnCapturePicture, btnRecordVideo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgPreview = (ImageView) findViewById(R.id.imgPreview);
videoPreview = (VideoView) findViewById(R.id.videoPreview);
btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);
btnRecordVideo = (Button) findViewById(R.id.btnRecordVideo);
/*
* Capture image button click event
*/
btnCapturePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// capture picture
captureImage();
}
});
/*
* Record video button click event
*/
btnRecordVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// record video
recordVideo();
}
});
// Checking camera availability
if (!isDeviceSupportCamera()) {
Toast.makeText(getApplicationContext(),
"Sorry! Your device doesn't support camera",
Toast.LENGTH_LONG).show();
// will close the app if the device does't have camera
finish();
}
}
/**
* Checking device has camera hardware or not
* */
private boolean isDeviceSupportCamera() {
if (getApplicationContext().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
/*
* Capturing Camera Image will lauch camera app requrest image capture
*/
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
/*
* Here we store the file url as it will be
* null after returning from camera
* app
*/
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on scren orientation
// changes
outState.putParcelable("file_uri", fileUri);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}
/*
* Recording video
*/
private void recordVideo() {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
// set video quality
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the
// image file
// name
// start the video capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
}
/**
* Receiving activity result method
* will be called after closing the camera
* */
#Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
// display it in image view
previewCapturedImage();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
} else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// video successfully recorded
// preview the recorded video
previewVideo();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled recording
Toast.makeText(getApplicationContext(),
"User cancelled video recording", Toast.LENGTH_SHORT)
.show();
} else {
// failed to record video
Toast.makeText(getApplicationContext(),
"Sorry! Failed to record video", Toast.LENGTH_SHORT)
.show();
}
}
}
/*
* Display image from a path to ImageView
*/
private void previewCapturedImage() {
try {
// hide video preview
videoPreview.setVisibility(View.GONE);
imgPreview.setVisibility(View.VISIBLE);
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
imgPreview.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
/*
* Previewing recorded video
*/
private void previewVideo() {
try {
// hide image preview
imgPreview.setVisibility(View.GONE);
videoPreview.setVisibility(View.VISIBLE);
videoPreview.setVideoPath(fileUri.getPath());
// start playing
videoPreview.pause();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* ------------ Helper Methods ----------------------
* */
/*
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/*
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard
// location.getExternalStoragePublicDirectory(
// Environment.DIRECTORY_PICTURES),IMAGE_DIRECTORY_NAME);
File mediaStorageDir = new File(
Environment
.getExternalStorageDirectory(),
IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "VID_" + timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
}
Add toggle button and set some value in it. let say 0 or 1
and then capture image/record video button.
and when toggle value is 0 call camera method and when toggle value is 1 call video method.
here is code for camera and video recording
Capture image
Record Video
implement both classes methods in one class. and then call onSnapClick for camera and startRecording() for video.
Hope this will help.
Try to use default functionality of camera and video like this-
Intent intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String fileName = "KeyICamImage"+System.currentTimeMillis()+".JPG";
String mPathImage = Environment.getExternalStorageDirectory()+ "/" + fileName;
file = new File(mPathImage);
mImageCaptureUri= Uri.fromFile( file );
try
{
intent1.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,mImageCaptureUri);
startActivityForResult(intent1, PICK_FROM_CAMERA);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
I don't know is it works or not, but try this
You should have
MediaRecorder recorder;
Camera camera;
Try to switching between video and photo by using
camera.setPreviewDisplay(holder);
or recorder.setPreviewDisplay(holder); in your surfaceCreated(SurfaceHolder holder). When you switching you should recreate surfaceView. Stock camera app recreates whole activity.