2012-04-22 69 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