场景:
我有一个 Activity (A) 调用另一个 Activity (B) 来拍照并将 Byte[]
发送回“A”。
Activity B 有一个用于拍照的按钮:
public void onClick(View v) {
//get the current image from the camera
mCamera.takePicture(null, null, mPicture);
Intent data1 = new Intent();
data1.putExtra("byte_array",dataPic);
if (getParent() == null) {
setResult(Activity.RESULT_OK, data1);
} else {
getParent().setResult(Activity.RESULT_OK, data1);
}
finish();
}
这是我的 PictureCallback:
private Camera.PictureCallback mPicture = new Camera.PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null){
Log.d(TAG, "Error creating media file, check storage permissions: " +
"no exception written by a boss");
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
dataPic = data;
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
mCamera.stopPreview();
mCamera.release();
}
};
我用 startActivityForResult
启动了 Activity B,并在 Activity A 中实现了 onActivityResult
。
问题:
我调试了我的代码并注意到 onActivityResult
在 onPictureTaken
之前被调用。所以逻辑上 Byte[]
是 null :(
我还尝试将 onClick
函数中的代码添加到 onPictureTaken
函数中(当然没有 mCamera.takePicture
),
无济于事,仍然无效。
也许我没有看到真正明显的东西,但我就是找不到解决方案。我试着在这里寻找一个合适的问题,但找不到任何有用的东西。
问题:
有没有办法等待回调?或者也许另一种解决问题的方法?
边注:
请不要建议使用 Camera Intent。
最佳答案
I debugged through my code and noticed that onActivityResult gets called before onPictureTaken does. So logically the Byte[] is null
那是因为takePicture()
是异步的。
I also tried to add the code inside the onClick function to the onPictureTaken function (of course without the mCamera.takePicture), with no avail, still null.
嗯,关于处理异步问题,这个是正确的答案。但是,除非您选择较小的分辨率,否则您的 Intent
会太大,并且在尝试发回结果时应该会崩溃。
Is there a way to wait for the callback?
没有。
or maybe another approach of solving the problem?
关于“Intent
too large”的问题,不要有两个activity。进行一项 Activity ,使用两个 fragment 或某种类似的方法在两种状态之间更改您的 UI。
关于异步问题,将处理结果逻辑移至 onPictureTaken()
,在 mCamera.release()
之后。在此过程中,摆脱 dataPic
(因为您不再需要它)并使用 data
(传入的 byte[]
) .
关于android - 等待 Camera.PictureCallback,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35538448/