最近在做一个图片上传的功能,需要提供上传图片在SD卡中的路径,在网上看了些例子,改改调试成功,代码很简单。其布局文件如下:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
- <Button
- android:id="@+id/select"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="请选择SD卡中的图片"
- />
- </LinearLayout>
JAVA文件如下:
- package com.lostinai;
- import java.io.IOException;
- import android.app.Activity;
- import android.content.ContentResolver;
- import android.content.Intent;
- import android.database.Cursor;
- import android.graphics.Bitmap;
- import android.net.Uri;
- import android.os.Bundle;
- import android.provider.MediaStore;
- import android.util.Log;
- import android.view.View;
- import android.widget.Button;
- public class QueryPictureUrlActivity extends Activity {
- private Button select;
- private final String IMAGE_TYPE = "image/*";
- private final int IMAGE_CODE = 0;
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- select = (Button)findViewById(R.id.select);
- select.setOnClickListener(new View.OnClickListener(){
- public void onClick(View v) {
- Intent getAlbum = new Intent(Intent.ACTION_GET_CONTENT);
- getAlbum.setType(IMAGE_TYPE);
- startActivityForResult(getAlbum, IMAGE_CODE);
- }
- });
- }
- protected void onActivityResult(int requestCode, int resultCode, Intent data){
- if (resultCode != RESULT_OK) { //此处的 RESULT_OK 是系统自定义得一个常量
- // Log.e(TAG,"ActivityResult resultCode error");
- return;
- }
- Bitmap bm = null;
- ContentResolver resolver = getContentResolver();
- if (requestCode == IMAGE_CODE) {
- try {
- Uri originalUri = data.getData(); //获得图片的uri
- bm = MediaStore.Images.Media.getBitmap(resolver, originalUri); //显得到bitmap图片
- // 这里开始的第二部分,获取图片的路径:
- String[] proj = {MediaStore.Images.Media.DATA};
- Cursor cursor = managedQuery(originalUri, proj, null, null, null);
- //按我个人理解 这个是获得用户选择的图片的索引值
- int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
- cursor.moveToFirst();
- //最后根据索引值获取图片路径
- String path = cursor.getString(column_index);
- Log.e("Lostinai",path);
- }catch (IOException e) {
- Log.e("Lostinai",e.toString());
- }
- }
- }
- }
最后别忘记了加上权限啊
- <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
- <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />