本文介绍了android如何取得本地通讯录的头像的原图的实现代码,分享给大家,也给自己留个笔记
如果想通讯录进入详情页,那么最重要的参数就是contactId,这个是联系人的唯一标识
代码语言:javascript复制getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<? parent, View view, int position, long id) {
try {
Cursor cursor = (Cursor) getListAdapter().getItem(position);
if (cursor == null) {
return;
}
int contactId = cursor.getInt(Personal.ID_COLUMN_INDEX);
Intent intent = new Intent();
intent.setClass(ContactsList.this, ContactDetail.class);
intent.putExtra("contactId",contactId);
startActivity(intent);
}catch(Exception ex) {
ex.printStackTrace();
}
}
});
本地通讯录的原图获取方法是:
代码语言:javascript复制public class ContactDetail extends Activity {
private ImageView contact_photo;
public static void startActivity(Context context) {
Intent intent = new Intent();
intent.setClass(context,ContactDetail.class);
context.startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.contact_detail);
int contactId = getIntent().getIntExtra("contactId", 0);
contact_photo = (ImageView)findViewById(R.id.contact_photo);
loadTask task = new loadTask(contactId);
task.execute();
}
private class loadTask extends AsyncTask<Void, Void, Bitmap {
public loadTask(int id) {
contactId = id;
}
private int contactId;
@Override
protected Bitmap doInBackground(Void... params) {
InputStream inputStream = openDisplayPhoto(contactId);
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inSampleSize = 1;
Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, opt);
return bitmap;
}
@Override
protected void onPostExecute(Bitmap result) {
if(result != null) {
contact_photo.setImageBitmap(result);
}
super.onPostExecute(result);
}
}
/**
* 这个是取到清晰图的inputStream的代码
* @param contactId
* @return
*/
public InputStream openDisplayPhoto(long contactId) {
Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
Uri displayPhotoUri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.DISPLAY_PHOTO);
try {
AssetFileDescriptor fd =
this.getContentResolver().openAssetFileDescriptor(displayPhotoUri, "r");
return fd.createInputStream();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
activity的运行效果是:
代码在https://github.com/nickgao1986/StepSport
以上就是本文的全部内容,希望对大家的学习有所帮助。