Android 开发相机示例
时间: 2024-10-08 15:14:14 浏览: 34
Android 相机示例
在Android开发中,使用Camera API获取和处理照片或实时视频流是一个常见的任务。这里提供一个简单的相机拍照示例,假设你已经设置了Activity的权限并配置了`ACTION_IMAGE_CAPTURE`:
首先,在AndroidManifest.xml中添加相机拍摄权限:
```xml
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" android:required="true" />
```
然后,在Activity中初始化相机:
```java
import android.content.Intent;
import android.media.MediaScannerConnection;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class CameraActivity extends AppCompatActivity {
private Button takePictureButton;
private Camera camera;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
takePictureButton = findViewById(R.id.take_picture_button);
takePictureButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
takePicture();
}
});
}
private void takePicture() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
saveImage(imageBitmap);
}
}
private void saveImage(Bitmap bitmap) {
// ... 将图片保存至相册或本地路径
MediaScannerConnection.scanFile(this, new String[]{bitmap.toString()}, null, new MediaScannerConnection.OnScanCompletedListener() {
@Override
public void onScanCompleted(String path, Uri uri) {
// 图片扫描完成后,更新UI或做其他处理
}
});
}
// 等待用户关闭相机后停止
@Override
protected void onPause() {
super.onPause();
if (camera != null) {
camera.stopPreview();
camera.release();
camera = null;
}
}
// ... 其他方法...
}
```
在这个例子中,当用户点击按钮时会触发拍照请求,照片被保存后会自动进行媒体扫描以便添加到设备的照片库。
阅读全文