如何動态擷取手機聯系人資訊
架構選擇為比較流行的JQuery Mobile
添加cordova插件:cordova plugin add cordova-plugin-contacts
一、html檔案代碼
- 為了提高頁面加載速度,html代碼建議盡量寫簡潔,為此我采用動态加載清單的方法來實作。
- 代碼為:
<div data-role="content"> //建立一個容器
<ul data-role="listview" id="listv" data-filter="true"> //建立清單項,data-filer=“true”添加一個搜尋框
</ul>
</div>
- 注:引用JQ Mobile時,必須按順序先導入jQ檔案,再導入JQ Mobile檔案。
二、js檔案代碼
document.addEventListener("deviceready",onDeviceReady,false);
dfunction onDeviceReady(){
console.log("ready...");
$(document).on("pageshow","#page1",function(){ console.log("page2.ok...");
addList();
}); //#page1為頁面id,加載成功後調用addList()函數
$("#listv").on("click", "li a:nth-of-type(2)", function () { //打電話
var phone = $(this).prev().children("p").html();
window.plugins.CallNumber.callNumber(onsuccess, onerror, phone, true);
function onsuccess() { console.log("ok..."); }
function onerror() { console.log("error..."); }
});
function addList(){
$("#listv").empty(); //清空清單,重新加載
console.log("addList.ok...");
var fields=["displayName"];
var options=new ContactFindOptions();
options.filter="";
options.multiple=true;
navigator.contacts.find(fields,onsuccess,onerror,options);
function onsuccess(contacts){
for(var i=0;i<contacts.length;i++){
var name=contacts[i].name.familyName+contacts[i].name.givenName;
if(contacts[i].phoneNumbers!==null){
var phone=contacts[i].phoneNumbers[0].value;
$("#listv").prepend("<li><a href=><h1>"+name+"</h1><p>"+phone +"</p></a><a href='' data-icon='phone'></a></li>");
}
}
$("#listv").listview("refresh"); //重新整理清單
}
function onerror(){console.log("error...");}
}