主要使用意图Intent.ACTION_PICK,
外带一个uri:android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI
例子:
Intent intent=new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent,requestCode);
话不多说,自己的一个简易的小Demo
源码:
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.FileNotFoundException;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private final int RESULTCODE=0;
private Button pick;
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pick=(Button)findViewById(R.id.pick);
imageView=(ImageView)findViewById(R.id.image);
pick.setOnClickListener(this);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == RESULTCODE) {
Log.i("Main","onActivity");
//处理显示的图像
Uri uri=data.getData();
Display current=getWindowManager().getDefaultDisplay();
int dw=current.getWidth();
int dh=current.getHeight()/2-100;
try {
BitmapFactory.Options biops=new BitmapFactory.Options();
biops.inJustDecodeBounds=true;
Bitmap bmp=BitmapFactory.decodeStream(getContentResolver().openInputStream(uri),null,biops);
int hRatio=(int)Math.ceil(biops.outHeight/(float)dh);
int wRatio=(int)Math.ceil(biops.outWidth/(float)dw);
if (hRatio>1 && wRatio>1) {
if (hRatio > wRatio) {
biops.inSampleSize = hRatio;
} else {
biops.inSampleSize=wRatio;
}
biops.inJustDecodeBounds=false;
bmp=BitmapFactory.decodeStream(getContentResolver().openInputStream(uri),null,biops);
imageView.setImageBitmap(bmp);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
@Override
public void onClick(View v) {
Intent intent=new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent,RESULTCODE);
}
}