0

我正在将相机用于条形码扫描仪应用程序,并且在某些设备(LG G Flex、华硕 Nexus 7)上得到:Android 运行时异常 - 无法连接相机服务。这是下面的清单文件的片段:

`uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"
uses-permission android:name="android.permission.CAMERA"
....`

我在暂停、停止和销毁时释放相机。

    /** 
* Restarts the camera. 
*/ 
@Override 
protected void onResume() { 
super.onResume(); 
try { 
startCameraSource(); 
} catch (Exception e) { 
e.printStackTrace();

    }
}

/**
 * Stops the camera.
 */
@Override
protected void onPause() {
    super.onPause();
    if (mPreview != null) {
        mPreview.stop();
    }
}

/**
 * Releases the resources associated with the camera source, the associated detectors, and the
 * rest of the processing pipeline.
 */
@Override
protected void onDestroy() {
    super.onDestroy();
    if (mPreview != null) {
        mPreview.release();
    }

}

仍然超出运行时异常,并且我没有以上两个设备,因此我可以重现。有没有解决这个问题的办法?

4

1 回答 1

0

您好,您需要在清单文件中添加以下权限

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

如果您使用的是Android M权限模型,您首先需要在运行时检查应用程序是否具有此权限,并且必须在运行时提示用户提供此权限。您在清单上定义的权限不会在安装时自动授予。

 if (checkSelfPermission(Manifest.permission.CAMERA)
    != PackageManager.PERMISSION_GRANTED) {

requestPermissions(new String[]{Manifest.permission.CAMERA},
        MY_REQUEST_CODE);
}

您将需要对对话结果进行回调:

@Override
public void onRequestPermissionResult(int requestCode, String[] permissions,      int[] grantResults) {
if (requestCode == MY_REQUEST__CODE) {
    if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        // Now user should be able to use camera
    }
    else {
        // Your app will not have this permission. Turn off all functions 
        // that require this permission or it will force close like your 
        // original question
    }
}
}
于 2016-10-17T09:16:12.157 回答