【发布时间】:2012-03-18 22:10:59
【问题描述】:
我尝试使用以下代码拍照并将照片的一些信息保存到数据库中。数据库部分已经过彻底测试,在所有其他情况下都可以正常工作。不幸的是,如果我取消注释下面的注释代码,我的代码就会超时。出于某种原因,如果this.camera.takePicture() 方法后面有代码,takePicture() 根本不会调用被覆盖的onPictureTaken 方法(它应该做的第一件事是打印出一行文本,但它没有'甚至不这样做)。如果后面没有代码,它可以正常工作。
在安装闩锁之前,我会收到一个错误,因为 ph.getPhoto() 正在返回 null(onPictureTaken() 尚未设置 ph 的 .photo 成员变量,因为它尚未被调用)。安装闩锁后,它会一直等到超时(或永远,如果没有指定超时值)。
谁能告诉我我错过了什么?
public void takePicture(View view) throws Exception {
CountDownLatch latch = new CountDownLatch(1);
System.out.println("Taking Photo!");
PhotoHandler photoHandler = new PhotoHandler(getApplicationContext(),latch);
this.camera.takePicture(null, null, photoHandler);
/* PhotoHandler has an overridden "onPictureTaken()" method which releases the latch as its final
* action; however, its first instruction is to print a confirmation that it has been accessed.
* Unfortunately, for some reason, onPictureTaken() is not called if the following code is
* uncommented; it deadlocks for the five seconds before timing out. However, with out the following,
* the camera.takePicture method invokes onPictureTaken() and it works just fine. */
// latch.await(5,TimeUnit.SECONDS);
// DatabaseHandler db = new DatabaseHandler(this);
// Photo p = photoHandler.getPhoto();
// db.addPhoto(p);
// List<Photo> photos = new ArrayList<Photo>();
// photos.add(p);
// this.addPhotosToMap(photos);
}
【问题讨论】:
标签: android multithreading concurrency camera deadlock