gpt4 book ai didi

Android Camera takePicture函数不调用Callback函数

转载 作者:塔克拉玛干 更新时间:2023-11-02 18:52:37 25 4
gpt4 key购买 nike

我正在为我的应用程序开发自定义相机 Activity 。我正在按照此处 Android 开发者网站的说明进行操作: http://developer.android.com/guide/topics/media/camera.html一切似乎都正常,只是没有调用回调函数并且没有保存图片。这是我的代码:

public class CameraActivity extends Activity {
private Camera mCamera;
private CameraPreview mPreview;
private static final String TAG = "CameraActivity";

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);

// Create an instance of Camera
mCamera = getCameraInstance();

// Create our Preview view and set it as the content of our activity.
mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mPreview);

Button captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.v(TAG, "will now take picture");
mCamera.takePicture(null, null, mPicture);
Log.v(TAG, "will now release camera");
mCamera.release();
Log.v(TAG, "will now call finish()");
finish();
}
});
}

private PictureCallback mPicture = new PictureCallback() {

@Override
public void onPictureTaken(byte[] data, Camera camera) {
Log.v(TAG, "Getting output media file");
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.v(TAG, "Error creating output file");
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.v(TAG, e.getMessage());
} catch (IOException e) {
Log.v(TAG, e.getMessage());
}
}
};

private static File getOutputMediaFile() {
String state = Environment.getExternalStorageState();
if (!state.equals(Environment.MEDIA_MOUNTED)) {
return null;
}
else {
File folder_gui = new File(Environment.getExternalStorageDirectory() + File.separator + "GUI");
if (!folder_gui.exists()) {
Log.v(TAG, "Creating folder: " + folder_gui.getAbsolutePath());
folder_gui.mkdirs();
}
File outFile = new File(folder_gui, "temp.jpg");
Log.v(TAG, "Returnng file: " + outFile.getAbsolutePath());
return outFile;
}
}

单击按钮后,我得到日志:“现在将拍照”、“现在将释放相机”和“现在将调用完成”。 Activity 成功完成,但回调函数未在

mCamera.takePicture(null, null, mPicture);

函数(没有来自 mPicture 回调或 getMediaOutputFile 函数的日志)并且在指定的位置没有文件。

有什么想法吗? :)非常感谢!

最佳答案

mCamera.takePicture() 的调用是异步的。这意味着调用会立即完成,但实际的拍照和处理会在稍后发生。但是,您在从 mCamera.takePicture() 调用返回后立即执行此操作:

Log.v(TAG, "will now release camera");
mCamera.release();
Log.v(TAG, "will now call finish()");
finish();

这意味着在相机有机会实际拍照并给您回电之前,您已经释放了相机资源并完成了 Activity。

您需要将该代码移动到回调方法 onPictureTaken() 中,以便在回调发生后释放资源并完成 Activity。

关于Android Camera takePicture函数不调用Callback函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19687324/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com