用户点击按钮选择拍照或者打开相册选择图片,然后将选中的图片显示在手机上。android6.0后,推出了动态权限管理。android6.0后,对于一些特别敏感的权限,开发者必须在程序中进行声明。在manifest文件中声明已经不好使。拍照和从相册选择图片都是涉及到用户隐私的敏感权限,必须在代码中进行声明。
首先我们缕清一下思路
1创建存放图片的文件夹
2隐式启动相机的Activity,uri作为intent的一个参数.
3拍照结束后,执行onActivityResult(…)获得图片 相册选取图片
4启动相册Activity
5选择结束后,执行onActivityResult(…)获得图片 动态权限管理
看一下布局文件几个按钮:
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context="com.qy.app.lkb.activity.UpLoadPhotoActivity">
<ImageView
android:id="@+id/preview_image"
android:layout_marginTop="30dp"
android:layout_width="230dp"
android:layout_height="230dp"
android:layout_centerHorizontal="true"
/>
<LinearLayout
android:id="@+id/my_pop_layout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:gravity="center_horizontal"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/shape_photo_pop_btn_normal"
android:orientation="vertical">
<TextView
android:layout_width="fill_parent"
android:layout_height="30dp"
android:text="请上传小于1M的图片"
android:gravity="center"
android:textColor="#444444"
/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="@color/divider_line_color" />
<Button
android:id="@+id/btn_take_photo1"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:background="@drawable/btn_style_alert_dialog_cancel"
android:text="拍照"
android:textColor="@drawable/selector_pop_text_color"
android:textSize="17sp" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="@color/divider_line_color" />
<Button
android:id="@+id/btn_pick_photo1"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:background="@drawable/btn_style_alert_dialog_cancel"
android:text="从相册选择"
android:textColor="@drawable/selector_pop_text_color"
android:textSize="17sp" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="@color/divider_line_color" />
</LinearLayout>
界面也就是这样:
- 创建文件夹
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
String storageDir = Environment.getExternalStorageDirectory() + "/picupload";
File dir = new File(storageDir);
if (!dir.exists())
dir.mkdir();
File image = new File(storageDir + "/" + imageFileName + ".jpg");
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
Log.i("uploadpath", "photo path = " + mCurrentPhotoPath);
return image;
}
- 照相
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
- 选择相册
/**
* 从相册选择图片
*/
protected void doPickPhotoFromGallery() {
try {
// Launch picker to choose photo for selected contact
final Intent intent = getPhotoPickIntent();
startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "暂无图片",
Toast.LENGTH_LONG).show();
}
}
/**
* 获取调用相册的Intent
*/
public static Intent getPhotoPickIntent() {
Intent intent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
return intent;
}
- 选择结束后,执行onActivityResult(…)获得图片 动态权限管理
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
Log.i("result", "onActivityResult: " + this);
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == Activity.RESULT_OK) {
Log.e("照相",mCurrentPhotoPath);
setPic();
}else if (requestCode == PHOTO_PICKED_WITH_DATA && resultCode == Activity.RESULT_OK) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
rotatedBMP = bitmap;
previewImage.setImageBitmap(bitmap);
}
}
- 动态权限管理
private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE = 7;
private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE2 = 8;
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
{
if (requestCode == MY_PERMISSIONS_REQUEST_CALL_PHONE)
{
boolean flag = true;
if (grantResults != null) {
for (int i = 0; i < grantResults.length; i++) {
if (grantResults[i] != PackageManager.PERMISSION_GRANTED )
{
flag = false;
}
}
if (flag){
// Permission Denied
dispatchTakePictureIntent();
}else{
Toast.makeText(UpLoadPhotoActivity.this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
}
}
if (requestCode == MY_PERMISSIONS_REQUEST_CALL_PHONE2)
{
if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
doPickPhotoFromGallery();
} else
{
// Permission Denied
Toast.makeText(UpLoadPhotoActivity.this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
点击事件的处理
@OnClick({R.id.btn_take_photo1, R.id.btn_pick_photo1, R.id.btn_cancel1, R.id.btn_upload})
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_take_photo1:
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA},
MY_PERMISSIONS_REQUEST_CALL_PHONE);
}else {
dispatchTakePictureIntent();
}
break;
case R.id.btn_pick_photo1:
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_CALL_PHONE2);
}else {
doPickPhotoFromGallery();
}
break;
case R.id.btn_upload:
if(rotatedBMP != null) {
rotatedBMP = PhotoUtil.compressImage(rotatedBMP);
try {
sendPhoto(rotatedBMP);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else {
Toast.makeText(UpLoadPhotoActivity.this,"请先选择图片",Toast.LENGTH_LONG).show();
}
case R.id.btn_cancel1:
finish();
break;
}
}