1:调用摄像头拍照
布局文件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.we.MainActivity" >
<Button
android:id="@+id/tak_photo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Take Photo"
/>
<ImageView
android:id="@+id/pricture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
/>
</RelativeLayout>
java文件
public class MainActivity extends Activity {
public static final int TAKE_PHOT0=1;
private ImageView picture;
private Uri imageUri;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button takePhoto=(Button)findViewById(R.id.tak_photo);
picture=(ImageView)findViewById(R.id.pricture);
takePhoto.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
File outputImage=new File(getExternalCacheDir(),"output_image.jpg");
try {
if(outputImage.exists()) {
outputImage.delete();
}
outputImage.createNewFile();
}catch(IOException e) {
e.printStackTrace();
}
{
imageUri=Uri.fromFile(outputImage);
}
//启动相机程序
Intent intent=new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent,TAKE_PHOT0);
}
});
}
protected void onActivityResult(int requestCode,int resultCode,Intent data) {
switch(requestCode) {
case TAKE_PHOT0:
if(resultCode==RESULT_OK) {
try {
Bitmap bitmap=BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
picture.setImageBitmap(bitmap);
}catch(FileNotFoundException e) {
e.printStackTrace();
}
}
break;
default:
break;
}
}
}
权限声明:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>