我正在编写一个应用程序,其中一个关键功能是拍照并将其写入文件,然后将该照片读入 base64 数组(只需单击一个按钮)。问题是当我启动 onclick 拍照时,它会在 onPhotoTaken() 函数接收到图像并将其写入指定的存储目录之前从该函数返回。
我在代码的几个阶段添加了日志输出,很明显 onclick takePhoto 函数在它调用的 onPhotoTaken() 函数完成之前退出。
android 文档指出,您需要等待 JpegCallback 完成返回,然后才能重新启动预览,但我无法让它等待写入完成。
代码:
public static void takePhoto(){
fCamera.takePicture(null, null, jpegCallback);
Log.d("capture", "photo was captured");
// Set the image callback
Log.d("this one is", "being called");
}
static PictureCallback jpegCallback = new Camera.PictureCallback() {
// Function for handling the picture
public void onPictureTaken(byte[] data, Camera fCamera){
//fCamera.stopPreview();
Log.d("is this", "not being called ??? probably");
File imagePath;
FileOutputStream out = null;
// create the filename with extension
String fileName = "IMAGE_1.bmp";
// Create / Find the storage Directory for our pictures
//storageDir = context.getDir("imageDir", Context.MODE_PRIVATE);
// Create it if it doesn't exist
// Create the image file
imagePath = new File(storageDir, fileName);
String finalPath = imagePath.getAbsolutePath();
Log.d("location", finalPath);
if (!imagePath.exists()) {
if (!imagePath.mkdirs())
Log.d("@string/app_name", "Failed to create File");
return;
}
try {
out = new FileOutputStream(imagePath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//finalImage.compress(CompressFormat.PNG, 100, out);
try {
out.write(data);
Log.d("write", "photo was written");
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
};
日志猫:
10-13 12:55:39.185: D/capture(7126): photo was captured
10-13 12:55:39.185: D/this one is(7126): being called
这些是唯一发生的日志输出。