概述
使用Camera有兩種方式:通過Intent使用已有的app和通過Camera構建自己的app。
Camera相關聲明
如果你的應用程式要使用Camera,則必須獲得使用許可,需要在AndroidManifest.xml中加入如下聲明。
<uses-permissionandroid:name="android.permission.CAMERA" />
如果你的應用程式必須有Camera才能使用,則聲明如下:
<uses-featureandroid:name="android.hardware.camera" />
否則應聲明如下:
<uses-featureandroid:name="android.hardware.camera"android:required="false" />
其他相關聲明:
儲存:<uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE" />
語音:<uses-permissionandroid:name="android.permission.RECORD_AUDIO" />
位置:<uses-permissionandroid:name="android.permission.ACCESS_FINE_LOCATION" />
核心類
Itent:通過它進行Camera編程更簡單。
Camera:通過它可以控制相機,構建功能更強大的Camera應用。
SurfaceView:提供即時預覽功能。
通過Itent來實現拍照
第一步:在Eclipse中建立一個名為Photo的Android工程,可參見Hello world的例子;
第二步:在AndroidManifest.xml中添加使用Camera相關的聲明如下:
<uses-permissionandroid:name="android.permission.CAMERA"/>
第三步:編寫MainActivity類。
(1) 新增成員變數
(2) 修改OnCreate方法
(3) 增加onActivityResult方法
(4) 新增兩個輔助方法
類的原始碼如下:
[java]
public class MainActivity extends Activity {
private static final int MEDIA_TYPE_IMAGE = 1;
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
private Intent intent = null;
private Uri fileUri = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//create a intent to take picture
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
// start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// Image captured and saved to fileUri specified in the Intent
Toast.makeText(this, "Image saved to:\n" +
data.getData(),
Toast.LENGTH_LONG).show();
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the image capture
} else {
// Image capture failed, advise user
}
}
}
/** Create a file Uri for saving an image or video */
private static Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile = null;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
}
return mediaFile;
}
}
public class MainActivity extends Activity {
private static final int MEDIA_TYPE_IMAGE = 1;
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
private Intent intent = null;
private Uri fileUri = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//create a intent to take picture
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
// start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// Image captured and saved to fileUri specified in the Intent
Toast.makeText(this, "Image saved to:\n" +
data.getData(),
Toast.LENGTH_LONG).show();
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the image capture
} else {
// Image capture failed, advise user
}
}
}
/** Create a file Uri for saving an image or video */
private static Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile = null;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
}
return mediaFile;
}
}
第四步:運行程式。
如果拍完照返回的時候,程式崩潰,查看日誌出現如下錯誤:
java.lang.RuntimeException: Failure delivering resultResultInfo{who=null, request=100, result=-1, data=null} to activity
在AndroidManifest.xml中的activity元素加入android:launchMode="singleInstance"屬性即可解決該問題。
拍完照之後,可以在SD卡中的Pictures/MyCameraApp目錄下找到儲存的照片。