借助Intent可以方便的调用Android系统的照相机程序,但是要声明摄像头的使用权限,在AndroidManifest.xml中添加下列代码:
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
完整示例代码如下:
package com.example.mycamerademo;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.provider.MediaStore;
public class MainActivity extends Activity {
private ImageView imageview;
private Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mycamerademo);
imageview=(ImageView) findViewById(R.id.imageView1);
btn=(Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
try{
//主要调用代码
Intent i=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, 1);
}
catch(Exception e){
Log.d("cameraDemo",e.toString());
}
}
});
}
protected void onActivityResult(int requestCode,int resultCode,Intent data){
try{
if(requestCode!=1){
return;
}
super.onActivityResult(requestCode, resultCode, data);
Bundle extras=data.getExtras();
Bitmap bitmap=(Bitmap) extras.get("data");
imageview.setImageBitmap(bitmap);
}catch(Exception e){
Log.d("cameraDemo",e.toString());
}
}
}
因为要回传拍摄的图像,所以调用了Activity.startActivityForResult(Intent intent,int requestCode)方法,启动的Activity正常结束时会自动返回发出请求的Activity,并且会返回对应的requestCode给onActivityResult(int requestCode,int resultCode,Intent data).