I tried to set an Android camera preview on my Activity but failed. There's nothing but black screen on my surface View. Seems to be too simple for others but I still cannot figure it out.
Here's my code:
package com.example.peterchen.camerapreviewexample;
import android.hardware.Camera;
import android.graphics.PixelFormat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import java.io.IOException;
public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback {
Camera myCamera;
SurfaceView previewSurfaceView;
SurfaceHolder previewSurfaceHolder;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
previewSurfaceView = (SurfaceView)findViewById(R.id.surfaceView);
previewSurfaceHolder = previewSurfaceView.getHolder();
previewSurfaceHolder.addCallback(this);
previewSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public void onResume() {
super.onResume();
myCamera.open();
myCamera.startPreview();
}
#Override
public void onPause() {
myCamera.stopPreview();
myCamera.release();
myCamera=null;
super.onPause();
}
#Override
public void surfaceCreated(SurfaceHolder holder) {}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {}
}
my layout xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.peterchen.camerapreviewexample.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="#+id/textView" />
<SurfaceView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/surfaceView"
android:layout_alignParentRight="true"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentBottom="true" />
</RelativeLayout>
and my manifest xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.peterchen.camerapreviewexample">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.CAMERA"></uses-permission>
Great thanks to all of you guys.
You can try to below code
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical" >
<SurfaceView
android:id="#+id/surfaceview"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="1" >
<Button
android:id="#+id/startcamerapreview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="Show Preview" />
<Button
android:id="#+id/stopcamerapreview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="Stop Preview" />
</LinearLayout>
</LinearLayout>
AndroidCamera.java
import android.app.Activity;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class AndroidCamera extends Activity implements SurfaceHolder.Callback
{
Camera camera;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
Button buttonStartCameraPreview, buttonStopCameraPreview;
boolean previewing = false;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonStartCameraPreview = (Button) findViewById(R.id.startcamerapreview);
buttonStopCameraPreview = (Button) findViewById(R.id.stopcamerapreview);
surfaceView = (SurfaceView) findViewById(R.id.surfaceview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
buttonStartCameraPreview.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
if (!previewing)
{
camera = Camera.open();
if (camera != null)
{
try
{
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
});
buttonStopCameraPreview.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
if (camera != null && previewing)
{
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
}
});
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
{
// TODO Auto-generated method stub
}
#Override
public void surfaceCreated(SurfaceHolder holder)
{
// TODO Auto-generated method stub
}
#Override
public void surfaceDestroyed(SurfaceHolder holder)
{
// TODO Auto-generated method stub
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.camera.preview"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.CAMERA" >
</uses-permission>
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".AndroidCamera"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Replace "AndroidCamera.java" your 90 Degree Screen Rotate Problem Solve
import android.app.Activity;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class AndroidCamera extends Activity implements SurfaceHolder.Callback
{
Camera camera;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
Button buttonStartCameraPreview, buttonStopCameraPreview;
boolean previewing = false;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonStartCameraPreview = (Button) findViewById(R.id.startcamerapreview);
buttonStopCameraPreview = (Button) findViewById(R.id.stopcamerapreview);
surfaceView = (SurfaceView) findViewById(R.id.surfaceview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
buttonStartCameraPreview.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
if (!previewing)
{
camera = Camera.open();
if (camera != null)
{
try
{
camera.setDisplayOrientation(90);
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
});
buttonStopCameraPreview.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
if (camera != null && previewing)
{
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
}
});
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
{
// TODO Auto-generated method stub
}
#Override
public void surfaceCreated(SurfaceHolder holder)
{
// TODO Auto-generated method stub
}
#Override
public void surfaceDestroyed(SurfaceHolder holder)
{
// TODO Auto-generated method stub
}
}
Related
I am trying to click only a rectangular portion of the screen from camera using this code:
Java code:
package com.example.cameraapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.IOException;
public class CameraActivity extends Activity implements Camera.PictureCallback, SurfaceHolder.Callback {
public static final String EXTRA_CAMERA_DATA = "camera_data";
private static final String KEY_IS_CAPTURING = "is_capturing";
private Camera mCamera, dummyCamera;
private ImageView mCameraImage;
private SurfaceView mCameraPreview,s1;
private Button mCaptureImageButton;
private byte[] mCameraData;
private boolean mIsCapturing;
private View v1;
private View.OnClickListener mCaptureImageButtonClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
// mCamera.release();
// mCamera = Camera.open();
// mCamera.setPreviewDisplay(mCameraPreview.getHolder());
// mCamera.startPreview();
// final SurfaceHolder surfaceHolder = mCameraPreview.getHolder();
// surfaceHolder.addCallback(CameraActivity.this);
// surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
captureImage();
}catch (Exception e){
e.printStackTrace();
}
}
};
private View.OnClickListener mRecaptureImageButtonClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
setupImageCapture();
}
};
private View.OnClickListener mDoneButtonClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mCameraData != null) {
Intent intent = new Intent();
intent.putExtra(EXTRA_CAMERA_DATA, mCameraData);
setResult(RESULT_OK, intent);
} else {
setResult(RESULT_CANCELED);
}
finish();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
mCameraImage = (ImageView) findViewById(R.id.camera_image_view);
mCameraImage.setVisibility(View.INVISIBLE);
v1 = findViewById(R.id.v1);
mCameraPreview = (SurfaceView) findViewById(R.id.preview_view);
s1 = (SurfaceView) findViewById(R.id.preview_view_1);
// final SurfaceHolder surfaceHolder = mCameraPreview.getHolder();
// surfaceHolder.addCallback(this);
// surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
final SurfaceHolder surfaceHolder2 = s1.getHolder();
surfaceHolder2.addCallback(this);
surfaceHolder2.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mCaptureImageButton = (Button) findViewById(R.id.capture_image_button);
mCaptureImageButton.setOnClickListener(mCaptureImageButtonClickListener);
final Button doneButton = (Button) findViewById(R.id.done_button);
doneButton.setOnClickListener(mDoneButtonClickListener);
mIsCapturing = true;
}
#Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putBoolean(KEY_IS_CAPTURING, mIsCapturing);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mIsCapturing = savedInstanceState.getBoolean(KEY_IS_CAPTURING, mCameraData == null);
if (mCameraData != null) {
setupImageDisplay();
} else {
setupImageCapture();
}
}
#Override
protected void onResume() {
super.onResume();
if (mCamera == null) {
try {
mCamera = Camera.open();
// dummyCamera = mCamera;
mCamera.setPreviewDisplay(s1.getHolder());
// dummyCamera.setPreviewDisplay(s1.getHolder());
if (mIsCapturing) {
// dummyCamera.startPreview();
mCamera.startPreview();
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(CameraActivity.this, "Unable to open camera.", Toast.LENGTH_LONG)
.show();
}
}
}
#Override
protected void onPause() {
super.onPause();
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
}
#Override
public void onPictureTaken(byte[] data, Camera camera) {
mCameraData = data;
setupImageDisplay();
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if (mCamera != null) {
try {
// mCamera.stopPreview();
mCamera.setPreviewDisplay(holder);
// dummyCamera.setPreviewDisplay(s1.getHolder());
if (mIsCapturing) {
mCamera.startPreview();
// dummyCamera.startPreview();
}
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(CameraActivity.this, "Unable to start camera preview.", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
private void captureImage() {
mCamera.takePicture(null, null, this);
}
private void setupImageCapture() {
try {
mCameraImage.setVisibility(View.INVISIBLE);
mCameraPreview.setVisibility(View.VISIBLE);
s1.setVisibility(View.VISIBLE);
v1.setVisibility(View.VISIBLE);
mCamera.setPreviewDisplay(s1.getHolder());
mCamera.startPreview();
mCaptureImageButton.setText(R.string.capture_image);
mCaptureImageButton.setOnClickListener(mCaptureImageButtonClickListener);
}catch (Exception e){
e.printStackTrace();
}
}
private void setupImageDisplay() {
Bitmap bitmap = BitmapFactory.decodeByteArray(mCameraData, 0, mCameraData.length);
Bitmap resizedbitmap1=Bitmap.createBitmap(bitmap, 0,0,mCameraPreview.getWidth(), mCameraPreview.getHeight());
mCameraImage.setImageBitmap(resizedbitmap1);
mCamera.stopPreview();
mCameraPreview.setVisibility(View.INVISIBLE);
s1.setVisibility(View.INVISIBLE);
v1.setVisibility(View.INVISIBLE);
mCameraImage.setVisibility(View.VISIBLE);
mCaptureImageButton.setText(R.string.recapture_image);
mCaptureImageButton.setOnClickListener(mRecaptureImageButtonClickListener);
}
}
Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/transparent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/capturing_image" />
<FrameLayout
android:id="#+id/camera_frame"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<ImageView
android:id="#+id/camera_image_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<SurfaceView
android:id="#+id/preview_view_1"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<View
android:id="#+id/v1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#CCFFFFFF"/>
<SurfaceView
android:id="#+id/preview_view"
android:layout_margin="80dp"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- <LinearLayout-->
<!-- android:layout_width="match_parent"-->
<!-- android:background="#android:color/transparent"-->
<!-- android:layout_height="match_parent">-->
<!-- -->
<!-- </LinearLayout>-->
</FrameLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center"
android:orientation="horizontal">
<Button
android:id="#+id/capture_image_button"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="#string/capture_image" />
<Button
android:id="#+id/done_button"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="#string/done" />
</LinearLayout>
</LinearLayout>
Here seems to be 2 workarounds:
Either i dynamically set the surface view "camera_image_view" at the time user try to capture screen. But i tried that in onClick and it is not working. Please suggest me some changes if you found any bug in that.
Clicking a full screen image and then cropping it to whatever fits inside the length and width of "camera_image_view". I tried this also but i think there is some flaw in this line:
Bitmap resizedbitmap1=Bitmap.createBitmap(bitmap, 0,0,mCameraPreview.getWidth(), mCameraPreview.getHeight());
as it is generating some broken colors instead of the cropped image.
So please help me with any of the two ways as both will work for me.
I am working on a QR decoder app in which i have created a SurfaceView to display camera output and a ImageButton to select an image from gallery.
I am using google play services to decode the QR code which requires to use surface view to scan the QR using camera. But it is not focusing on its own.
Below is the code for the same.
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.SparseArray;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.Detector;
import com.google.android.gms.vision.Frame;
import com.google.android.gms.vision.barcode.Barcode;
import com.google.android.gms.vision.barcode.BarcodeDetector;
public class Scanner extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scanner);
final SurfaceView cameraView = (SurfaceView) findViewById(R.id.camera_view);
BarcodeDetector barcodeDectector = new BarcodeDetector.Builder(this).setBarcodeFormats(Barcode.QR_CODE).build();
final CameraSource cameraSource = new CameraSource.Builder(this,barcodeDectector).setRequestedPreviewSize(1920,1080).build();
cameraView.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
try {
cameraSource.start(cameraView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
cameraSource.stop();
}
});
barcodeDectector.setProcessor(new Detector.Processor<Barcode>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> barcodes = detections.getDetectedItems();
//QRcode found hence move to intent action.
if( barcodes.size() != 0){
Intent i = new Intent(Scanner.this,Verify.class);
i.putExtra("xml",barcodes.valueAt(0).displayValue);
startActivity(i);
}
}
});
ImageButton scanImage = (ImageButton) findViewById(R.id.scanImage);
scanImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//button action to be added
}
});
}
}
The activity_scanner.xml is as follows.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"">
<SurfaceView
android:layout_width="match_parent"
android:layout_height="400dip"
android:layout_weight="70"
android:id="#+id/camera_view"
android:layout_alignParentLeft="true"
/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/scanImage"
android:layout_below="#+id/camera_view"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:src="#drawable/ic_image_black_48dp"
android:layout_alignRight="#+id/camera_view"
android:layout_alignEnd="#+id/camera_view" />
</RelativeLayout>
Try extending Surface view like this, and setFocusable(true).
public class CameraView extends SurfaceView implements SurfaceHolder.Callback {
public CameraView(Context context) {
super(context);
getHolder().addCallback(this);
setFocusable(true);
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
}
EDIT 1:
Then in layout you can use this class like this,
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://s...content-available-to-author-only...d.com/apk/res/android"
xmlns:tools="http://s...content-available-to-author-only...d.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<com.abhayjatindoshi.encryptorcode.qrlogin.javaclass.CameraView
android:layout_width="match_parent"
android:layout_height="400dip"
android:layout_weight="70"
android:id="#+id/camera_view"
android:layout_alignParentLeft="true"
/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/scanImage"
android:layout_below="#+id/camera_view"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:src="#drawable/ic_image_black_48dp"
android:layout_alignRight="#+id/camera_view"
android:layout_alignEnd="#+id/camera_view" />
</RelativeLayout>
Use Layout like above.
try this:
cameraView.requestFocus();
cameraView.setFocusableInTouchMode(true);
cameraView.setFocusable(true);
cameraView.requestFocus();
Above did not solved mine "focus" problem but i come a cross other solution which helped me:
private void setCamFocusMode(){
if(null == mCamera) {
return;
}
/* Set Auto focus */
Parameters parameters = mCamera.getParameters();
List<String> focusModes = parameters.getSupportedFocusModes();
if(focusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)){
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
} else
if(focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)){
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
}
mCamera.setParameters(parameters);
}
oryginally posted here:
https://stackoverflow.com/a/27092999/6225516
If somebody still looking for this yet, I've solved it by adding .setAutoFocusEnabled(true) before .build, in the line:
BarcodeDetector barcodeDectector = new BarcodeDetector.Builder(this)
.setBarcodeFormats(Barcode.QR_CODE)
.build();*
I'm new to Android Application Development, I was trying to build a basic Flashlight app but seems like most of the libraries are deprecated. I have tried doing Camera.Parameters camera; but still not working. Log shows the Exception : Caused by: java.lang.RuntimeException: Fail to connect to camera service.AndroidManifest.xml
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus"/>
MainActivity.java
package com.thenewboston.flashlight;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.hardware.Camera.Parameters;
public class MainActivity extends AppCompatActivity {
private android.hardware.Camera camera = null;
Parameters params;
Boolean isOn;
ImageButton imageButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageButton = (ImageButton) findViewById(R.id.imageButton);
Boolean isCameraFlash = getApplication().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA);
if(!isCameraFlash)
showNoCameraAlert();
else{
camera = android.hardware.Camera.open();
params = camera.getParameters();
}
}
private void showNoCameraAlert() {
new AlertDialog.Builder(this)
.setTitle("Error")
.setMessage("Sorry, your device doesn't support flash light!")
.setNeutralButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.show();
}
public void myButton(View view){
if (isOn){
setFlashOff();
}
else {
setFlashOn();
}
}
private void setFlashOn() {
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isOn = true;
}
private void setFlashOff() {
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isOn = false;
}
#Override
protected void onStop() {
super.onStop();
if(camera != null){
camera.release();
camera = null;
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.thenewboston.flashlight.MainActivity"
android:background="#000000">
<ImageButton
android:layout_width="150dp"
android:layout_height="150dp"
android:id="#+id/imageButton"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:src="#drawable/mytoggle"
android:scaleType="fitCenter"
android:background="#null"
android:onClick="myButton" />
</RelativeLayout>
I know, I'm using outdated stuff in my code, but that's probably because I have not seen anyone building flashlight app for Marshmallow. If anyone can suggest new code it will be helpful or correct my code(given above) will be thankful.
I try to display camera preview on a surface. but it just display black surface. What should I do ? I put the code below
Thanks for your help
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import java.io.IOException;
public class MainActivity extends ActionBarActivity implements SurfaceHolder.Callback {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().setFormat(PixelFormat.UNKNOWN);
SurfaceView surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
SurfaceHolder surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
Camera camera = Camera.open();
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<SurfaceView
android:id="#+id/surfaceView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="test.frontcamerateststartup" >
<uses-permission android:name="android.permission.CAMERA"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
............................................................................................................................................................................
put the following code in surfaceCreated()
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
The surface needs to be setup before use
I'm following this tutorial to learn Android's Camera API. I made it the end of the first section (right before "Providing an overlay" begins), and I'm getting the following error:
06-20 23:33:50.903: ERROR/AndroidRuntime(1114): at android.hardware.Camera.startPreview(Native Method)
06-20 23:33:50.903: ERROR/AndroidRuntime(1114): at com.sobel.Sobel.startCamera(Sobel.java:73)
06-20 23:33:50.903: ERROR/AndroidRuntime(1114): at com.sobel.Sobel.surfaceChanged(Sobel.java:36)
(Full trace)
Git repo here. Main Activity here. Manifest here.
I checked and re-checked my code and have followed the tutorial to a t, so what could be causing this error?
Try setting the type of Surface in initCamera().
private void initCamera() {
mCamSV = (SurfaceView)findViewById(R.id.surface_camera);
mCamSH = mCamSV.getHolder();
mCamSH.addCallback(this);
**mCamSH.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);**
}
EDIT 1
I am copying all the files here which worked for me with android 2.2 sdk
Activity
package com.stack.camera;
import java.io.IOException;
import android.app.Activity;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.WindowManager;
import android.widget.FrameLayout;
public class CameraStackActivity extends Activity implements SurfaceHolder.Callback {
private Camera mCam;
private SurfaceView mCamSV;
private SurfaceHolder mCamSH;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
initCamera();
}
#Override
public void onDestroy() {
stopCamera();
}
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
startCamera(holder, width, height);
}
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
mCam = Camera.open();
try {
mCam.setPreviewDisplay(holder);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
private void initCamera() {
mCamSV = (SurfaceView)findViewById(R.id.surface_camera);
mCamSH = mCamSV.getHolder();
mCamSH.addCallback(this);
mCamSH.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
private void startCamera(SurfaceHolder sh, int width, int height) {
Camera.Parameters p = mCam.getParameters();
// Camera.Size s = p.getSupportedPreviewSizes().get(0);
p.setPreviewSize(width, height);
mCam.setParameters(p);
try {
mCam.setPreviewDisplay(sh);
} catch (Exception e) {
}
mCam.startPreview();
}
private void stopCamera() {
mCamSH.removeCallback(this);
mCam.stopPreview();
mCam.release();
}
}
Layout
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<SurfaceView android:id="#+id/surface_camera"
android:layout_width="fill_parent" android:layout_height="fill_parent" />
</FrameLayout>
Manifest File
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.stack.camera"
android:versionCode="1"
android:versionName="1.0">
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name="CameraStackActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Check if it still doesnt work out for you.