android 调用相机拍照
时间: 2023-10-11 15:07:00 浏览: 112
在 Android 平台上调用相机拍照可以通过使用 Camera API 或者更现代的 Camera2 API 来实现。下面是一个简单的示例代码,演示如何使用 Camera API 来调用相机拍照:
首先,在 AndroidManifest.xml 文件中添加相机权限:
```xml
<uses-permission android:name="android.permission.CAMERA" />
```
然后,在你的活动(Activity)中,添加以下代码:
```java
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_CAMERA_PERMISSION = 200;
private static final int REQUEST_IMAGE_CAPTURE = 1;
private Button captureButton;
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
captureButton = findViewById(R.id.capture_button); imageView = findViewById(R.id.image_view);
captureButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CAMERA},
REQUEST_CAMERA_PERMISSION);
} else {
openCamera();
}
}
});
}
private void openCamera() {
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) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
imageView.setImageBitmap(imageBitmap);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == REQUEST_CAMERA_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openCamera();
}
}
}
}
```
上述代码中,我们首先检查相机权限是否已经被授予,如果没有,则请求相机权限。然后,当用户点击拍照按钮时,我们打开相机应用,并在拍照完成后将结果显示在 ImageView 中。
请注意,上述代码仅涵盖了基本的相机调用和权限请求,实际开发中可能还需要处理其他方面的逻辑和错误情况。此外,由于 Android 平台的版本差异,还可能需要根据目标设备的版本进行适当的调整。希望这个示例能帮助到你!
阅读全文