2 nana4ever nana4ever 于 2013.02.04 17:43 提问

URI 和 ACTION_GET_CONTENT

我想从一个 android 设备中选择一个图像,当我使用下面这段代码时,什么时候要使用 ACTION_GET_CONTENT intent 呢?

// 随机获取图像
    public static Uri getRandomImage(ContentResolver resolver) {

        String[] projection = new String[] { BaseColumns._ID
        };
        Uri uri = new Random().nextInt(1) == 0 ? Media.EXTERNAL_CONTENT_URI
                : Media.INTERNAL_CONTENT_URI;

        Cursor cursor = Media.query(resolver, uri, projection, null,
                MediaColumns._ID);
        if (cursor == null || cursor.getCount() <= 0) {
            return null;
        }

        cursor.moveToPosition(new Random().nextInt(cursor.getCount()));

        return Uri.withAppendedPath(uri, cursor.getString(0));
    }

2个回答

curie_87
curie_87   2013.02.05 14:08

如果你想从android gallery 中选择图像,可以这样

Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 100);

要返回结果

protected void onActivityResult(int requestCode, int resultCode, 
   Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 

switch(requestCode) { 
case REQ_CODE_PICK_IMAGE:
    if(resultCode == RESULT_OK){  
        Uri selectedImage = imageReturnedIntent.getData();
        String[] filePathColumn = {MediaStore.Images.Media.DATA};

        Cursor cursor = getContentResolver().query(
                           selectedImage, filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String filePath = cursor.getString(columnIndex);
        cursor.close();


        Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
    }
}
}
zlQQhs
zlQQhs   2013.02.25 23:55
protected void select() {
        Intent intent = new Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, 1);
    }



protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==RESULT_OK){
            switch (requestCode) {
            case 1:
                Uri uri = data.getData();
                String[] col = {MediaStore.Images.Media.DATA};
                Cursor c = getContentResolver().query(uri, col, null, null, null);
                c.moveToFirst();
                String imgpath = c.getString(c.getColumnIndex(col[0]));
                iv_imgage.setImageURI(Uri.parse(imgpath));
                c.close();
                break;

            default:
                break;
            }
        }
    }
suannai0314
suannai0314 这格式有点乱,帮你编辑了下,详细的markdown使用方法见http://ask.csdn.net/pages/markdown
4 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片