android studio 调用系统相机
时间: 2023-10-13 11:07:54 浏览: 85
1. 在AndroidManifest.xml文件中添加相机权限:
```
<uses-permission android:name="android.permission.CAMERA" />
```
2. 创建一个Intent对象,设置Action为MediaStore.ACTION_IMAGE_CAPTURE:
```
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
```
3. 创建一个File对象,用于保存拍摄的照片:
```
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
ex.printStackTrace();
}
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this, "com.your.package.name.fileprovider", photoFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
}
```
其中,createImageFile()方法用于创建一个临时文件来存储拍摄的照片:
```
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
```
注意,需要在AndroidManifest.xml文件中定义一个FileProvider:
```
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.your.package.name.fileprovider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
```
还需要在res/xml目录下创建一个file_paths.xml文件,用于指定临时文件存储的路径:
```
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-files-path name="my_images" path="Pictures" />
</paths>
```
4. 调用startActivityForResult()方法启动相机:
```
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
```
5. 在onActivityResult()方法中处理拍摄完成后的结果:
```
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
// Image captured and saved to fileUri specified in the Intent
Toast.makeText(this, "Image saved to file: " + mCurrentPhotoPath, Toast.LENGTH_SHORT).show();
// TODO: Do something with the image
}
}
```
阅读全文