3

Im trying to build a camera app (Im pretty new at this) When I run the application on real device its gives me this Error:

    05-26 13:16:37.504 14076-14076/involved.pose9 E/AndroidRuntime: FATAL EXCEPTION: main
                                                            Process: involved.pose9, PID: 14076
                                                            java.lang.RuntimeException: Fail to connect to camera service
                                                                at android.hardware.Camera.<init>(Camera.java:511)
                                                                at android.hardware.Camera.open(Camera.java:368)
                                                                at involved.pose9.CameraActivity.surfaceCreated(CameraActivity.java:63)
                                                                at android.view.SurfaceView.updateWindow(SurfaceView.java:582)
                                                                at android.view.SurfaceView$3.onPreDraw(SurfaceView.java:177)
                                                                at android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:944)
                                                                at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2067)
                                                                at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1119)
                                                                at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6060)
                                                                at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
                                                                at android.view.Choreographer.doCallbacks(Choreographer.java:670)
                                                                at android.view.Choreographer.doFrame(Choreographer.java:606)
                                                                at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
                                                                at android.os.Handler.handleCallback(Handler.java:746)
                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                at android.os.Looper.loop(Looper.java:148)
                                                                at android.app.ActivityThread.main(ActivityThread.java:5443)
                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)

This is my Class

    import android.graphics.PixelFormat;
    import android.hardware.Camera;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.SurfaceHolder;
    import android.view.SurfaceView;
    import android.view.Window;
    import android.view.WindowManager;

    import java.io.IOException;

    public class CameraActivity extends AppCompatActivity implements SurfaceHolder.Callback {

SurfaceHolder mSurfaceHolder;
SurfaceView mSurfaceView;
public Camera mCamera;
boolean mPreviewRunning;

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


    getWindow().setFormat(PixelFormat.TRANSLUCENT);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_camera);
    mSurfaceView = (SurfaceView) findViewById(R.id.surface_camera);
    mSurfaceHolder = mSurfaceView.getHolder();
    mSurfaceHolder.addCallback(this);
    mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}

@Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
    // TODO Auto-generated method stub


    if (mPreviewRunning) {
        mCamera.stopPreview();
    }
    Camera.Parameters p = mCamera.getParameters();
    //p.setPreviewSize(w, h);
    mCamera.setParameters(p);
    try {
        mCamera.setPreviewDisplay(arg0);
    } catch (IOException e) {
        e.printStackTrace();
    }
    mCamera.startPreview();
    mPreviewRunning = true;
}

@Override
public void surfaceCreated(SurfaceHolder holder) {
    // TODO Auto-generated method stub
    mCamera = Camera.open();
}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {
    // TODO Auto-generated method stub
    mCamera.stopPreview();
    mPreviewRunning = false;
    mCamera.release();
}

Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() {
    public void onPictureTaken(byte[] imageData, Camera c) {
    }
};
}

What is wrong here? Thanks in advance..

I also declare permissions in manifest.xml

    <uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.Camera" />
<uses-feature android:name="android.hardware." />
Allie Fly
  • 55
  • 1
  • 8
  • 2
    For marshamllow you need RunTimePermission please refer this https://developer.android.com/training/permissions/requesting.html – Abhishek Patel May 26 '16 at 10:27
  • @AbhishekPatel wouldn't the exception be different if that was the case? Though you're right, in M you need to check for permissions. Given the log I'm not sure this is the case though. – RominaV May 26 '16 at 10:32
  • @Allie if its permission problem you are going to get this error. You will not be able to access camera and asking permission in manifest will not work :) – Preethi Rao May 26 '16 at 10:35
  • 2
    Possible duplicate of [Android Marshmallow : java.lang.RuntimeException: Fail to connect to camera service](http://stackoverflow.com/questions/35172397/android-marshmallow-java-lang-runtimeexception-fail-to-connect-to-camera-serv) – RominaV May 26 '16 at 10:35
  • So what should I do? I have read the Link mr Patel send me but I dont understand what to do.. Thanks for quick response and sorry for beeing noob... – Allie Fly May 26 '16 at 10:37
  • see my answer here : http://stackoverflow.com/a/37269354/6127411 – Janki Gadhiya May 26 '16 at 10:49

3 Answers3

7

You need to give android.hardware.Camera permission programmatically.

MANIFEST PERMISSIONS WON'T WORK on Android 6

With marshmallow(newest version of Android). We have got some restrictions in Using Sensitive permissions like : Storage,Contacts access, etc..In edition to give these permissions in manifest, We need to request them from users at Runtime.

For more details refer this : Android M permissions

Add this code in your activity :

@Override
protected void onStart() {
    super.onStart();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

        int hasCameraPermission = checkSelfPermission(Manifest.permission.CAMERA);

        List<String> permissions = new ArrayList<String>();

        if (hasCameraPermission != PackageManager.PERMISSION_GRANTED) {
            permissions.add(Manifest.permission.CAMERA);

        } 
        if (!permissions.isEmpty()) {
            requestPermissions(permissions.toArray(new String[permissions.size()]), 111);
        }
    }


}

Add this after onActivityResult :

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    switch (requestCode) {
        case 111: {
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                    System.out.println("Permissions --> " + "Permission Granted: " + permissions[i]);


                } else if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                    System.out.println("Permissions --> " + "Permission Denied: " + permissions[i]);

                }
            }
        }
        break;
        default: {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
}
Janki Gadhiya
  • 4,492
  • 2
  • 29
  • 59
1

In marshmellow onwards the OS permisson are supposed to be taken at runtime. The camera permission also has to be take at run time Please check the below link to see how to ask permission at runtime. https://developer.android.com/training/permissions/requesting.html

Quick Solution : This is a fix but you can use for current marshmellow version Try adding this in your build.gradle file

targetSdkVersion 22
Preethi Rao
  • 5,117
  • 1
  • 16
  • 29
  • This worked but it wont run at Marshmallow devices.. Thanks though.. :) – Allie Fly May 26 '16 at 10:42
  • Wont run in the sense app doesnt launch in marshmellow ? – Preethi Rao May 26 '16 at 10:43
  • 1
    @AllieFly it will run in marshmallow. But by default all the permissions will be granted. better to handle the permissions at runtime rather than making the targetSdk version lower to 23 – droidev Dec 21 '16 at 16:22
1

on Marshmallow you have to ask user for grant permission at run time something like this

int permissionCheck = ContextCompat.checkSelfPermission(thisActivity,
        Manifest.permission.WRITE_CALENDAR);

if(permissionCheck == PackageManager.PERMISSION_GRANTED){
//user granted you
}else{
//the user denied your permission
}
Moh'd Awad
  • 1,758
  • 1
  • 12
  • 22
  • But this is for calendar. What permission is for camera and where should I write this? Also should I delete manifest permissions? – Allie Fly May 26 '16 at 10:51
  • no you have to keep the manifest permission , yes just edit the code and replace CALENDAR with CAMERA permisison – Moh'd Awad May 26 '16 at 11:03