我正在创建将用作后台服务的应用程序,并将定期从前置摄像头拍摄图像而无需预览,并且应用程序必须保持后台。我在一个论坛中找到了来源。人们说代码是有效的,但对我来说,这段代码不起作用。我不能拍照。
请帮我修复此代码。对不起我的英语=)
public class CamService extends Service {
private static final String TAG = "CameraDemo";
private final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
Camera camera;
ScheduledFuture<?> beeperHandle;
/* Service Life cycle Overrides */
@Override
public void onCreate() {
super.onCreate();
camera = Camera.open();
try {
camera.setPreviewDisplay(null);
} catch (IOException e) {
e.printStackTrace();
}
takePicsPeriodically(5);
}
@Override
public void onDestroy() {
stopPics();
super.onDestroy();
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
/* ----------------------------------- */
private IMyRemoteService.Stub myRemoteServiceStub = new IMyRemoteService.Stub() {
/* Basic Service Methods */
public boolean isCollecting() {
return (beeperHandle != null);
}
/* ------------------------- */
};
public void takePicsPeriodically(long period) {
final Runnable beeper = new Runnable() {
public void run()
{
camera.takePicture(shutterCallback,rawCallback,jpegCallback);
}
};
camera.startPreview();
beeperHandle = scheduler.scheduleAtFixedRate(beeper, period, period, TimeUnit.SECONDS);
}
public void stopPics() {
beeperHandle.cancel(true);
beeperHandle = null;
camera.stopPreview();
camera.release();
camera = null;
}
/* Camera Call backs */
ShutterCallback shutterCallback = new ShutterCallback() {
public void onShutter() {
Log.d(TAG, "onShutter'd");
}
};
/** Handles data for raw picture */
PictureCallback rawCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
Log.d(TAG, "onPictureTaken - raw");
}
};
/** Handles data for j peg picture */
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
FileOutputStream outStream = null;
try {
// write to local sand box file system
//outStream = CameraDemo.this.openFileOutput(String.format("%d.jpg", System.currentTimeMillis()), 0);
// Or write to s d card
outStream = new FileOutputStream(String.format("/sdcard/%d.jpg", System.currentTimeMillis()));
outStream.write(data);
outStream.close();
Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
Log.d(TAG, "onPictureTaken - jpeg");
}
};
}