Open front camera by default - java

I am creating an app, in which I am setting a profile image and cover image ,so on setting profile image I want to open the front camera by default using intent.
I am using
pictureIntent.putExtra("android.intent.extras.CAMERA_FACING",1);
Its working on Sony but when I tested on a Samsung Galaxy J4 ,it's opening the back camera. I searched and found somewhere that for Samsung one should use value 2.
However it's not working.
I want to do this using intent only.
Does anyone have an idea about it?

You can do like below,
private Camera openFrontFacingCamera() {
int cameraCount = 0;
Camera cam = null;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
cameraCount = Camera.getNumberOfCameras();
for ( int camIdx = 0; camIdx < cameraCount; camIdx++ ) {
Camera.getCameraInfo( camIdx, cameraInfo );
if ( cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT ) {
try {
cam = Camera.open( camIdx );
} catch (RuntimeException e) {
Log.e(TAG, "Camera failed to open: " + e.getLocalizedMessage());
}
}
}
return cam;
}
And then use it in your app as follows:
public static Camera getCameraInstance() {
Camera c = null;
try {
c = openFrontFacingCamera();
}
catch (Exception e){
}
return c;
}

Related

Codes to print PDF not working at the last step

I am writing an app that can create Maths worksheet with answer pages in PDF format. I want to add a print function to allow printing the worksheet directly from the app.
In the PrintDocumentAdapter, the first half of the codes check the color of a certain pixel of the page to determine whether it is an answer page and reduce the number of pages to print accordingly. It then constructs a printingPDF document and sends it to print using 's writeTo() method in the onWrite().
Everything works fine until the last part. It reads the PDF correctly, checks the number of answer pages correctly, and sends a correct PDF with question pages only to the printing page. If I choose "Save as PDF" in the printing page, it saves the pages to a new PDF file with no problem. However, if I try to print with my printer that is connected to my phone with USB by clicking the print button, the printing page simply disappears and goes back to the main page of my app. (It is supposed to past those few pages to the printer app.) I tried several different android printer driver apps and the result was the same.
private void printWS() throws IOException {
findViewById(R.id.defaultTextView).setVisibility(View.INVISIBLE);
if (!loadedFile) {
File file = new File(getApplicationContext().getCacheDir(), getString(R.string.defaultFileName));
parcelFileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
} else {
parcelFileDescriptor = getContentResolver().openFileDescriptor(pdfUri, "r");
}
// Start printing
PrintManager printManager = (PrintManager) this.getSystemService(PRINT_SERVICE);
String jobName = getString(R.string.app_name);
PrintAttributes printAttributes = new PrintAttributes.Builder().setMediaSize(PrintAttributes.MediaSize.ISO_A4).build();
printManager.print(jobName, new PrintDocumentAdapter() {
int finalTotal;
#Override
public void onStart() {
if (parcelFileDescriptor != null) {
try {
pdfRenderer = new PdfRenderer(parcelFileDescriptor);
} catch (IOException e) {
e.printStackTrace();
}
}
int tempTotal = pdfRenderer.getPageCount();
Bitmap[] tempBitmap = new Bitmap[tempTotal];
finalTotal = tempTotal;
for (int pageNum = 0; pageNum < tempTotal; pageNum++) {
PdfRenderer.Page tempPage = pdfRenderer.openPage(pageNum);
tempBitmap[pageNum] = Bitmap.createBitmap(WS_WIDTH, WS_HEIGHT, Bitmap.Config.ARGB_8888);
tempPage.render(tempBitmap[pageNum], null, null, PdfRenderer.Page.RENDER_MODE_FOR_PRINT);
if (tempBitmap[pageNum].getPixel(0, 0) == Color.GRAY) {
finalTotal--;
}
tempPage.close();
}
}
PrintedPdfDocument printingPDF;
#Override
public void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal, LayoutResultCallback callback, Bundle bundle) {
printingPDF = new PrintedPdfDocument(getApplicationContext(), newAttributes);
if (cancellationSignal.isCanceled()) {
callback.onLayoutCancelled();
return;
}
if (finalTotal > 0) {
PrintDocumentInfo info = new PrintDocumentInfo
.Builder("Worksheet")
.setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT)
.setPageCount(finalTotal)
.build();
callback.onLayoutFinished(info, true);
} else {
callback.onLayoutFailed("Page count calculation failed.");
}
}
#Override
public void onWrite(PageRange[] pageRanges, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, WriteResultCallback callback) {
Bitmap[] loadedBitmap = new Bitmap[finalTotal];
for (int pageNum = 0; pageNum < finalTotal; pageNum++) {
PdfDocument.PageInfo printingPageInfo = new PdfDocument.PageInfo.Builder(WS_WIDTH, WS_HEIGHT, pageNum).create();
PdfDocument.Page printingPage = printingPDF.startPage(printingPageInfo);
if (cancellationSignal.isCanceled()) {
callback.onWriteCancelled();
printingPDF.close();
printingPDF = null;
return;
}
PdfRenderer.Page loadedPage = pdfRenderer.openPage(pageNum);
loadedBitmap[pageNum] = Bitmap.createBitmap(WS_WIDTH, WS_HEIGHT, Bitmap.Config.ARGB_8888);
loadedPage.render(loadedBitmap[pageNum], null, null, PdfRenderer.Page.RENDER_MODE_FOR_PRINT);
Canvas canvas = printingPage.getCanvas();
Paint paint = new Paint();
canvas.drawBitmap(loadedBitmap[pageNum], 0, 0, paint);
printingPDF.finishPage(printingPage);
loadedPage.close();
}
try {
printingPDF.writeTo(new FileOutputStream(destination.getFileDescriptor()));
} catch (IOException e) {
callback.onWriteFailed(e.toString());
return;
} finally {
printingPDF.close();
printingPDF = null;
}
PageRange[] writtenPages = new PageRange[]{PageRange.ALL_PAGES};
callback.onWriteFinished(writtenPages);
}
#Override
public void onFinish() {
try {
pdfRenderer.close();
parcelFileDescriptor.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}, printAttributes);
}
Can someone take a look at my codes and tell me what is going wrong? Please help! Thanks!
Nevermind. It turned out the codes are ok. What I needed to do was go to the settings of my phone and change the "Display pop-up windows while running in the background" of the printer driver app to "allow", then it worked perfectly!
I will keep the question and answer here in case someone encounters the same problem.

CameraDevice failing to create session [Camera2]

I'm trying to use the Camera2 API to stream camera data to a SurfaceView. I'm following this guide: Camera2 guide
I cannot get past step 5
MainActivity.java::onCreate()
setContentView(R.layout.activity_main);
surfaceView = (SurfaceView)findViewById(R.id.surface);
manager = (CameraManager)getSystemService(Context.CAMERA_SERVICE);
MainActivity.java::onClick()
for (String id : manager.getCameraIdList()) {
CameraCharacteristics characteristics = manager.getCameraCharacteristics(id);
Integer direction = characteristics.get(CameraCharacteristics.LENS_FACING);
if (direction != null && direction == CameraCharacteristics.LENS_FACING_BACK) {
if (checkCallingOrSelfPermission("android.permission.CAMERA") == PackageManager.PERMISSION_GRANTED)
manager.openCamera(id, new StateCallback(), null);
break;
}
}
MainActivity.java.StateCallback::onOpened(CameraDevice camera)
List<Surface> surfaces = new LinkedList<>();
surfaces.add(surfaceView.getHolder().getSurface());
CaptureRequest.Builder builder = camera.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
builder.addTarget(surfaces.get(0));
camera.createCaptureSession(surfaces, new CameraCaptureSession.StateCallback() {
#Override
public void onConfigured(CameraCaptureSession session) {
Log.i(TAG, "Configured");
}
#Override
public void onConfigureFailed(CameraCaptureSession session) {
Log.e(TAG, "Configured failed"); // Ends up in this function :(
}
}, null);
The program ends up in the onConfigureFailed() function. I don't know what could be the error, and I don't know how to check what is.
My guess would be that I'm missing something in the CaptureRequest, but I have no idea what.
I'm running on a Samsung Galaxy S4.
add to onConfigured:
if (null == cameraDevice) {
Log.e(TAG, "updatePreview error, return");
return;
}
captureRequestBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
try {
cameraCaptureSessions.setRepeatingRequest(captureRequestBuilder.build(), null, mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
Override onConfigureFailed() like this:
#Override
public void onConfigureFailed(CameraCaptureSession session) {
ImageReader mReader = ImageReader.newInstance(640, 480, ImageFormat.JPEG, 1);
takePicture() // function to get image
createCameraPreview(); // function to set camera Preview on screen
}
Call createCameraPreview function to restart the camera, otherwise, it will stay stuck.
You can change the ImageReader with new values
ImageReader mReader = ImageReader.newInstance(640, 480, ImageFormat.JPEG, 1);
And call the takePicture() function again so that user don't have to click again to capture image.

Android FlashLight Application

I wrote an Android Flash Light application but that seems to show some strange behavior.
The code that is invoked on clicking the "Turn On" button is
public void flashLightOn(View view){
try {
if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH))
cam = Camera.open(0);
Camera.Parameters p = cam.getParameters();
p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
cam.setParameters(p);
cam.startPreview();
}catch (Exception e){
e.printStackTrace();
}
}
Now , the strange thing is that this app works fine on some phones and doesn't work on others.
I have tried it on my OnePlus One and Motorola Droid Mini and on both of them it works fine, but when I ran it on a Motorola Droid RAZR and Moto E it didn't work.
I am not able to understand the problem here. Can anyone help?
Replace your code with:
public void flashLightOn(View view){
try {
if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH))
{ // you don't added this
cam = Camera.open(0);
Camera.Parameters p = cam.getParameters();
p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
cam.setParameters(p);
cam.startPreview();
} // and this
}catch (Exception e){
e.printStackTrace();
}
}

Check which camera is Open Front or Back Android

I know i can set a boolean flag while opening front Camera. And if flag is true it means front camera is on.
But is there a way using Android API to know which Camera is Open right now? Front or Back.
public int getFrontCameraId() {
CameraInfo ci = new CameraInfo();
for (int i = 0 ; i < Camera.getNumberOfCameras(); i++) {
Camera.getCameraInfo(i, ci);
if (ci.facing == CameraInfo.CAMERA_FACING_FRONT) return i;
}
return -1; // No front-facing camera found
}
Camera Preview is inverting(upside donw) when i open Front Camera. So i have to add a check which Camera is open if FrontCamera is opened then matrix = 270. otherwise matrix =90.
onPreviewFrame(byte abyte0[] , Camera camera)
int[] rgbData = YuvUtils.decodeGreyscale(abyte0, mWidth,mHeight);
editedBitmap.setPixels(rgbData, 0, widthPreview, 0, 0, widthPreview, heightPreview);
finalBitmap = Bitmap.createBitmap(editedBitmap, 0, 0, widthPreview, heightPreview, matrix, true);
private boolean safeCameraOpen(int id) {
boolean qOpened = false;
try {
releaseCameraAndPreview();
mCamera = Camera.open(id);
qOpened = (mCamera != null);
} catch (Exception e) {
Log.e(getString(R.string.app_name), "failed to open Camera");
e.printStackTrace();
}
return qOpened;
}
private void releaseCameraAndPreview() {
mPreview.setCamera(null);
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
}
Since API level 9, the camera framework supports multiple cameras. If you use the legacy API and call open() without an argument, you get the first rear-facing camera.Android devices can have multiple cameras, for example a back-facing camera for photography and a front-facing camera for video calls. Android 2.3 (API Level 9) and later allows you to check the number of cameras available on a device using the Camera.getNumberOfCameras() method.
To access the primary camera, use the Camera.open() method and be sure to catch any exceptions, as shown in the code below:
/** A safe way to get an instance of the Camera object. */
public static Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
}
catch (Exception e){
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
On devices running Android 2.3 (API Level 9) or higher, you can access specific cameras using Camera.open(int). The example code above will access the first, back-facing camera on a device with more than one camera.
In new android.hardware.camera2 package, you can enquire from CameraCharacteristics.LENS_FACING property and each CameraDevice publishes its id with CameraDevice.getId() it's easy to get to the characteristics.
In the older camera API, I think the only way is to keep track of the index you opened it with.
private int cameraId;
public void openFrontCamera(){
cameraId = getFrontCameraId();
if (cameraId != -1)
camera = Camera.open(cameraId); //try catch omitted for brevity
}
Then use cameraId later, this little snippet might be a better way of achieving what you are trying to:
public void onOrientationChanged(int orientation) {
if (orientation == ORIENTATION_UNKNOWN) return;
android.hardware.Camera.CameraInfo info =
new android.hardware.Camera.CameraInfo();
android.hardware.Camera.getCameraInfo(cameraId, info);
orientation = (orientation + 45) / 90 * 90;
int rotation = 0;
if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
rotation = (info.orientation - orientation + 360) % 360;
} else { // back-facing camera
rotation = (info.orientation + orientation) % 360;
}
mParameters.setRotation(rotation);
}
if you have a custom Camera Activity you can try this method.
boolean inPreview;
in your on surfaceChanged method from surfaceView set
inPreview = True;
in your Camera.CallbackListener variable set
inPreview = false;

How to switch camera in android and show the preview

I have been busting my head over this, this is the last thing I need to complete and he app is done.
Basically, I created a camera for my app and I need to switch from back camera to front camera on onClick()...
When I switch, I lose the preview... When I record, the screen is black but the video get recorded... but no preview at all.. here is the code
#Override
protected void onCreate(Bundle saved) {
super.onCreate(saved);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.camera);
//some initializing code like checking flash, number of cameras...
preview = (FrameLayout) findViewById(R.id.camera_preview);
}
#Override
public void onResume(){
super.onResume();
if (Camera.getNumberOfCameras() < 2) {
a.id(R.id.camera_switch).clickable(false);
}
if(m!=null){
m.reset();
m.release();
m=null;
c.lock();
}
if (c != null) {
c.release();
c = null;
}
cam = "front";
Instance();
}
public void Instance(){
if(flash.equalsIgnoreCase("yes"))
a.id(R.id.camera_flash).clickable(true);
if(cam.equalsIgnoreCase("back")){
try{
m.reset();m=null;
c.stopPreview();
c.release();c.reconnect();
c = null;
}catch(Exception e){}
a.id(R.id.camera_flash).clickable(false);
Camera c = getCameraInstanceB(this);
parameters = c.getParameters();
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
c.setParameters(parameters);
cam = "front";
try {
c.setPreviewDisplay(mPreview.getHolder());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}c.startPreview();
}else{
try{
c.release();
c = null;
}catch(Exception e){}
c = getCameraInstance(this);
parameters = c.getParameters();
cam = "back";
}
m = new MediaRecorder();
// Create our Preview view and set it as the content of our activity.
mPreview = new CameraPreview(this, c);
int orien =getResources().getConfiguration().orientation;
if(orien ==1){
parameters.setRotation(0); // set rotation to save the picture
c.setDisplayOrientation(90);
cam_rotation =90;
parameters.setPictureSize(640, 480);
PIC_ORIENTATION = "portrait";
Toast.makeText(this, PIC_ORIENTATION, Toast.LENGTH_SHORT).show();
}else{
parameters.setRotation(0); // set rotation to save the picture
c.setDisplayOrientation(0);
parameters.setPictureSize(640, 480);
PIC_ORIENTATION = "landscape";
cam_rotation=0;
Toast.makeText(this, PIC_ORIENTATION, Toast.LENGTH_SHORT).show();
}
c.setParameters(parameters);
m.setCamera(c);
preview.addView(mPreview);
}
now the camera instances for back and front
public static Camera getCameraInstance(Cam cam){
c = null;
try {
c = Camera.open(CameraInfo.CAMERA_FACING_BACK); // attempt to get a Camera instance
Camera.Parameters parameters = c.getParameters();
parameters.setRecordingHint(true);
parameters.setFocusMode(Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
c.setParameters(parameters);
}
catch (Exception e){
// Camera is not available (in use or does not exist)
e.printStackTrace();
text = "The camera is in use";
//---set the data to pass back---
data.putExtra("vid",text);
cam.setResult(RESULT_OK, data);
//---close the activity---
cam.finish();
}
return c; // returns null if camera is unavailable
}
public static Camera getCameraInstanceB(Cam cam){
c = null;
try {
c = Camera.open(CameraInfo.CAMERA_FACING_FRONT); // attempt to get a Camera instance
Camera.Parameters parameters = c.getParameters();
parameters.setRecordingHint(true);
c.setParameters
(parameters);
}
catch (Exception e){
// Camera is not available (in use or does not exist)
e.printStackTrace();
text = "The camera is in use";
//---set the data to pass back---
data.putExtra("vid",text);
cam.setResult(RESULT_OK, data);
//---close the activity---
cam.finish();
}
return c; // returns null if camera is unavailable
}
on Resume()... everything is fine but when I switch... no more preview
After spending hours, I finally came up with a solution, basically, I just recreate the surfaceView on each switch as it was an onStart();
public void Instance(){
preview = (FrameLayout) findViewById(R.id.camera_preview);
//rest of the code here
Now it works like a charm... no more error even onResume

Categories