2011年9月29日

Android: 從Content Resolver取得Media (II)

Android Developer: Content Provider
底下節錄翻譯自上面:
//Use ContentUris to produce the base URI for the contact with _ID= 23.
Uri myPerson = ContentUris.withAppendedId(People.CONTENT_URI, 23);
// Alternatively, use the Uri method to produce the base URI.
// It takes a string rather than an integer.
Uri myPerson = Uri.withAppendedPath(People.CONTENT_URI, "23");
// Then query for this specific record:
Cursor cur = managedQuery(myPerson, null, null, null, null);
  • 如果此項目一個content: URI,你不應該直接打開讀取此文件(會沒有權限而失敗)。你應呼叫ContentResolver.openInputStream()取得物件InputStream,用它來讀取資料。
  • 利用ContentValues.put()可以把小量的binary資料放進去。但若是相片或完整歌曲時,則應該存放content: URI即可,然後以該文件的URI來呼叫ContentResolver.openOutputStream()
  • 因此Android管理影像、圖形的 MediaStore content provider採用了一種特殊的作法:使用和query()或managedQuery()同樣的URI ,也可以用在openInputStream() 來取得資料。同樣的用在insert()的URI,也可以用在openOutputStream()來放入資料!
import android.provider.MediaStore.Images.Media;
import android.content.ContentValues;
import java.io.OutputStream;

//Save the name and description of an image in a ContentValues map. 
ContentValues values = new ContentValues(3);
values.put(Media.DISPLAY_NAME, "road_trip_1");
values.put(Media.DESCRIPTION, "Day 1, trip to Los Angeles");
values.put(Media.MIME_TYPE, "image/jpeg");

//Add a new record without the bitmap, but with the values just set.
//insert()returns the URI of the new record.
Uri uri=getContentResolver().insert(Media.EXTERNAL_CONTENT_URI,values);

//Now get a handle to the file for that record,and save data into it.
//Here,sourceBitmap is a Bitmap representing the file to save to database
try {
    OutputStream outStream = getContentResolver().openOutputStream(uri);
    sourceBitmap.compress(Bitmap.CompressFormat.JPEG, 50, outStream);
    outStream.close();
} catch (Exception e) {
   Log.e(TAG, "exception while writing image", e);
}

沒有留言: