2012-04-22 68 views
4

我正在使用手机差距的应用程序。 我正尝试访问手机上的联系人,以后再使用它们。 我现在正在尝试编写代码以在移动设备上查找联系人。 下面是我使用的JS文件:在Android上使用Phonegap访问联系人

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,并且我更新了清单中的权限以便能够访问联系人。 那么,你知道我的代码有什么问题吗&为什么它不起作用?

非常感谢。

回答

6

你是否在等待deviceready事件(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'); 
} 
+0

它的工作,非常感谢=) – 2012-04-23 23:04:54

4

您正在从古老例如:

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

尚未正确的方式呼吁联系人的不少发布。使用方法:

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

改为。

+0

谢谢男人......这是最新版本的手机差距+10 :) – 2013-09-10 10:10:22

+0

iPhone也是这样吗? – dikkini 2014-06-12 11:17:19