写一段时间静默拍照的代码
时间: 2023-09-27 09:06:53 浏览: 137
以下是一个简单的时间静默拍照的 Android 代码示例:
```java
private static final int REQUEST_IMAGE_CAPTURE = 1;
private static final int INTERVAL = 5000; // 5 seconds
private Handler handler;
private Runnable runnable;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create a handler and runnable to take pictures periodically
handler = new Handler();
runnable = new Runnable() {
@Override
public void run() {
takePicture();
handler.postDelayed(this, INTERVAL);
}
};
}
@Override
protected void onResume() {
super.onResume();
// Start taking pictures when the app is resumed
handler.postDelayed(runnable, INTERVAL);
}
@Override
protected void onPause() {
super.onPause();
// Stop taking pictures when the app is paused
handler.removeCallbacks(runnable);
}
private void takePicture() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
// Get the image data from the intent and save it to a file
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
String fileName = "image_" + System.currentTimeMillis() + ".jpg";
File file = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), fileName);
try {
FileOutputStream fos = new FileOutputStream(file);
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
该代码使用 Handler 和 Runnable 来定期调用 takePicture() 方法拍照。在 takePicture() 方法中,我们使用 Android 系统相机应用程序来拍摄照片,然后将照片数据保存到文件中。在 onActivityResult() 方法中,我们获取从相机应用程序返回的照片数据,并将其保存到文件中。
请注意,此代码需要您在应用程序的 AndroidManifest.xml 文件中声明相机权限。在 Manifest 文件中添加以下行:
```xml
<uses-permission android:name="android.permission.CAMERA" />
```
此外,为了确保照片数据可以保存到文件中,您还需要声明外部存储读取和写入权限。在 Manifest 文件中添加以下行:
```xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
```
阅读全文