如何检查设备中是否安装了摄像头?

时间:2016-03-15 07:01:46

标签: android

这是我的代码。我想从相机或图库中选择一张图片。 为此,我必须检查设备的相机支持功能。

  public void selectImage() {
            final String[] items = new String[]{"Camera", "Gallery"};
            final Integer[] icons = new Integer[]{R.drawable.ic_camera, R.drawable.ic_gallery};
            ListAdapter adapter = new ArrayAdapterWithIcon(getActivity(), items, icons);
            new AlertDialog.Builder(getActivity()).setTitle("Select Picture")
                    .setAdapter(adapter, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int item) {
                            if (items[item].equals("Camera")) {
                                if (//here i want to check is there mobile exists camera or not) {
                                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                    startActivityForResult(intent, REQUEST_CAMERA);
                                } 
                            } else if (items[item].equals("Gallery")) {

                                    Intent intent = new Intent();
                                    intent.setType("image/*");
                                    intent.setAction(Intent.ACTION_GET_CONTENT);
                                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                                    startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);

                            }
                        }
                    }).show();

        }

我已经尝试了很多但没有成功。

2 个答案:

答案 0 :(得分:4)

import android.hardware.Camera;`

使用Camera.getNumberOfCameras();。如果返回值大于 0 ,则表示您的设备配有相机。

答案 1 :(得分:1)

使用此功能显示图库以从中选择图像:

private void showGallery() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    startActivityForResult(intent, 1234);
}

用它打开相机(检查设备是否有相机):

private void showCamera() {
        // get the package manager and check if device has camera
        PackageManager pm = getPackageManager();
        if (pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

            // ensure that there is some activity to handle camera intents
            if (takePictureIntent.resolveActivity(pm) != null) {
                startActivityForResult(takePictureIntent, 5678);
            }
        } else {
            Snackbar.make(mView, "your device dont have camera", Snackbar.LENGTH_LONG).show();
        }
    }

注意:请确保在清单中声明Camera的权限为:

<manifest ... >
    <uses-feature android:name="android.hardware.camera"
                  android:required="true" />
    ...
</manifest>

有关详细信息,请查看this输出。