android 8.3.2
本帖最后由 alltolove 于 2017-10-29 09:10 编辑修改之前的项目activity_main<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<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.javapackage com.example.xinwei.cameraalbumtest;
import android.Manifest;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
public static final int TAKE_PHOTO=1;
public static final int CHOOSE_PHOTO=2;
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 outputImage = new File(getExternalCacheDir(),"output_image.jpg");
if (outputImage.exists()){
outputImage.delete();
}
try {
outputImage.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
if (Build.VERSION.SDK_INT>=24){
imageUri= FileProvider.getUriForFile(MainActivity.this,"com.example.xinwei.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);
}
});
choosePhoto();
}
private void choosePhoto() {
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
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, 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;
case CHOOSE_PHOTO:
if(requestCode==RESULT_OK){
if(Build.VERSION.SDK_INT>=19){
handleImageOnKitKat(data);
}else {
handleImageBeforeKitKat(data);
}
}
default:
break;
}
}
private void handleImageBeforeKitKat(Intent data) {
Uri uri=data.getData();
String imagePath=getImagePath(uri,null);
displayImage(imagePath);
}
private void handleImageOnKitKat(Intent data) {
String imagePath=null;
Uri uri=data.getData();
if(DocumentsContract.isDocumentUri(this,uri)){
String docId=DocumentsContract.getDocumentId(uri);
if("com.android.providers.media.documents".equals(uri.getAuthority())){
String id=docId.split(":");
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);
}else if ("file".equalsIgnoreCase(uri.getScheme())){
imagePath=uri.getPath();
}
displayImage(imagePath);
}
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();
}
}
private String getImagePath(Uri uri, String selection) {
String path=null;
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;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case 1:
if(grantResults.length>0&&grantResults==PackageManager.PERMISSION_GRANTED){
openAlbum();
}else{
Toast.makeText(this, "You denied zhe permission", Toast.LENGTH_SHORT).show();
}
break;
default:
}
}
}
这个代码又多又复杂最好是照抄就行了,另外因为手机模拟器上没有照片所以显示不出来,需要先拍几张黑屏才行。
页:
[1]