使用Phonegap访问Android上的联系人

Access contacts on Android using Phonegap

本文关键字:联系人 Android Phonegap 访问 使用      更新时间:2023-09-26

我正在使用phone-gap开发一个应用程序。我正在尝试访问移动上的联系人,因为我稍后会使用它们。我现在正在尝试编写代码以在移动设备上查找联系人。这是我正在使用的JS文件:

alert('Starting JS');
var TAP = ('ontouchend' in window) ? 'touchend' : 'click';
alert('I entered the function'); 
   document.addEventListener('DOMContentLoaded', function () {
   alert('I entered the second function');
       x$('#friendSubmit').on(TAP, function () {
           var filter = x$('#friendName')[0].value;
           alert('I entered the third function');
           if (!filter)
            {
            alert('Cant find contacts');
                // no contents
                return;
            } 
           else 
           {
              findContactByName(filter, function (contacts) 
              {
   alert(contacts.length + ' contact(s) found matching "' +filter + '"');
  }
); }               
  }); });
  function findContactByName(name, callback) {
       function onError() {
           alert('Error: unable to read contacts');
       };
       var fields = ["displayName", "name"],
           options = new ContactFindOptions();
       options.filter = name;
       options.multiple = true;
       // find contacts
       navigator.service.contacts.find(fields, callback, onError,
       options);
     }

没有任何警报被提醒,所以代码中似乎有问题(但是当我删除"findContactByName"函数时,它发出了警报。

你知道我是否应该添加任何类型的插件,或更新任何东西以便这些功能可以工作吗?我正在使用 cordova 版本 1.6.1,我更新了清单上的权限以便能够访问联系人。那么,你知道我的代码出了什么问题,为什么它不起作用吗?

多谢。

您是否正在等待设备就绪事件(已加载 PhoneGap)?

以下代码适用于我将带有姓名字段的所有联系人放入名称数组中:

function onDeviceReady() {
    // specify contact search criteria
    var options = new ContactFindOptions();
    options.filter="";          // empty search string returns all contacts
    options.multiple=true;      // return multiple results
    filter = ["displayName"];   // return contact.displayName field
    // find contacts
    navigator.contacts.find(filter, onSuccess, onError, options);
}
var names = [];
// onSuccess: Get a snapshot of the current contacts
//
function onSuccess(contacts) {
    for (var i=0; i<contacts.length; i++) {
        if (contacts[i].displayName) {  // many contacts don't have displayName
            names.push(contacts[i].displayName);
        }
    }
    alert('contacts loaded');
}

您正在处理一个旧示例:

navigator.service.contacts.find(fields, callback, onError, options);

在相当多的版本中,这不是呼叫联系人的正确方式。用:

navigator.contacts.find(fields, callback, onError, options);

相反。