android获取设备上的摄像头数量

时间:2014-01-08 00:38:07

标签: android android-camera

在尝试计算相机数量时,我遇到了一个奇怪的错误。

错误是:

  

“调用需要API级别9(当前最小值为5):android.hardware.Camera #getNumberOfCameras”

package com.example.cam_test2;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.view.Menu;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MainActivity extends Activity {

@Override
  protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
 checkCameraHardware(getApplicationContext());
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

/** Check if this device has a camera */
private boolean checkCameraHardware(Context context) {
    if   (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
        // this device has a camera
        LinearLayout lView = new LinearLayout(this);

        TextView myText = new TextView(this);

        myText.setText("yes");

        lView.addView(myText);

        setContentView(lView);
        return true;
    } else {
        // no camera on this device
        LinearLayout lView = new LinearLayout(this);

        TextView myText = new TextView(this);
        myText.setText("no");

        lView.addView(myText);

        setContentView(lView);

        return false;
    }
}

/** A safe way to get an instance of the Camera object. */
public static Camera getCameraInstance(){
    int camNum;
    camNum=Camera.getNumberOfCameras() ;///////error here///////////

    TextView myTextView = null;
    myTextView.setText("There are " + camNum+" cameras availabe");

    Camera c = null;
    try {
        c = Camera.open(); // attempt to get a Camera instance
    }
    catch (Exception e){
        // Camera is not available (in use or does not exist)
    }
    return c; // returns null if camera is unavailable
}
}

2 个答案:

答案 0 :(得分:1)

您需要获得在AndroidManifest文件中使用相机的许可。

将其放在<manifest>

的根目录中
<uses-permission android:name="android.permission.CAMERA"/>

您还需要确保指定了正确的最低API级别。此类是在API级别9中引入的,因此您需要指定9或更高级别作为最低API级别:

<uses-sdk android:minSdkVersion="9"/>

答案 1 :(得分:0)

如果您可以发布您的Manifest文件会有所帮助,但我认为您需要提高minSdkVersion。

<uses-sdk android:minSdkVersion="10" />