2012-12-17 71 views
0

在我的應用程序IAM試圖檢索電話簿聯繫人圖像,並顯示在list.below的圖像檢索聯繫人圖片是我的代碼的AsyncTask:從設備電話簿

public InputStream getContactPhoto(Context context, String profileId){ 
     try{ 
      ContentResolver cr = context.getContentResolver(); 
      Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.parseLong(profileId)); 
      return ContactsContract.Contacts.openContactPhotoInputStream(cr, uri); 
     }catch(Exception e){ 
      return null; 
     } 
    } 

    private Bitmap loadContactPhoto(ContentResolver cr, long id) { 
     Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, id); 

     InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(cr, uri); 

     if (input == null) { 
      return null; 
     } 
     return BitmapFactory.decodeStream(input); 
    } 

其工作,但是好像並不順利,所以想實現使用asynctask獲取圖像 關於如何使用上述代碼實現的任何建議

回答

0

如果您正在使用ImageView並希望加載圖片(在本例中,它從圖片中檢索圖片SD卡),你可以這樣做:

- 創建一個擴展的ImageView

public class SDImageView extends CacheableImageView { 
    ... 
} 

自定義類 - 創建一個名爲load()(或任何你想要的)你需要的參數的方法。在我的情況是圖像的路徑:

public final void loadImage(final String tpath) { 
     if (tpath == null) { 
      return; 
     } 

     SDLoadAsyncTask.load(this, tpath); 
    } 

- 創建一個擴展的AsyncTask和實施要在doInBackground方法做操作的類

private static class SDLoadAsyncTask extends AsyncTask<Void, Void, Bitmap> { 

     final SDImageView view; 
     final String path; 

     private SDLoadAsyncTask(SDImageView view, String path) { 
      this.view = view; 
      this.path = path; 
     } 

     @Override 
     protected final Bitmap doInBackground(Void... params) { 
      Bitmap bmp = null; 
      InputStream is = null; 
      try { 
       is = new FileInputStream(mContext.getExternalFilesDir(null) + "/" + path); 
       bmp = BitmapFactory.decodeStream(is); 
      } catch (Exception e) { 
       Utils.logMsg("Exception for img " + path, e); 
      } finally { 
       try { 
        is.close(); 
       } catch (Exception e2) { 
       } 
      } 
      return bmp; 

     @Override 
     protected final void onPostExecute(Bitmap result) { 
      view.setImageBitmap(result); 
     } 
}