最近在做一個圖片上傳的功能,需要提供上傳圖片在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" />