Camera appears with black screen. Error fail to connect to camera service

2

I'd like to open the camera, but without the buttons that appear normally, I'd like to add my own buttons and assign features to them.

I searched but found no answer. The buttons I'm going to add will only redirect to another activity, it's not very complicated ... the problem is how do I add them and remove the ones that already exist.

I tried to make more of the error now and the application closes:

public class BuscaProduto extends AppCompatActivity {

private SurfaceView preview = null;
private SurfaceHolder previewHolder = null;
private Camera camera;
private boolean inPreview = false;
private boolean cameraConfigured = false;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.busca_produto);

    preview = (SurfaceView) findViewById(R.id.surfaceView);
    previewHolder = preview.getHolder();
    previewHolder.addCallback(surfaceCallback);
    previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}

@Override
public void onResume() {
    super.onResume();
    if (requestPermissionCamera(this)) {
        try {
            camera = Camera.open();
        } catch (Exception ex) {
            Log.e("Erro", ex.getMessage());
        }
        startPreview();
    }

}

@Override
public void onPause() {
    super.onPause();
    if (inPreview) {
        camera.release();
        camera = null;
        inPreview = false;
    }
}

private Camera.Size getBestPreviewSize(int width, int height, Camera.Parameters parameters) {
    Camera.Size result = null;
    for (Camera.Size size : parameters.getSupportedPreviewSizes()) {
        if (size.width <= width && size.height <= height) {
            if (result == null) {
                result = size;
            } else {
                int resultArea = result.width * result.height;
                int newArea = size.width * size.height;

                if (newArea > resultArea) {
                    result = size;
                }
            }
        }
    }

    return (result);
}

private void initPreview(int width, int height) {
    if (camera != null && previewHolder.getSurface() != null) {
        try {
            camera.setPreviewDisplay(previewHolder);
        } catch (Throwable t) {
            Log.e("SurfaceCallback", "Exception in setPreviewDisplay()", t);
            alert(t.getMessage());
        }

        if (!cameraConfigured) {
            Camera.Parameters parameters = camera.getParameters();
            Camera.Size size = getBestPreviewSize(width, height,
                    parameters);

            if (size != null) {
                parameters.setPreviewSize(size.width, size.height);
                camera.setParameters(parameters);
                cameraConfigured = true;
            }
        }
    }
}

private void startPreview() {
    if (cameraConfigured && camera != null) {
        camera.startPreview();
        inPreview = true;
    }
}

SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() {
    public void surfaceCreated(SurfaceHolder holder) {
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        initPreview(width, height);
        startPreview();
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
    }
};


public boolean requestPermissionCamera(Context context) {
    int REQUEST_PERMISSION_CAMERA = 221;
    boolean res = true;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            res = false;
            ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.CAMERA}, REQUEST_PERMISSION_CAMERA);
        }
    }
    return res;
}

private void alert(String s) {
    Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
}

xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <SurfaceView
        android:id="@+id/surfaceView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center" />

</LinearLayout>

Manifest:

<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera"/>
<uses-feature android:name="android.hardware.camera.autofocus" />

error:

java.lang.RuntimeException: Fail to connect to camera service
                                                                                  at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2790)
                                                                                  at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2819)
                                                                                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2254)
                                                                                  at android.app.ActivityThread.access$800(ActivityThread.java:141)
                                                                                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1212)
                                                                                  at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                  at android.os.Looper.loop(Looper.java:136)
                                                                                  at android.app.ActivityThread.main(ActivityThread.java:5113)
                                                                                  at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                  at java.lang.reflect.Method.invoke(Method.java:515)
                                                                                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
                                                                                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
                                                                                  at dalvik.system.NativeStart.main(Native Method)
                                                                               Caused by: java.lang.RuntimeException: Fail to connect to camera service
                                                                                  at android.hardware.Camera.native_setup(Native Method)
                                                                                  at android.hardware.Camera.<init>(Camera.java:374)
                                                                                  at android.hardware.Camera.open(Camera.java:344)
                                                                                  at br.ufop.socialmarket.BuscaProduto.onResume(BuscaProduto.java:53)
                                                                                  at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1192)
                                                                                  at android.app.Activity.performResume(Activity.java:5324)
                                                                                  at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2780)
                                                                                  at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2819) 
                                                                                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2254) 
                                                                                  at android.app.ActivityThread.access$800(ActivityThread.java:141) 
                                                                                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1212) 
                                                                                  at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                                  at android.os.Looper.loop(Looper.java:136) 
                                                                                  at android.app.ActivityThread.main(ActivityThread.java:5113) 
                                                                                  at java.lang.reflect.Method.invokeNative(Native Method) 

How the screen looks:

    
asked by anonymous 20.08.2016 / 18:00

1 answer

1

Use SurfaceView for your camera view as described in the documentation on the own Android. Under the conditions of Android 6.0 (Api level 23) there is the Requesting Permissions at Run Time which issue of permissions, which is very interesting you give read and learn more.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <SurfaceView
        android:id="@+id/preview"
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:layout_gravity="center" />

    <Button android:text="Freeze"
        android:id="@+id/someButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>

Then in your Main class do so:

private SurfaceView preview=null;
private SurfaceHolder previewHolder=null;
private Camera camera=null;

private boolean inPreview=false;
private boolean cameraConfigured=false;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.surface_view);

    preview = (SurfaceView)findViewById(R.id.preview);
    previewHolder = preview.getHolder();
    previewHolder.addCallback(surfaceCallback);
    previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}

@Override
public void onResume() {
    super.onResume();

    camera=Camera.open();
    startPreview();
}

SurfaceHolder.Callback surfaceCallback=new SurfaceHolder.Callback() {
    public void surfaceCreated(SurfaceHolder holder) {
        // no-op -- wait until surfaceChanged()
    }

    public void surfaceChanged(SurfaceHolder holder,
                               int format, int width,
                               int height) {
        initPreview(width, height);
        startPreview();
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        // no-op
    }
};

private void initPreview(int width, int height) {
    if (camera!=null && previewHolder.getSurface()!=null) {
        try {
            camera.setPreviewDisplay(previewHolder);
        }
        catch (Throwable t) {
            Log.wtf("teste","teste");
            Toast.makeText(MainViewPage.this, t.getMessage(), Toast.LENGTH_LONG)
                    .show();
        }

        if (!cameraConfigured) {
            Camera.Parameters parameters=camera.getParameters();
            Camera.Size size=getBestPreviewSize(width, height,
                    parameters);

            if (size!=null) {
                parameters.setPreviewSize(size.width, size.height);
                camera.setParameters(parameters);
                cameraConfigured=true;
            }
        }
    }
}

private Camera.Size getBestPreviewSize(int width, int height,
                                       Camera.Parameters parameters) {
    Camera.Size result=null;

    for (Camera.Size size : parameters.getSupportedPreviewSizes()) {
        if (size.width<=width && size.height<=height) {
            if (result==null) {
                result=size;
            }
            else {
                int resultArea=result.width*result.height;
                int newArea=size.width*size.height;

                if (newArea>resultArea) {
                    result=size;
                }
            }
        }
    }

    return(result);
}

private void startPreview() {
    if (cameraConfigured && camera!=null) {
        camera.startPreview();
        inPreview=true;
    }
}

Permissions

Considering Android 6.0 (Api level 23), you need to adapt this method below in your code, taking into account that also when setting up an image capture action it is necessary to give permission for WRITE_EXTERNAL_STORAGE writing and reading READ_EXTERNAL_STORAGE .

public boolean requestPermissionCamera(Context context){
        int REQUEST_PERMISSION_CAMERA = 221;
        boolean res=true;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                res = false;
                ActivityCompat.requestPermissions((Activity) context, new String[]{
                                Manifest.permission.CAMERA},
                        REQUEST_PERMISSION_CAMERA);

            }
        }
        return res;
    }

Screenshot

Takealookat .

    
20.08.2016 / 18:19