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

Asked

Viewed 292 times

2

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

I looked it up, but I couldn’t find any answers. The buttons I’m going to add will just redirect to another Activity, it’s nothing too complicated... the problem is how I add them and remove the ones that already exist.

I tried to do but now the error 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:

inserir a descrição da imagem aqui

1 answer

1


Use SurfaceView for your camera view as you describe the documentation on the website of Android itself. Under the conditions of Android 6.0(Api level 23) exists the Requesting Permissions at Run Time which is the 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), it is necessary to adapt this method below in your code, taking into account that also when placing an image capture action it is necessary to give permission to write and read WRITE_EXTERNAL_STORAGE and 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

inserir a descrição da imagem aqui

Take a look in this project.

  • I tried and is giving the error: fail to connect to camera service. I updated the post with my code

  • @Éowyn this error is giving because you are not giving permission to your camera! You are probably using Android 6.0.

  • @Éowyn as I said, this error is happening because you are not giving permission from the camera to your app. Before doing the permission programming, you can test by giving permission manually, which is why I took this screenshot for you to see working.

  • It had tested on an API 19 device and the targetSdkVersion in the manifest was set to 22. But I changed it to 23 and tried to request permission but the error continues :(

  • @Éowyn was what happened to me so I gave the permission manually and funfou.

  • Did you run my code just like that? Because it doesn’t want to work at all, there’s no permission when I’m going to move it manually

  • @Éowyn I made a scheme here to make it easier for you, but tomorrow I’ll help you if you can’t. I will post a method in my reply for you to adapt.

  • I tried to adapt and was giving the same error, then I decided to give a clean project and the application stopped to stop responding, but now the camera screen turns black. I’m already feeling pretty dumb about not being able to do what you say

  • @Éowyn I adapted the requestPermissionCamera in my code, but I didn’t want to post straight to you last night (on purpose) to make you think a little. Try a little more, anything when I get home, I give one more help. Now I’m in the job.

  • It worked! Sorry for the delay to give the return... it was the same mistake of my other problem, I was using the permission tags in the wrong place. Thank you very much!

  • @Éowyn for nothing! Need give a shout here!

Show 6 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.