【起航计划 009】2015 起航计划 Android APIDemo的魔鬼步伐 08 App->Activity->QuickContactsDemo 联系人 ResourceCursorAdapter使用 QuickContactBadge使用
QuickContactsDemo示例介绍了如何使用Content Provider来访问Android系统的Contacts 数据库。
Content Provider为不同应用之间共享数据提供了统一的接口,通过对底层数据源的抽象,Content Provider实现了应用程序代码和数据层分离。
Android平台对大部分的系统数据库都提供了对应的Content Provider接口:
- Browser: 读取和修改Bookmark,Browser history或Web Searches。
- CallLog: 查看或是更新Call History(打入电话或是打出电话,未接电话等)
- Contacts: 检索,修改或存储通讯录。
- MediaStore: 访问媒体库(包括声音,视频,图像等)。
- Settings: 访问系统设置,查看或是修改蓝牙设置,铃声设置等。
Android系统的每个Content Provider都定义了一个CONTENT_URI,功能类似于数据库的名称。
Android中每个 Context对象(如Activity)都含有一个ContentResolver,ContentResolver可以根据CONTENT_URI获取对应的Content Provider:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String select = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND ("
+ Contacts.HAS_PHONE_NUMBER + "=1) AND ("
+ Contacts.DISPLAY_NAME + " != '' ))"; //((display_name NOTNULL) AND (has_phone_number=1) AND (display_name!=''))
Cursor c =
getContentResolver().query(Contacts.CONTENT_URI, CONTACTS_SUMMARY_PROJECTION, select,
null, Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
startManagingCursor(c);
ContactListItemAdapter adapter = new ContactListItemAdapter(this, R.layout.quick_contacts, c);
setListAdapter(adapter); }
getContentResolver() 取得ContentResolver对象,它的Query方法定义如下:
public final Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)
- Uri: 需要访问的Content Provider对应的URI,如通讯录的URI为Contacts.CONTENT_URI。
- Projection: 需要返回的表的列名,如为NULL,则返回表的全部列。
- Selection: 查询数据表的条件,相当于SQL 的Where语句。
- selectionArgs: 相当于SQL查询条件的查询参数?
- sortOrder: 相当于SQL查询的Order语句,查询排序,为空时,返回记录的缺省顺序。
可以看得出,Content Provider和 数据库的用法非常类似。query返回的对象为Cusor ,有Cursor对象后就可以和访问数据库表一样来insert ,delete ,update 数据库。
startManagingCursor(c); 让Activity来管理cursor 的生命周期。
此外访问Content Provider还需要合适的权限才能正确访问,比如读写通讯录,需要在AndroidManifest.xml设置:
<uses-permission android:name=”android.permission.READ_CONTACTS” />
<uses-permission android:name=”android.permission.WRITE_CONTACTS” />
才能有权限访问通信录。

注:如果在模拟器上运行这个示例,需要在Contacts添加几个Contacts,否则这个例子没有显示。
这里使用了ResourceCursorAdapter数据适配器。
private final class ContactListItemAdapter extends ResourceCursorAdapter {
public ContactListItemAdapter(Context context, int layout, Cursor c) {
super(context, layout, c);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
final ContactListItemCache cache = (ContactListItemCache) view.getTag();
// Set the name
cursor.copyStringToBuffer(SUMMARY_NAME_COLUMN_INDEX, cache.nameBuffer);
int size = cache.nameBuffer.sizeCopied;
cache.nameView.setText(cache.nameBuffer.data, 0, size);
final long contactId = cursor.getLong(SUMMARY_ID_COLUMN_INDEX);
final String lookupKey = cursor.getString(SUMMARY_LOOKUP_KEY);
cache.photoView.assignContactUri(Contacts.getLookupUri(contactId, lookupKey));
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = super.newView(context, cursor, parent);
ContactListItemCache cache = new ContactListItemCache();
cache.nameView = (TextView) view.findViewById(R.id.name);
cache.photoView = (QuickContactBadge) view.findViewById(R.id.badge);
view.setTag(cache);
return view;
}
}
final static class ContactListItemCache {
public TextView nameView;
public QuickContactBadge photoView;
public CharArrayBuffer nameBuffer = new CharArrayBuffer(128);
}
中文API:ResourceCursorAdapter
bindView方法绑定游标指向的数据到既存视图.
newView方法根据指定的 xml 文件创建视图.
ContactList的布局还是用了QuickContactBadge,它是一个自定义的ImageView,点击联系人头像就会出现这个Android原生的视图。
它的使用也很简单:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:paddingLeft="0dip"
android:paddingRight="9dip"
android:layout_height= "wrap_content"
android:minHeight="48dip"> <QuickContactBadge
android:id="@+id/badge"
android:layout_marginLeft="2dip"
android:layout_marginRight="14dip"
android:layout_marginTop="4dip"
android:layout_marginBottom="3dip"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_height= "wrap_content"
android:layout_width= "wrap_content"
android:src="@drawable/ic_contact_picture"
style="?android:attr/quickContactBadgeStyleWindowSmall" /> <TextView
android:id="@+id/name"
android:textAppearance="?android:attr/textAppearanceMedium"
android:paddingLeft="2dip"
android:layout_centerVertical="true"
android:layout_toRightOf="@id/badge"
android:layout_width="match_parent"
android:layout_height="wrap_content" /> </RelativeLayout>
QuickContactBadge的一些方法:contacts里QuickContactBadge弹出窗口
其中assignContactUri方法:
public void assignContactUri (Uri contactUri)
指定和QuickContactBadge关联的联系人URI。注意,这里只是显示QuickContact窗口,并不为你绑定联系人图片。
参数 contactUri CONTENT_URI或CONTENT_LOOKUP_URI其中一种风格的URI.
QuickContactBadge的详细使用如下:
Android Quick Tip: Using the Quick Contact Badge
If you’ve spent any time on an Android device, you may have noticed how you can click on little Contact images to launch a toolbar with lots of different actions, such as call, text or email that person. In this Quick Tip, you learn how to build this great functionality—called the Quick Contact Badge—into your own applications.
In order to have easy access to contacts, we’ll start with our existing open source code here. We enhance this project, which initially allowed the user to simply choose a contact from a list, and create several different quick contact badges for that contact to illustrate how they work.
Note: This tutorial requires Android 2.0 or higher.
Step 1: Adding an Activity
Start with a new Activity called QuickContactBadgeActivity. Inside the onCreate() method, add a setContentView() method call for a new layout called badge (e.g. R.id.badge).
public class QuickContactBadgeActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.badge);
}
}
Step 2: Creating the Layout
Now you need to create a layout using QuickContactBadge controls. The QuickContactBadge control was introduced in Android 2.0 (API Level 5). The following layout creates two QuickContactBadge controls and provides a holder for a third (a FrameLayout control). The QuickContactBadge control is derived from an ImageView control. Thus, you can set the image displayed by the QuickContactBadge control just as you would an ImageView, using the src attribute.
Here’s the final layout we’re using:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:text="Sample Quick Contact Badges"
android:id="@+id/TextView01"
android:layout_width="match_parent"
android:layout_height="wrap_content"></TextView>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/pick_contact"
android:onClick="onPickContact"
android:text="@string/pick_contact_for_badge"></Button>
<QuickContactBadge
android:id="@+id/badge_small"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/droid_small"></QuickContactBadge>
<QuickContactBadge
android:id="@+id/badge_medium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></QuickContactBadge>
<FrameLayout
android:id="@+id/badge_holder_large"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></FrameLayout>
</LinearLayout>
QuickContactBadge controls can launch the contact action bar (as we’re calling it) in three different sizes: small, medium (default), and large. The small action bar contains only the action buttons and minimal details. The medium action bar contains the action buttons and some additional contact info. The large action bar contains lots of actions, contact info and graphics.
Note: The current ADT plug-in for Eclipse allows you to set the window size of the contact action bar in XML. An error is shown when you try to set a value, though. Unfortunately, this means you can’t actually set this attribute in the XML layout file. Instead, you must set the window size programmatically using the setMode() method of the QuickContactBadge class. You will see how in the next step.
Step 3: Configuring the Badges
Within the onCreate() method of the Activity, add the following code, replacing the email address with one in your contacts (add it ahead of time if you need to).
QuickContactBadge badgeSmall = (QuickContactBadge) findViewById(R.id.badge_small);
badgeSmall.assignContactFromEmail("any@gmail.com", true);
badgeSmall.setMode(ContactsContract.QuickContact.MODE_SMALL);
The more information that is associated with the contact tied to the badge, the more action items will be available for use in the contact action bar. For instance, here’s one using my own email address:

And here’s another with a contact that has a web address assigned:

You can use the setExcludeMimeTypes() method of the QuickContactBadge class to remove any actions or information you don’t want to display.
Step 4: Working with Unknown Contacts
The previous example worked well because you already knew your own address or added a contact you knew to exist. What if the contact doesn’t yet exist within your Contacts database? Try it!
Add the following code, this time to look up a phone number that you probably don’t have in your address book:
QuickContactBadge badgeMedium = (QuickContactBadge) findViewById(R.id.badge_medium);
badgeMedium.assignContactFromPhone("831-555-1212", true);
badgeMedium.setImageResource(R.drawable.droid_small);
Note also that this time we are using a medium sized QuickContactBadge. When clicking on the QuickContactBadge for an unknown entry, something interesting happens. The user is asked if they want to add the contact. If they choose yes, they’ll get the option to add the email or phone number to an existing contact or create a new contact. Then, on subsequent presses of this QuickContactBadge, the contact will exist and be found. This can be quite handy.
Step 5: Creating a QuickContactBadge From an Existing Contact
Generally speaking, you don’t know what contacts are on someone’s device. You do, however, have access to the Contacts content provider and can retrieve URIs for each contact as needed. You learned how to launch the contact picker in this previous tutorial.
Here’s an example of how we can use a contact URI to supply the contact information for a QuickContactBadge:
public void onPickContact(View view) {
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
Contacts.CONTENT_URI);
startActivityForResult(contactPickerIntent, CONTACT_PICKER_RESULT);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case CONTACT_PICKER_RESULT:
Uri contactUri = data.getData();
FrameLayout badgeLargeHolder = (FrameLayout) findViewById(R.id.badge_holder_large);
QuickContactBadge badgeLarge = new QuickContactBadge(this);
badgeLarge.assignContactUri(contactUri);
badgeLarge.setMode(ContactsContract.QuickContact.MODE_LARGE);
badgeLarge.setImageResource(R.drawable.droid_small);
badgeLargeHolder.addView(badgeLarge);
break;
}
}
}
Here you use the Contact Uri chosen by the user to configure a QuickContactBadge that the user can click on. In addition, this shows the final, and largest, contact action bar mode.
Using the QuickContactBadge
When might you want to use the QuickContactBadge? Use the QuickContactBadge anywhere that displays friends or lists of contacts, enabling the user to interact with these individuals in other ways. You could also add your email and phone number to the Contacts and provide a QuickContactBadge within your application to give users a quick way to email, call, or message you (or your support team).
Conclusion
In this Quick Tip, you learned how to use the QuickContactBadge control to quickly bring up the contact action bar (available in various sizes) and enable various actions to be taken. The QuickContactBadge is a standard view control available in Android 2.0 and higher, so users should be familiar with its purpose, and therefore appreciate it when developers take advantage of its powerful features. The QuickContactBadge can also save you, the developer, valuable time in creating all of the possible Intent actions that this control provides with ease.
【起航计划 009】2015 起航计划 Android APIDemo的魔鬼步伐 08 App->Activity->QuickContactsDemo 联系人 ResourceCursorAdapter使用 QuickContactBadge使用的更多相关文章
- 【起航计划 007】2015 起航计划 Android APIDemo的魔鬼步伐 06 App->Activity->Forwarding Activity启动另外一个Activity finish()方法
Android应用可以包含多个Activity,某个Activity可以启动另外的Activity. 这些Activity采用栈结构来管理,新打开的Activity叠放在当前的Activity之上,当 ...
- 【起航计划 004】2015 起航计划 Android APIDemo的魔鬼步伐 03 App->Activity->Animation Activity跳转动画 R.anim.×× overridePendingTransition ActivityOptions类
App->Activity->Animation示例用于演示不同Activity切换时动态效果. android 5.0例子中定义了6种动画效果: 渐变Fade In 缩放Zoom In ...
- 【起航计划 002】2015 起航计划 Android APIDemo的魔鬼步伐 01
本文链接:[起航计划 002]2015 起航计划 Android APIDemo的魔鬼步伐 01 参考链接:http://blog.csdn.net/column/details/mapdigitap ...
- 【起航计划 037】2015 起航计划 Android APIDemo的魔鬼步伐 36 App->Service->Remote Service Binding AIDL实现不同进程间调用服务接口 kill 进程
本例和下个例子Remote Service Controller 涉及到的文件有RemoteService.java ,IRemoteService.aidl, IRemoteServiceCallb ...
- 【起航计划 031】2015 起航计划 Android APIDemo的魔鬼步伐 30 App->Preferences->Advanced preferences 自定义preference OnPreferenceChangeListener
前篇文章Android ApiDemo示例解析(31):App->Preferences->Launching preferences 中用到了Advanced preferences 中 ...
- 【起航计划 027】2015 起航计划 Android APIDemo的魔鬼步伐 26 App->Preferences->Preferences from XML 偏好设置界面
我们在前面的例子Android ApiDemo示例解析(9):App->Activity->Persistent State 介绍了可以使用Shared Preferences来存储一些状 ...
- 【起航计划 020】2015 起航计划 Android APIDemo的魔鬼步伐 19 App->Dialog Dialog样式
这个例子的主Activity定义在AlertDialogSamples.java 主要用来介绍类AlertDialog的用法,AlertDialog提供的功能是多样的: 显示消息给用户,并可提供一到三 ...
- 【起航计划 012】2015 起航计划 Android APIDemo的魔鬼步伐 11 App->Activity->Save & Restore State onSaveInstanceState onRestoreInstanceState
Save & Restore State与之前的例子Android ApiDemo示例解析(9):App->Activity->Persistent State 实现的UI类似,但 ...
- 【起航计划 003】2015 起航计划 Android APIDemo的魔鬼步伐 02 SimpleAdapter,ListActivity,PackageManager参考
01 API Demos ApiDemos 详细介绍了Android平台主要的 API,android 5.0主要包括下图几个大类,涵盖了数百api示例:
随机推荐
- jupyter notebook 设置默认目录
1.打开 cmd 输入命令 jupyter notebook --generate-config 可以看到生成文件的路径,这个就是生成的配置文件jupyter_notebook_config.py, ...
- thinkphp 3.0 核心函数U的一个致命bug
最近在玩thinkphp,感觉内置函数 U 挺强大的! 传递多个参数时,出乱子了(window环境下,xampp) 例如 echo U('Blog/cate',array('cate_id'=> ...
- git 工作中常用命令
git 命令: git init : 初始化 git add . :添加所有文件 git status :查看状态 若果是第一次会提示你输入你的 邮箱 和姓名: git commit ...
- poj1062 昂贵的礼物(dijkstra+枚举)
传送门:点击打开链接 题目大意:买东西,每个东西有了替代品,拥有替代品后可以有优惠价格,每个物品的主人有自己的等级,等级超过m的不能直接或者间接交易,问买1号物品的最低价格是多少. 思路:一开始想到d ...
- QQ号_保存_20180124
1.1337978907 (密码:33+我的名字全小写全部拼音) 2. 3. 4. 5.
- Error in event handler for "el.form.change": "TypeError: value.getTime is not a function"
首先说一下我使用的实际场景 html代码: js代码: 首先说明出现原因,elementUI的日期选择器[el-date-picker]在加上格式 value-format="yyyy-MM ...
- TCP Nagle算法以及延迟确认(即延迟回复ACK)的学习
TCP/IP协议中,无论发送多少数据,总是要在数据前面加上协议头,同时,对方接收到数据,也需要发送ACK表示确认.为了尽可能的利用网络带宽,TCP总是希望尽可能的发送足够大的数据. (一个连TCP接会 ...
- 性能测试工具LoadRunner19-LR之Controller IP欺骗
概念 IP地址欺骗是指用户操作产生的IP数据包为伪造的源IP地址,以便冒充其他系统或发件人的身份.这是一种黑客的攻击形式,黑客使用一台计算机上网,而借用另外一台机器的IP地址,从而冒充另外一台机器与服 ...
- 性能测试工具Jmeter02-安装配置
安装配置 1.安装配置jdk 2.Jmeter下载地址:http://mirror.bit.edu.cn/apache/jmeter/binaries/ 下载后,解压文件到任意目录,避免在一个有空格的 ...
- mac 下安装 mysql
1. 下载mysql community server 2. 下载mysql workbench 3. 启动mysql server 4. 进入mysql命令行 5. 修改root密码 ALTER U ...

