- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
Android 相机无法打开。发生值为 4 的 stateCallBack onError。问题是相机之前工作得很好,当我在几个小时后尝试使用它时,发生了错误。
我尝试更新 android studio 和 gradle,重新运行脚本并重新打开相机,但仍然没有成功。
public class CustomCamActivity extends AppCompatActivity {
private static final String TAG = "CustomCamActivity";
private Button takePictureButton;
private TextureView textureView;
int rotation;
private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
static {
ORIENTATIONS.append(Surface.ROTATION_0, 90);
ORIENTATIONS.append(Surface.ROTATION_90, 0);
ORIENTATIONS.append(Surface.ROTATION_180, 270);
ORIENTATIONS.append(Surface.ROTATION_270, 180);
}
private String cameraId;
protected CameraDevice cameraDevice;
protected CameraCaptureSession cameraCaptureSessions;
protected CaptureRequest.Builder captureRequestBuilder;
private Size imageDimension;
private static final int REQUEST_CAMERA_PERMISSION = 200;
private Handler mBackgroundHandler;
private HandlerThread mBackgroundThread;
@SuppressLint("UseSparseArrays")
private HashMap<Integer, HashMap<byte[], Integer>> images_map = new HashMap<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e(TAG, "onCreate");
setContentView(R.layout.activity_custom_cam);
textureView = findViewById(R.id.texture);
textureView.setSurfaceTextureListener(textureListener);
takePictureButton = findViewById(R.id.btn_takepicture);
takePictureButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
takePicture();
}
});
Log.e(TAG, "onCreate X");
}
TextureView.SurfaceTextureListener textureListener = new TextureView.SurfaceTextureListener() {
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
//open your camera here
openCamera();
}
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
// Transform you image captured size according to the surface width and height
} // check on this method
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
return false;
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
}
};
private final CameraDevice.StateCallback stateCallback = new CameraDevice.StateCallback() {
@Override
public void onOpened(CameraDevice camera) {
Log.e(TAG, "onOpened");
cameraDevice = camera;
createCameraPreview();
}
@Override
public void onDisconnected(CameraDevice camera) {
cameraDevice.close();
}
@Override
public void onError(CameraDevice camera, int error) {
Log.e(TAG, "onError - " + error);
closeCamera();
}
};
protected void startBackgroundThread() {
Log.e(TAG, "startBackgroundThread");
mBackgroundThread = new HandlerThread("Camera Background");
mBackgroundThread.start();
mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
}
protected void stopBackgroundThread() {
Log.e(TAG, "stopBackgroundThread");
mBackgroundThread.quitSafely();
try {
mBackgroundThread.join();
mBackgroundThread = null;
mBackgroundHandler = null;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
protected void takePicture() {
if(null == cameraDevice) {
Log.e(TAG, "cameraDevice is null");
return;
}
CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraDevice.getId());
Size[] jpegSizes = null;
if (characteristics != null) {
jpegSizes = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP).getOutputSizes(ImageFormat.JPEG);
}
int width = 640;
int height = 480;
if (jpegSizes != null && 0 < jpegSizes.length) {
width = jpegSizes[0].getWidth();
height = jpegSizes[0].getHeight();
}
ImageReader reader = ImageReader.newInstance(width, height, ImageFormat.JPEG, 1);
List<Surface> outputSurfaces = new ArrayList<Surface>(2);
outputSurfaces.add(reader.getSurface());
outputSurfaces.add(new Surface(textureView.getSurfaceTexture()));
final CaptureRequest.Builder captureBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
captureBuilder.addTarget(reader.getSurface());
captureBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
// Orientation
rotation = getWindowManager().getDefaultDisplay().getRotation();
captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, ORIENTATIONS.get(rotation));
ImageReader.OnImageAvailableListener readerListener = new ImageReader.OnImageAvailableListener() {
@Override
public void onImageAvailable(ImageReader reader) {
Image image = null;
try {
image = reader.acquireLatestImage();
ByteBuffer buffer = image.getPlanes()[0].getBuffer();
byte[] bytes = new byte[buffer.capacity()];
buffer.get(bytes);
save(bytes);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (image != null) {
image.close();
}
}
}
private void save(byte[] bytes) throws IOException {
OutputStream output = null;
try {
Log.i(TAG, "** Opening Captured Activity");
System.out.println(bytes.length);
System.out.println(Arrays.toString(bytes));
System.out.println("Rotation - " + rotation);
System.out.println("-------------------------------------------------------");
Intent capture = new Intent(CustomCamActivity.this, CapturedImgg.class);
capture.putExtra("img", bytes);
capture.putExtra("rotation", rotation);
closeCamera();
startActivity(capture);
} finally {
if (null != output) {
output.close();
}
}
}
};
reader.setOnImageAvailableListener(readerListener, mBackgroundHandler);
final CameraCaptureSession.CaptureCallback captureListener = new CameraCaptureSession.CaptureCallback() {
@Override
public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
super.onCaptureCompleted(session, request, result);
createCameraPreview();
}
};
cameraDevice.createCaptureSession(outputSurfaces, new CameraCaptureSession.StateCallback() {
@Override
public void onConfigured(CameraCaptureSession session) {
try {
session.capture(captureBuilder.build(), captureListener, mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
@Override
public void onConfigureFailed(CameraCaptureSession session) {
}
}, mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
protected void createCameraPreview() {
Log.e(TAG, "createCameraPreview");
try {
SurfaceTexture texture = textureView.getSurfaceTexture();
assert texture != null;
texture.setDefaultBufferSize(imageDimension.getWidth(), imageDimension.getHeight());
Surface surface = new Surface(texture);
captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
captureRequestBuilder.addTarget(surface);
cameraDevice.createCaptureSession(Arrays.asList(surface), new CameraCaptureSession.StateCallback(){
@Override
public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
if (null == cameraDevice) {
return;
}
cameraCaptureSessions = cameraCaptureSession;
updatePreview();
}
@Override
public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {
Toast.makeText(CustomCamActivity.this, "Configuration change", Toast.LENGTH_SHORT).show();
}
}, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void openCamera() {
CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
Log.e(TAG, "is camera open");
try {
cameraId = manager.getCameraIdList()[0];
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
assert map != null;
imageDimension = map.getOutputSizes(SurfaceTexture.class)[0];
// Add permission for camera and let user grant the permission
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(CustomCamActivity.this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CAMERA_PERMISSION);
return;
}
manager.openCamera(cameraId, stateCallback, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
Log.e(TAG, "openCamera X");
}
protected void updatePreview() {
if(null == cameraDevice) {
Log.e(TAG, "updatePreview error, return");
}
Log.e(TAG, "updatePreview");
captureRequestBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
try {
cameraCaptureSessions.setRepeatingRequest( captureRequestBuilder.build(), null, mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void closeCamera() {
if (null != cameraDevice) {
cameraDevice.close();
cameraDevice = null;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == REQUEST_CAMERA_PERMISSION) {
if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
// close the app
Toast.makeText(CustomCamActivity.this, "Sorry!!!, you can't use this app without granting permission", Toast.LENGTH_LONG).show();
finish();
}
}
}
@Override
protected void onResume() {
super.onResume();
Log.e(TAG, "onResume");
startBackgroundThread();
if (textureView.isAvailable()) {
openCamera();
} else {
textureView.setSurfaceTextureListener(textureListener);
}
}
@Override
protected void onPause() {
Log.e(TAG, "onPause");
//closeCamera();
stopBackgroundThread();
super.onPause();
}
}
我希望相机预览能够正确显示。
任何帮助都会很棒。
最佳答案
来自官方文档
An error code that can be reported by onError(CameraDevice, int) indicating that the camera device has encountered a fatal error. The camera device needs to be re-opened to be used again.
我猜你使用相机后没有正确关闭它!尝试重新启动您的手机,它应该可以工作
关于java - camera2 停止使用 CameraDevice.StateCallBack onError 值 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56533267/
在Elm中,我有一个简单的图像,我希望将其替换为一些“缺少”的onerror图像。因此,我添加了一个“onerror”属性: img [ src "broken-link.png" ,
我正在编写一个程序来使用 os.walk 遍历文件系统。 我的 for 循环使用 os.walk,onerror 函数如下: def walk_error(os_error): return(
这可能是一个非常明显的问题,但请解释一下 xhr 和 xhr.upload 之间的区别是什么? 我的用例是我正在将文件上传到服务器,但假设服务器出现故障。在这种情况下,我应该处理 xhr.onerro
我是 Flutter 的新手,我想了解我的错误处理程序有什么问题: import 'package:http/http.dart' as http; try { var response = aw
我的 VBA 中有以下示例代码。每当我遇到与系统相关的错误时,我想显示我自己的错误消息。但是下面的代码不起作用。 VBA 告诉 Type Mismatch 我想 Hello your date is
我的代码是这样的: function func1() { document.getElementById("img").src="pic.jpg"; ---stament2---
好吧,每当加载广告网络提供的图像时出现问题时,我都会尝试运行一些 JavaScript。 广告显示得很好,但我的脚本无论如何都会被调用。我是否以错误的方式处理这个问题? 代码: functi
我正在尝试控制背景是否可用。我看到到处都在使用 onerror,但不适合我。我有 bg 文件夹和 background1.jpg 到 background4.jpg 背景图片。对于前 4 个没有问题。
我在 Android 应用程序的 MainActivity 中编写了以下代码。当我运行以下代码时,它不会抛出任何异常并且 onError() 也不会被调用。但是我看到 onSuccess: testi
我有一张图片正在通过使用 javascript 更改图片的 src 进行更新。我添加了一个 error 事件监听器来测试图像是否损坏,如果是则重新加载图像。但如果它没有损坏,我想删除 error 事件
我需要在我的 TestCafe 测试中抑制错误(错误来自模拟页面)。示例代码: function stoperror() { try { thi
我有以下外部脚本标签(但 self 控制的 javascript 文件): 脚本并不重要,存在一个很好的后备方案。我想触发我的回退: 如果 test.js 不可用(这有效) 手动在 test.js
我有一个非常奇怪的情况,无法设法解决。 const handleImageError = e => { e.target.onerror = null; e.target.src =
我正在尝试让 onError 事件起作用,但到目前为止它只能在 Internet Explorer 9 中起作用。我已经尝试了几种代码,但基本上归结为: Internet Explorer 9: 成
当 src 中指定的其他图像不存在时,我试图显示默认图像,所以我这样做了: '; 问题是我仍然得到损坏的缩略图。奇怪的是:如果我切换 src,那么我将 assets/img/default-avata
鉴于以下情况: 为什么从未调用 Subscribe 中的 OnError 处理程序? var observable = Observable.Create( async (o, c) =>
ASP.NET (4.0) 中的 UserControls 继承自 System.Web.UI.UserControl。 VisualStudio 智能感知建议 OnError 作为 Template
在我的图像上,我设置了 onerror属性,以便在图像由于某种原因不可用的情况下使用占位符: 现在,它看起来像 onerror has been deprecated ,但我找不到任何关于处理错误的
我正在测试这段代码。 service.getProducts() .subscribeOn(Schedulers.io()) .observeOn(An
我正在考虑在我支持的应用程序中重新工作并简化我们的错误处理。我们目前的所有页面都继承自我们创建的基类,而该基类显然又继承自 System.Web.UI.Page。在这个基类中,OnError 方法当前
我是一名优秀的程序员,十分优秀!