2013-02-04 50 views
1

當使用URI VS ACTION_GET_CONTENT

// to get image randomly 
    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)); 
    } 

以及何時使用ACTION_GET_CONTENT意圖是什麼?

因爲我想從Android設備中選擇圖片!

請幫助

回答

0

如果您想選擇從德Android圖庫的圖像,然後嘗試這樣:

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); 
    } 
} 

}

你也可以參考這個:

How to pick an image from gallery (SD Card) for my app?

相關問題