我开发了一款可以在不预览用户的情况下拍摄照片的应用。我的问题是,在执行OnPictureTaken方法之前,有时候GC会清理Camera.takePicture()方法创建的对象。因此,当它发生时,应用程序无法保存该照片。
以下是拍摄照片的课程:
public class MyCamera implements Camera.PictureCallback {
private Camera mCamera;
private Context context;
public MyCamera(Context c_) {
Log.d(TAG, "On constructor");
context = c_;
if (Camera.getNumberOfCameras() >= 2) {
mCamera = Camera.open(CameraInfo.CAMERA_FACING_FRONT);
} else {
mCamera = Camera.open(CameraInfo.CAMERA_FACING_BACK);
}
}
public void takePicture() {
try {
Log.d(TAG, "On take picture");
mCamera.setPreviewTexture(new SurfaceTexture(0));
mCamera.startPreview();
Thread.sleep(1000);
Log.d(TAG, "About to take");
mCamera.takePicture(null, null, null, this);
Log.d(TAG, "Took it");
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void onPictureTaken(byte[] data, Camera camera) {
Log.d(TAG, "onPictureTaken");
File pictureFile = getOutputMediaFile(1);
if (pictureFile == null) {
Log.d(TAG, "Error creating picture file");
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (Exception e) {
Log.d(TAG, "Error writing picture");
e.printStackTrace();
}
finally {
mCamera.release();
}
}
我尝试将回调更改为全局变量,或者将其用作我的类的实现,但是没有一个能够顺利运行。
这是logCat:
06-08 15:46:48.554: D/MyAppService(1248): Capture camera this time
06-08 15:46:48.554: D/MyCamera(1248): On constructor
06-08 15:46:48.844: D/MyCamera(1248): On take picture
06-08 15:46:49.884: D/MyCamera(1248): About to take
06-08 15:46:49.884: D/MyCamera(1248): Took it
06-08 15:46:51.844: D/MyCamera(1248): onPictureTaken
06-08 15:46:51.854: D/DataReceive(1248): handling data
06-08 15:46:51.854: E/DataReceive(1248): Data handled
06-08 15:48:12.144: D/dalvikvm(1248): GC_FOR_ALLOC freed 479K, 3% free 17161K/17676K, paused 41ms, total 42ms
06-08 15:48:48.164: D/dalvikvm(1248): GC_EXPLICIT freed 104K, 3% free 17165K/17676K, paused 9ms+2ms, total 46ms
06-08 15:48:48.604: D/MyAppService(1248): Capture camera this time
06-08 15:48:48.604: D/MyCamera(1248): On constructor
06-08 15:48:48.884: D/MyCamera(1248): On take picture
06-08 15:48:49.914: D/MyCamera(1248): About to take
06-08 15:48:49.914: D/MyCamera(1248): Took it
06-08 15:48:51.884: D/dalvikvm(1248): GC_FOR_ALLOC freed 8K, 3% free 17163K/17676K, paused 16ms, total 16ms
06-08 15:48:52.634: I/dalvikvm-heap(1248): Grow heap (frag case) to 17.046MB for 266152-byte allocation
06-08 15:48:52.644: D/dalvikvm(1248): GC_FOR_ALLOC freed <1K, 3% free 17423K/17936K, paused 10ms, total 10ms
答案 0 :(得分:0)
我发现问题是我的方法(takePicture),它在onPictureTaken被调用之前被关闭了。我解决了将问题延迟到takePhoto方法的问题。