`
dinguangx
  • 浏览: 240545 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

【Cordova2.9】 扩展Contacts插件实现按ID查询

阅读更多

      PhoneGap(Cordova)的通讯录插件(contacts & Contact)提供了对本地通讯录的数据检索(contacts.find)、新增(Contact.save)和删除(Contact.remove)等功能,基本实现了对本地通讯录的CRUD操作。但是在使用过程中,发现该插件并不支持对特定ID的检索功能。典型的场景是在用find()操作获取到所有的通讯录信息之后,点击指定的条目,需要查询的是该条目对应的所有信息,这时就需要通过特定ID来进行数据检索。

find()操作中,接收两个参数fieldsoptions,分别用来表示检索结果要包含的字段以及过滤条件。通过phonegap的源码可以看出,它对通讯录的检索条件是根据fields来做的,如果fields的值为[“*”],就在所有的字段中匹配options;如果fields的内容是一个普通的字符串数组,就在该数组所表示的字段中匹配options,返回的结果中只会包括fields数组中所给定的列信息。也就是说,find()操作并不能完成对特定ID的数据检索。只能通过自行扩展该插件来实现。

下面是对该插件的扩展,通过对该插件的扩展实现,也对PhoneGap的插件机制以及对原生插件的扩展有了全面的掌握。

首先是扩展现有的ContactManager类:

/**
 * 扩展ContactManager插件,实现附加的一些功能
 * 
 * @author dylan
 * 
 */
public class ContactManagerExtend extends ContactManager {

	private ContactAccessor contactAccessor;
	private static final String LOG_TAG = "Contact Query";

	@Override
	public boolean execute(String action, JSONArray args,
			final CallbackContext callbackContext) throws JSONException {
		boolean res = super.execute(action, args, callbackContext);
		if (!res) {
			// not support by parent
			if (this.contactAccessor == null) {
				this.contactAccessor = new ContactAccessorSdk5(this.webView,
						this.cordova);
			}
			if ("findById".equals(action)) {
				final String contactId = args.getString(0);
				Log.v(LOG_TAG, "find contact by ID[" + contactId+"]");
				this.cordova.getThreadPool().execute(new Runnable() {
					public void run() {
						JSONObject res = null;
						if (contactId != null) {
							try {
								res = contactAccessor.getContactById(contactId);
							} catch (JSONException e) {
								Log.e(LOG_TAG, "JSON fail.", e);
							}
						}
						if (res != null) {
							callbackContext.success(res);
						} else {
							callbackContext.sendPluginResult(new PluginResult(
									PluginResult.Status.ERROR, UNKNOWN_ERROR));
						}
					}
				});
			} else {
				return false;
			}
		}
		return true;
	}
}

     在该类中,重写了父类的execute(action,args,context),用于在父类不支持当前action时,接管程序的执行。

然后在config.xml中将插件类替换为我们的扩展类:

<feature name="Contacts">
   <!-- 
  <param name="android-package" value="org.apache.cordova.ContactManager"/>
   -->
  <param name="android-package" value="org.dylan.phonegap.plugins.ContactManagerExtend"/>
</feature>

 同步地,在前台js中扩展contacts插件,增加对findById()的支持:

(function(cordova) {
	var exec = cordova.require("cordova/exec");
	var argscheck = cordova.require('cordova/argscheck');
	var contacts = cordova.require("cordova/plugin/contacts");
	/**
	 * contacts plugin: findById
	 */
	contacts.findById = function(contactId, successCB, failCB) {
		argscheck.checkArgs('SFF', 'contacts.findById', arguments);
		console.log("find contact by id["+contactId+"]");
		if (!contactId) {
			failCB
					&& failCB(new ContactError(
							ContactError.INVALID_ARGUMENT_ERROR));
		} else {
			var win = function(result) {
				var model = null;
				if (result) {
					model = contacts.create(result);
				}
				successCB(model);
			};
			exec(win, failCB, "Contacts", "findById", [ contactId ]);
		}
	};
})(cordova);

 前台页面中调用该函数的代码为:

navigator.contacts.findById(contactId, function(contact){
	console.log("success..." + contact.displayName);
	//do something
}, function(){
	alert("Find Failed!");
});

 至此,对通讯录插件的扩展完成;findById()方法将会返回Contact支持的所有信息。

附:Contact信息格式(参考http://www.gafish.net/archives/990)

{
    'id': '1',
    'rawId': '17',
    'name': {
        'familyName': '加',
        'formatted': '加菲 ',
        'givenName': '菲',
        'middleName': '',
        'honorificPrefix': '',
        'honorificSuffix': ''
    },
    'displayName': 'Gafish',
    'nickname': '加菲',
    'birthday': '1999/01/01',
    'note': 'xx是个好东西',
    'phoneNumbers': [{
        'id': '1',
        'type': 'mobile',
        'value': '13888888888',
        'pref': false
    }],
    'emails': [{
        'id': '1',
        'type': 'home',
        'value': 'gafish@xx.com',
        'pref': false
    }],
    'addresses': [{
        'id': '1',
        'type': 'home',
        'pref': false,
        'postalCode': '310000',
        'formatted': 'xx路xx号xx大厦',
        'locality': '杭州',
        'region': '浙江',
        'country': '中国'
    }],
    'ims': [{
        'id': '1',
        'type': 'qq',
        'value': '88888888',
        'pref': false
    }],
    'organizations': [{
        'id': '1',
        'type': 'work',
        'title': 'xx工程师',
        'department': 'xx部',
        'name': 'xx公司'
        'pref': false,
    }],
    'photos': [{
        'type': 'url',
        'id': '1',
        'value': 'photo8.jpg',
        'pref': false
    }],
    'categories': [{
        'id': '1',
        'type': '',
        'value': 'Business',
        'pref': false
    }],
    'urls': [{
        'id': '1',
        'type': 'work',
        'value': 'www.gafish.net',
        'pref': false
    }]
}

 

1
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics