1.调用摄像头拍照
新建一个CameraAlbumTest项目,然后修改activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/take_photo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Take Photo" />
<ImageView
android:id="@+id/picture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"/>
</LinearLayout>
可以看到布局中有两个控件,一个Button和一个ImageView.Button用于打开摄像头进行拍照,而ImageView用于将拍到的图片显示出来.
然后编写调用摄像头的具体逻辑,修改MainActivity代码:
public class MainActivity extends AppCompatActivity {
public static final int TAKE_PHOTO = 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.take_photo);
picture = (ImageView)findViewById(R.id.picture);
takePhoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//创建File对象,用于存储拍照后的图片
File outputImage = new File(getExternalCacheDir(), "output_image.jpg");
try {
if (outputImage.exists()){
outputImage.delete();
}
outputImage.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
if (Build.VERSION.SDK_INT >= 24){
imageUri = FileProvider.getUriForFile(MainActivity.this, "com.example.cameraalbumtest.fileprovider", outputImage);
} else {
imageUri = Uri.fromFile(outputImage);
}
//启动相机程序
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, TAKE_PHOTO);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode){
case TAKE_PHOTO:
if (resultCode == RESULT_OK){
try {
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
picture.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
break;
default:
break;
}
}
}
代码中分别获取到Button和ImageView的实例,并给Button注册点击响应事件,然后在点击事件中处理调用摄像头的逻辑.
首先创建一个File对象,用于存放摄像头拍下的照片,这里把图片命名为output_image.jpg,并将它存放在手机SD卡的应用关联缓存目录下,就是指SD卡中专门存放当前应用缓存数据的位置,调用getExternalCacheDir()方法可以得到这个目录,具体路径为/sdcard/Android/data/package name/cache.
为什么使用应用关联缓存目录来存放图片,因为从Android6.0系统开始,读写SD卡被列为危险权限,如果将图片存放在SD卡的任何其他目录,都要进行运行时权限处理才行,而使用应用关联目录则可以跳过这一步
接着会进行一个判断,如果运行的设备系统版本低于Android7.0,就调用Uri的fromFile()方法将File对象转换为Uri对象,这个Uri对象标识着output_image.jpg这张图片的本地真实路径,否则,就调用FileProvider的getUriForFile()方法将File对象转换成一个封装过的Uri对象,getUriForFile()方法接收三个参数,第一个参数是Context对象,第二个参数是任意唯一的字符串,第三个参数是File对象.
之所以进行这样一层转换,是因为从Android7.0系统开始,直接使用本地真实路径的Uri被认为是不安全的,会抛出一个FileNotFoundException异常,而FileProvider则是一种特殊的内容提供器,它使用了和内容提供器类似的机制来对数据进行保护,可以选择性的将封装过的Uri共享给外部,从而提高了应用的安全性.
接下来构建出一个Intent对象,并将这个Intent的action指定为android.media.action.IMAGE_CAPTURE,再调用Intent的putExtra()方法指定图片的输出地址,这里是Uri对象,最后调用startActivityForResult()来启动活动,由于我们使用的是一个隐式Intent,系统会找出能够响应这个Intent的活动去启动,这样照相机程序就被打开,拍下的照片会输出到output_image.jpg
刚才使用的startActivityForResult()来启动活动,因此拍照完成之后的结果会返回到onActivityResult()方法中,如果发现拍照成功,就可以调用BitmapFactory的decodeStream()方法将output_image,jpg这张照片解析成Bitmap对象,然后把它设置到ImageView中显示出来.
刚才的内容提供器要在AndroidManifest中进行注册,代码如下
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.cameraalbumtest">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
...
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.cameraalbumtest.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"/>
</provider>
</application>
</manifest>
其中andorid:name属性的值是固定的,android:authorities属性的值必须和FileProvider.getUriForFile()方法中第二个参数一致,另外,这里还在provider标签的内部使用meta-data来指定Uri的共享路径,并引用了一个@xml/file_paths资源,当然,这个资源现在还是不存在的,需要创建,代码如下:
<?xml version="1.0" encoding="utf-8"?>
<path xmlns:android="http://schemas.android.com/apk/res/android"
<external-path name="my_images" path=""/>
</path>
其中external-path就是用来指定Uri共享的,name属性的值可以随便写,path属性的值表示共享的具体路径,这里设置空值就表示将整个SD卡进行共享,当然也可以仅共享我们存放output_image.jpg的路径
注意:在Android4.4之前,访问SD卡的应用关联目录也是要声明权限的,从Android4.4系统开始就不再需要声明了.所以在AndroidManifest中添加权限声明,代码如下:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.cameraalbumtest">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
...
</manifest>
2.从相册中选择照片.
修改activity_main.xml代码,在布局中添加一个按钮用于从相机中选择照片,代码如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/take_photo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Take Photo" />
<Button
android:id="@+id/choose_from_album"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Choose From Album"/>
<ImageView
android:id="@+id/picture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"/>
</LinearLayout>
修改MainActivity代码,加入从相册选择照片的逻辑,代码如下:
public class MainActivity extends AppCompatActivity {
...
public static final int CHOOSE_PHOTO = 2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button takePhoto = (Button)findViewById(R.id.take_photo);
...
Button chooseFromAlbum = (Button)findViewById(R.id.choose_from_album);
chooseFromAlbum.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
} else {
openAlbum();
}
}
});
}
private void openAlbum(){
Intent intent = new Intent("android.intent.action.GET_CONTENT");
intent.setType("image/*");
startActivityForResult(intent, CHOOSE_PHOTO);//打开相册
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode){
case 1:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
openAlbum();
} else {
Toast.makeText(this, "You denied the permission", Toast.LENGTH_SHORT).show();
}
break;
default:
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode){
...
case CHOOSE_PHOTO:
if (resultCode == RESULT_OK){
//判断手机系统版本号
if (Build.VERSION.SDK_INT >= 19){
//4.4及以上系统使用这个方法处理图片
handleImageOnKitKat(data);
} else {
//4.4以下系统使用这个方法处理图片
handleImageBeforeKitKat(data);
}
}
default:
break;
}
}
@TargetApi(19)
private void handleImageOnKitKat(Intent data){
String imagePath = null;
Uri uri = data.getData();
if (DocumentsContract.isDocumentUri(this,uri)){
//如果是document类型的Uri,则通过document id处理
String docId = DocumentsContract.getDocumentId(uri);
if ("com.android.providers.media.documents".equals(uri.getAuthority())){
String id = docId.split(":")[1];//解析出数字格式的id
String selection = MediaStore.Images.Media._ID + "=" + id;
imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
} else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())){
Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
imagePath = getImagePath(contentUri, null);
}
} else if ("content".equalsIgnoreCase(uri.getScheme())){
//如果是content类型的Uri,则使用普通方式处理
imagePath = getImagePath(uri, null);
} else if ("file".equalsIgnoreCase(uri.getScheme())){
//如果是file类型的Uri,直接获取图片路径即可
imagePath = uri.getPath();
}
displayImage(imagePath); //根据图片路径显示图片
}
private void handleImageBeforeKitKat(Intent data){
Uri uri = data.getData();
String imagePath = getImagePath(uri, null);
displayImage(imagePath);
}
private String getImagePath(Uri uri, String selection){
String path = null;
//通过Uri和selection来获取真实的图片路径
Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
if (cursor != null){
if (cursor.moveToFirst()){
path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
}
cursor.close();
}
return path;
}
private void displayImage(String imagePath){
if (imagePath != null){
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
picture.setImageBitmap(bitmap);
} else {
Toast.makeText(this, "failed to get image", Toast.LENGTH_SHORT).show();
}
}
}
可以看到,在Choose From Album按钮的点击事件里我们先是进行了一个运行时权限处理,动态申请WRITE_EXTERNAL_STORAGE这个危险权限.因为相册中的照片都是存储在SD卡上的,我们要从SD卡中读取照片就需要申请这个权限,WRITE_EXTERNAL_STORAGE表示同时授予程序对SD卡的读写能力.
当用户授权了权限的申请之后会调用openAlbum()方法,这里我们选构造出一个Intent对象,并将它的action指定为android.intent.action.GET_CONTENT.接着给这个Intent对象设置一些必要的参数,然后调用startActivityForResult()方法就可以打开相册程序选择照片了,注意在调用startActivityForResult()方法的时候,我们给第二个参数传入的值变成了CHOOSE_PHOTO,这样当从相册选择完图片回到onActivityResult()方法时,就会进入CHOOSE_PHOTO的case来处理图片,
首先为了兼容新老版本的手机,我们做了一个判断,如果是4.4及以上系统的手机就调用handleImageOnKitKat()方法来处理图片,否则就调用handleImageBeforeKitKat()来处理图片.是因为Android系统从4,4版本开始,选取相册中的图片不再返回图片真实的Uri了,而是封装过的Uri,因此如果是4.4版本以上的手机就需要对这个Uri进行解析才行.
那么handleImageOnKitKat()方法中的逻辑就基本是如何解析这个封装过的Uri了.这里有好几种判断情况,如果返回的Uri是document类型的话,那就取出document id进行处理,如果不是的话,那就使用普通的方式处理,另外,如果Uri的authority是media格式的话,document id还需要再进行一次解析,要通过字符串分割的方式取出后半部分才能得到真正的数字id,取出的id用于构建新的Uri和条件语句,然后把这些值作为参数传入到getItemPath()方法当中,就可以获取到图片的真实路径了,拿到图片的路径之后,再调用displayImage()方法将图片显示在界面上
相对于handleImageOnKitKat()方法,handleImageBeforeKitKat()方法中的逻辑就要简单得多了,因为它的Uri是没有封装过的,不需要任何解析,直接将Uri传入到getItemPath()方法当中就能获取到图片的真实路径了,最后同样是调用displayImage()方法将图片显示在界面上.