以下为代码块:


package com.example.demo;



import java.io.File;


import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio.Media;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;


public class MainActivity extends Activity {


public static final int TAKE_PHOTO = 1;
public static final int CROP_PHOTO = 2;
public static final int CHOOSE_PH = 3;


Button b, chooseFromAlbum;
ImageView pictrue;
Uri imageUri;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button) findViewById(R.id.button1);
chooseFromAlbum = (Button) findViewById(R.id.choose_from_album);
pictrue = (ImageView) findViewById(R.id.imageView1);
chooseFromAlbum.setOnClickListener(new OnClickListener() {


@Override
public void onClick(View v) {
Intent intent = new Intent("android.intent.action.GET_CONTENT");
intent.setType("image/*");
startActivityForResult(intent,CHOOSE_PH);//打开相册。
}
});
b.setOnClickListener(new OnClickListener() {


@Override
public void onClick(View v) {
File outputImage = new File(Environment
.getExternalStorageDirectory(), "output_image.jpg");// Environment.getExternalStorageDirectory()获取SD卡的根目录.
try {
if (outputImage.exists()) {
outputImage.delete();
}
outputImage.createNewFile();


} catch (Exception e) {
// TODO: handle exception
}
imageUri = Uri.fromFile(outputImage);
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);// 个人理解拍完放在imageUri下。
startActivityForResult(intent, TAKE_PHOTO);// 启动相机程序。
}
});
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {// requestCode:拍完照传回1,裁剪完传回2。
switch (requestCode) {
case TAKE_PHOTO:
if (resultCode == RESULT_OK) {
try {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(imageUri, "image/*");
intent.putExtra("scale", true);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);// 剪完放在放在imageUri下。
startActivityForResult(intent, CROP_PHOTO);// 启动裁剪程序。
} catch (Exception e) {
Log.i("test", "e=" + e);
}
}
break;
case CROP_PHOTO:
if (resultCode == RESULT_OK) {
try {
Bitmap bitMap = BitmapFactory
.decodeStream(getContentResolver().openInputStream(
imageUri));// 解码。
Log.i("test", "bitMap=" + bitMap);
pictrue.setImageBitmap(bitMap);// 将裁减的图片显示出来。
} catch (Exception e) {
Log.i("test", "e1=" + e);
}
}
break;
case CHOOSE_PH:
if(resultCode == RESULT_OK ){
//判断当前系统版本。
if(Build.VERSION.SDK_INT>=19){
// 4.4以上的系统版本使用这个方法处理。
handleImageOnKitKat(data);
}else{
// 4.4以下的系统版本使用这个方法处理。
handleImageBeforeKitKat(data);
}
}
break;
default:
break;
}
}
@TargetApi(19)
private void handleImageOnKitKat(Intent data){
String imagePath = null;
Uri uri = data.getData();
Log.i("test","4.4以上uri="+uri);
if(DocumentsContract.isDocumentUri(this, uri)){
String docId = DocumentsContract.getDocumentId(uri);
if("com.android.providers.media.documents".equals(uri.getAuthority())){
String id = docId.split(":")[1];
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())){
imagePath = getImagePath(uri,null);
}
//imagePath此时的路径为真实的手机图片的路径。
displayImage(imagePath);
}


private void handleImageBeforeKitKat(Intent data){
Uri uri = data.getData();
String imagePath = getImagePath(uri,null);
//imagePath此时的路径为真实的手机图片的路径。
displayImage(imagePath);
}
private String getImagePath(Uri uri,String selection){
String path = null;
// getContentResolver:获得内容解析;query:查询。
Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
if(cursor!=null){
if(cursor.moveToFirst()){
// getColumnIndex:获得列索引。
path = cursor.getString(cursor.getColumnIndex(Media.DATA));
}
cursor.close();
}
return path;
}
private void displayImage(String imagePath){
if(imagePath!=null){
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
pictrue.setImageBitmap(bitmap);
}else{
Toast.makeText(this, "错误!", Toast.LENGTH_LONG).show();
}
}


}

以下为AndroidManifest.xml文件内容:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.demo"
android:versionCode="1"
android:versionName="1.0" >


<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19" />
<uses-permission android:name="androd.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />


<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>


</manifest>

以下为简单的布局文件:

<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.choosepictest.MainActivity" >


<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="打开相机" />


<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button1"
android:layout_below="@+id/button1"
android:layout_marginTop="131dp" />


<Button
android:id="@+id/choose_from_album"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button1"
android:layout_below="@+id/button1"
android:layout_marginTop="26dp"
android:text="打开相册" />


</RelativeLayout>

更多相关文章

  1. AndroidManifest.xml 系统找不到指定的文件
  2. 各Android版本WifiStateMachine状态机
  3. Android获取当前WiFi的MAC地址-适配所有版本
  4. 一张图带你掌握Android Q上InputDispatcher事件分发流程(系统层)
  5. Android应用程序版本切换
  6. android studio 中设置apk的版本号
  7. 让应用程序不被任务管理器杀死...(获取系统权限)
  8. Android 版本号和分支查看
  9. Android系统升级的完整过程

随机推荐

  1. Android 6.0 源代码编译实践
  2. Android中下拉列表框操作
  3. Android让一个apk作为Launcher启动
  4. Android 网络操作(上传下载等)
  5. android程序安全注意点
  6. Android 探究 LayoutInflater setFactory
  7. Android 线程池管理工具类
  8. Android回调事件传播-android学习之旅(四
  9. TextView设置行间距 和 字间距
  10. android之创建快捷方式