23

I am trying to use Zxing Library for developing a barcode scanner.

My activity is as follows:

public class Scanner extends Activity {  

    private static final String PACKAGE = "com.test.scan";  
    private static final String SCANNER = "com.google.zxing.client.android.SCAN";  
    private static final String SCAN_FORMATS = "UPC_A,UPC_E,EAN_8,EAN_13,CODE_39,CODE_93,CODE_128";  
    private static final String SCAN_MODE = "QR_CODE_MODE";  
    public static final int REQUEST_CODE = 1;  

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

        setContentView(R.layout.main);  

         Button ok;  
         ok = (Button) findViewById(R.id.b1);  
         ok.setOnClickListener(new View.OnClickListener() {  

             public void onClick(View v) {  

                Intent scanIntent = new Intent(SCANNER);  
                scanIntent.setPackage(PACKAGE);  
                scanIntent.addCategory(Intent.CATEGORY_DEFAULT);  
                scanIntent.putExtra("SCAN_FORMATS", SCAN_FORMATS);  
                scanIntent.putExtra("SCAN_MODE", SCAN_MODE);  
                try {  
                    startActivityForResult(scanIntent, REQUEST_CODE);  
                } catch (ActivityNotFoundException e) {  
                     // TODO: Exception handling  
                }  
            }  

        });  
     }

Also manifest file:

    <activity android:name=".Scanner"
            android:screenOrientation="landscape"   android:configChanges="orientation|keyboardHidden"
            android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
            android:windowSoftInputMode="stateAlwaysHidden">  
                 <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />  
            </intent-filter>

</activity>

<activity android:name="com.google.zxing.client.android.CaptureActivity"
                android:screenOrientation="landscape" android:configChanges="orientation|keyboardHidden"  
                android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
                android:windowSoftInputMode="stateAlwaysHidden">
                <intent-filter>
                    <action     android:name="com.google.zxing.client.android.SCAN" />
                    <category    android:name="android.intent.category.DEFAULT" />
                </intent-filter>
            </activity>
            <activity android:name="com.google.zxing.client.android.PreferencesActivity"
                android:label="@string/preferences_name">
            </activity>
            <activity android:name="com.google.zxing.client.android.HelpActivity"
                android:screenOrientation="user">
                <intent-filter>
                    <action android:name="android.intent.action.VIEW" />
                    <category android:name="android.intent.category.DEFAULT" />
                </intent-filter>
            </activity>
            <activity android:name="com.google.zxing.client.android.share.ShareActivity"
                android:label="@string/share_name" android:screenOrientation="user"
                android:theme="@android:style/Theme.Light">
                <intent-filter>
                    <action android:name="com.google.zxing.client.android.SHARE" />
                    <category android:name="android.intent.category.DEFAULT" />
                </intent-filter>
            </activity>
    <uses-permission android:name="android.permission.CAMERA"

But I am getting the following error:

"Sorry, the Android camera encountered a problem. You may need to restart the device".

I have followed few blogs.

Log:

   Unexpected error initializating camera  
    01-27 10:40:48.281: WARN/CaptureActivity(1007): java.lang.RuntimeException: Fail to connect to camera service  
    01-27 10:40:48.281: WARN/CaptureActivity(1007):     at android.hardware.Camera.native_setup(Native Method)  
    01-27 10:40:48.281: WARN/CaptureActivity(1007):     at android.hardware.Camera.<init>(Camera.java:185)  
    01-27 10:40:48.281: WARN/CaptureActivity(1007):     at android.hardware.Camera.open(Camera.java:165)
   01-27 10:40:48.281: WARN/CaptureActivity(1007):     at com.google.zxing.client.android.camera.CameraManager.openDriver(CameraManager.java:126)
    01-27 10:40:48.281: WARN/CaptureActivity(1007):     at com.google.zxing.client.android.CaptureActivity.initCamera(CaptureActivity.java:606)  
    01-27 10:40:48.281: WARN/CaptureActivity(1007):     at com.google.zxing.client.android.CaptureActivity.surfaceCreated(CaptureActivity.java:346)   
    01-27 10:40:48.281: WARN/CaptureActivity(1007):     at android.view.SurfaceView.updateWindow(SurfaceView.java:532)  
    01-27 10:40:48.281: WARN/CaptureActivity(1007):     at android.view.SurfaceView.dispatchDraw(SurfaceView.java:339) 
Siddharth
  • 9,349
  • 16
  • 86
  • 148
Smitha
  • 6,110
  • 24
  • 90
  • 161

11 Answers11

37

For Android 6+, because of the "permission" issue, If you got the message "Sorry, the camera encountered a problem. You may need to restart the device.", go to Settings - Apps - find "your app name" - select Permissions and switch on "Camera".

1nteger
  • 839
  • 9
  • 15
  • This unstuck me, thanks! But what is "the permission issue"? – Deleplace Jun 05 '16 at 19:36
  • 2
    Apps designed for Android 6.0 will now ask for a permission when they need it. For example, instead of giving an app access to your camera when you install it, you’ll be prompted the first time the app wants to access your camera. – 1nteger Jun 06 '16 at 05:02
  • This is only true if the app targets Android 6+. – Sean Owen Jun 27 '16 at 08:40
16

permission of camera

<uses-permission android:name="android.permission.CAMERA"

is not at proper place. it should be after application tag.

7

This means the device returned null from Camera.open() and it shouldn't ever do that. It's treated as a device bug. I am not sure how you would debug why it is doing this, but that's the cause.

The only time I have seen this happen consistently is on Android 2.2 devices that have a front camera, only. The API for accessing a front camera only appeared in Android 2.3, and the previous Camera.open() API method may only return a rear-facing camera. So these return null. And it is a device bug, really, since they really need to be running Android 2.3 to let apps use a front camera.

Sean Owen
  • 66,182
  • 23
  • 141
  • 173
  • Yes, it supports 1.5 even. 4.0 will requires 2.1. – Sean Owen Jan 30 '12 at 12:39
  • @SeanOwen in my case I have a Samsung Galaxy S (Android 2.3.6) which has a front and rear camera and I get this warning when I try go use the barcode scanner. Is there a way around it? I'm using the latest version of BarcodeScanner. Downloaded it 2 days ago. Thank you. – Edison Santos Sep 12 '13 at 08:56
  • It can't make the firmware behave, no. If it returns null it returns null. It's not a function of the app. – Sean Owen Sep 12 '13 at 09:11
  • @ConnectinglifewithAndroid did you solved this issue. Im also getting this while using the front camera – Qadir Hussain Oct 01 '13 at 13:02
  • Here the issue was the place of camera permission.there can be many reason. you can find it by your own.also ensure that its not device bug. – Connecting life with Android Oct 02 '13 at 18:54
  • No, that's not correct. Without permission, you get a different failure. – Sean Owen Feb 17 '14 at 11:11
  • I m having same issue like this"https://code.google.com/p/zxing/issues/detail?id=1648" Error occur when i try to scan 5th time. Any one got the solution for this bug please share with all. I m getting this error in samsung tab pro 12.2 – Rhn Bhadani May 30 '14 at 10:10
  • @SeanOwen I guess somehow you are blocking the camera of the device(see if is possible to release it) because other apps(e.g. Camera app) are also unable to access the camera after this error occurs. I can't use the app anymore if I don't "force close" it. If I close my app the problem disappears. So, I'm pretty sure is a function of your app. I'm using Nexus 5 with Android 4.4.4 Cheers! – AlexAndro Sep 29 '14 at 11:36
  • No, definitely not. See the source code and onPause() method. Why would you assume it is not a driver bug? Apps can't disable the camera even if they wanted to. – Sean Owen Sep 29 '14 at 12:21
2

I faced a similar problem. While testing on Android M,the camera requires runtime permission. Adding this answer just for reference so as to help anyone who is stuck in a similar scenario.

johny kumar
  • 1,270
  • 2
  • 14
  • 24
2

I solved the issue on Android 8.1.0 with requesting permissions for the app via code.

The reason for that is (I think) due to changed policies in handling device access in newer Android versions you have to ask for permissions in your code. It is not enough to put the needed permissions in your XML. The user has to have the choice of denying access while using the app.

To activate the "give-permission-popup" you can use the following e.g. inside of onCreate of your MainActivity:

    if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA)
            == PackageManager.PERMISSION_DENIED) {
        ActivityCompat.requestPermissions(MainActivity.this, new String[] {Manifest.permission.CAMERA}, MY_CAMERA_REQUEST_CODE);
    }

It should have the same effect like activating permission via settings. But in an actual app, asking for permissions from inside of your app is probably more user friendly.

laka
  • 644
  • 8
  • 23
2

Just Add camera permission with Toast :

if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
              == PackageManager.PERMISSION_GRANTED) {
          // Permission is already available, start camera preview
          Toast.makeText(this,"camera permission granted",Toast.LENGTH_LONG).show();


      } else {
          // Permission is missing and must be requested.
          requestCameraPermission();
      }

and :

private void requestCameraPermission() {
        // Permission has not been granted and must be requested.
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.CAMERA)) {
            // Provide an additional rationale to the user if the permission was not granted
            // and the user would benefit from additional context for the use of the permission.
            // Display a SnackBar with cda button to request the missing permission.
            Toast.makeText(this, "Camera access is required to Scan The Barcode.",
                    Toast.LENGTH_LONG).show();


                    // Request the permission
                    ActivityCompat.requestPermissions(CaptureActivity.this,
                            new String[]{Manifest.permission.CAMERA},
                            PERMISSION_REQUEST_CAMERA);



        } else {
            Toast.makeText(this,
                    "<b>Camera could not be opened.</b>\\nThis occurs when the camera is not available (for example it is already in use) or if the system has denied access (for example when camera access has been disabled).", Toast.LENGTH_SHORT).show();
            // Request the permission. The result will be received in onRequestPermissionResult().
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA}, PERMISSION_REQUEST_CAMERA);
        }
    }
rizujikeda
  • 47
  • 6
0

It's possible that you have a Device Administrator disabling access to the camera. Should check if the android camera app can start up or if it complains of a device admin.

Sojurn
  • 475
  • 6
  • 15
0

I got the same problem Fixed it with

SurfaceHolder surfaceHolder = surfaceView.getHolder();
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

Note: this seems to be a recent issue with the OS ( pre V3.0 Android) as the code was previously working.

drmpf
  • 31
  • 1
-1

I was able to sort the issue out by simply placing the camera permissions in the main application.

Sylvain Defresne
  • 42,429
  • 12
  • 75
  • 85
-2

If you are invoking camera in android emulator for Android 2.2 it will give exception . While it runs fine on a device.

Relsell
  • 771
  • 6
  • 18
-2

Check out your code, I think your code trying to open camera multiple times. Download google zxing barcode scanner source code and then try it.

Suvam Roy
  • 1,282
  • 2
  • 11
  • 21