2
I have a problem in my application that uses the camera of a device. However, whenever I try to use the Camera.open()
he makes an exception java.lang.RuntimeException: Fail to connect to camera service
. I am trying to better understand this error, but it is my first application that I use a camera. Follow 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;
}
}
01/08/2016
I just went through a very strange situation, my device is the LENOVO VIBE A7010 and the Camera.open()
always from the Exception java.lang.RuntimeException: Fail to connect to câmera service
, I decided to get another device, one Moto G first generation and look what happened, the application worked perfectly, I do not know what the problem with Lenovo a7010, but lately I’m having a lot of headache with it when it comes to development, I spent a while trying to make it work in Android Studio.
Instead of adding answers that don’t answer the question, click edit link. Otherwise this place will end up a mess.
– Victor Stafusa
Try to open your camera normally on the device by clicking on the camera icon. Probably won’t be opening, this is an Android bug. Restart the device solves.
– Leonardo Dias
@Victorstafusa you’re right, went unnoticed by me.
– Vinithius
Which android version did you test? Android M?
– Marcelo López
That’s right, version 6.0
– Vinithius
If the error only occurs in version 6 or higher, the problem may be a lack of permissions. See this reply
– ramaral
The problem was permission from Android M, thank you @ramaral I will put my solution....
– Vinithius