Camera problems: Fail to connect to camera service

2

I have a problem with my app that uses the camera on a device. However, whenever I try to use Camera.open() it gives an exception java.lang.RuntimeException: Fail to connect to camera service . I am trying to understand this error better, but it is my first application that I use a camera. Here is the code:

Manifest code:

<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.FLASHLIGHT"/>
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

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

Java code:

package br.com.camera;

import android.content.Intent;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Toast;

import com.melnykov.fab.FloatingActionButton;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.text.StringCharacterIterator;
import java.util.Date;

import butterknife.ButterKnife;
import butterknife.InjectView;

public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback {

    private Camera camera = null;
    private int camId = 1;
    @InjectView(R.id.surfaceView)
    SurfaceView surfaceView;
    @InjectView(R.id.btn_take_photo)
    FloatingActionButton btn_take_photo;
    SurfaceHolder surfaceHolder;
    Camera.PictureCallback jpegCallback;
    Camera.ShutterCallback shutterCallback;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_camera);
        ButterKnife.inject(this);
        surfaceHolder = surfaceView.getHolder();
        //Instalamos uma surfaceHolder.Callback então nós notificamos quando o underlying surface é criado e destroido.
        surfaceHolder.addCallback(this);
        //Confirguração precaria, ,as requer um android versão rioritaria 3.0
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        btn_take_photo.setOnClickListener(new FloatingActionButton.OnClickListener() {
            @Override
            public void onClick(View view) {
                cameraImage();
            }
        });
        jpegCallback = new Camera.PictureCallback() {
            @Override
            public void onPictureTaken(byte[] bytes, Camera camera) {
                FileOutputStream outputStream = null;
                File file_image = getDirc();
                if(!file_image.exists() && !file_image.mkdirs()){
                    Toast.makeText(getApplicationContext(),"Não pode criar diretorio para salvar imagem", Toast.LENGTH_SHORT).show();
                    return;
                }
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyymmddhhmmss");
                String date = simpleDateFormat.format(new Date());
                String photofile =  "Cam_demo" + date + ".jpeg";
                String file_name = file_image.getAbsolutePath() + "/" + photofile;
                File picFile = new File(file_name);
                try{
                    outputStream = new FileOutputStream(picFile);
                    outputStream.write(bytes);
                    outputStream.close();

                }catch (FileNotFoundException e) {

                }catch (IOException ex){

                }finally {

                }
                Toast.makeText(getApplicationContext(),"Imagem salvou... ",Toast.LENGTH_SHORT).show();
                refreshCamera();
                refreshGallery(picFile);
            }
        };
    }

    public void refreshCamera(){
        if(surfaceHolder.getSurface() == null){
            //Preview surface não existe
            return;
        }
        //Para preview antes de fazer as mudanças
        try{
            camera.stopPreview();
        }catch (Exception e){

        }
        //Coloca no preview tamanho e faz alguma mudança de tamanho, rotação ou reformata as mudanças aqui,
        // inicia o preview com novas configurações.
        try{
            camera.setPreviewDisplay(surfaceHolder);
            camera.startPreview();
        }catch (Exception e){

        }
    }

    public void refreshGallery(File file){
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        intent.setData(Uri.fromFile(file));
        sendBroadcast(intent);
    }

    private File getDirc(){
        File dics = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        return new File(dics,"Camera_demo");
    }

    public void cameraImage(){
        //Tira a foto
        camera.takePicture(null,null,jpegCallback);
    }

    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {
        //Abre a câmera
        try{
            camera = Camera.open();

            Camera.Parameters parameters;
            parameters = camera.getParameters();
            parameters.setPreviewFrameRate(20);
            parameters.setPictureSize(352,288);
            camera.setParameters(parameters);
            camera.setDisplayOrientation(90);

        }catch (RuntimeException ex){
            Log.e("ERRO",ex.getMessage());
            Toast.makeText(this,"Ocorreu um erro com a câmera! ",Toast.LENGTH_SHORT);
        }

        try{
            //O SurfaceView tem sido criado, agora comunica-se com a câmera para desenhar o Preview.
            camera.setPreviewDisplay(surfaceHolder);
            camera.startPreview();
        }catch (Exception e){
            Log.e("ERRO",e.getMessage());
        }

    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
        refreshCamera();
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
        //para preview w reinicia camera
        camera.stopPreview();
        camera.release();
        camera = null;
    }
}

08/01/2016

I've just been through a very strange situation, my device is the Lenovo VIBE A7010 and Camera.open() always gives Exception java.lang.RuntimeException: Fail to connect to câmera service , I decided to get another device, a Moto G first generation and look what happened, the application worked perfectly, I do not know what the problem of Lenovo a7010 , but lately I'm having a lot of headache with it when it comes to development, time trying to make it work in Android Studio.

    
asked by anonymous 30.07.2016 / 01:29

1 answer

1

I managed to solve the problem with the help of our colleague Ramaral, it was simple, the permissions of Android 6.0 are different from its previous versions, however, it is still necessary to declare in the manifest, follow the link that helped me and the code: answer

Code:

//...

    @Override
protected void onCreate(Bundle savedInstanceState) {

    //...

    permissoesAndroidM();

    //...

}

private void permissoesAndroidM(){
    if(PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)){

        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.CAMERA)) {

        } else {

            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA},
                    PERMISSIONS_REQUEST_CAMERA);

        }
    }
}

    @Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case PERMISSIONS_REQUEST_CAMERA: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //Abre a câmera
                openCamera();

            } else {

            }
            return;
        }
    }
}

private void openCamera(){
    try {
        Display display = getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        int x = size.x;
        int y = size.y;
        camera = Camera.open();
        Camera.Parameters parameters;
        parameters = camera.getParameters();
        int aux = display.getRotation();
        switch (aux) {
            case 0:
                camera.setDisplayOrientation(90);
                parameters.setRotation(90);
                parameters.setPreviewSize(y, x);
                parameters.setPictureSize(y, x);
                orientation = 90;
                //Toast.makeText(this, "Orientação: " + orientation, Toast.LENGTH_SHORT).show();
                break;
            case 1:
                camera.setDisplayOrientation(0);
                parameters.setRotation(0);
                parameters.setPreviewSize(x, y);
                parameters.setPictureSize(x, y);
                orientation = 0;
                //Toast.makeText(this, "Orientação: " + orientation, Toast.LENGTH_SHORT).show();
                break;
            case 2:
                camera.setDisplayOrientation(90);
                parameters.setRotation(90);
                parameters.setPreviewSize(y, x);
                parameters.setPictureSize(y, x);
                orientation = 90;
                //Toast.makeText(this, "Orientação: " + orientation, Toast.LENGTH_SHORT).show();
                break;
            case 3:
                camera.setDisplayOrientation(180);
                parameters.setRotation(180);
                parameters.setPreviewSize(x, y);
                parameters.setPictureSize(x, y);
                orientation = 180;
                //Toast.makeText(this, "Orientação: " + orientation, Toast.LENGTH_SHORT).show();
                break;
        }
        parameters.setPreviewFrameRate(20);
        parameters.setJpegQuality(100);
        camera.setParameters(parameters);
        //O SurfaceView tem sido criado, agora comunica-se com a câmera para desenhar o Preview.
        camera.setPreviewDisplay(surfaceHolder);
        camera.startPreview();
    } catch (RuntimeException ex) {
        Log.e("ERRO", ex.getMessage());
        Toast.makeText(this, getResources().getString(R.string.cameraErro), Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        Log.e("ERRO", e.getMessage());
        Toast.makeText(this, getResources().getString(R.string.cameraErro), Toast.LENGTH_SHORT).show();
    }
}

    @Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
    //Abre a câmera
    if(PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)) {
        openCamera();
    }
}

//...
    
06.08.2016 / 22:58