Cordova 3.x 基础(7) -- Native API的使用

来源:互联网 发布:什么是好的相声知乎 编辑:程序博客网 时间:2024/04/30 23:27
移动设备的Hardware接口包括:Accelerometer、Camera、Capture、Compass、Connection、Contacts、Device、Native Events、File、Geolocation、Notification、Storage、Gestures/Multitouch、Messages/Telephone、Bluetooth、NFC、Vibration。Cordova的Native API接口调用很简单,这里列举一下常用的API调用方法,由于Cordova只是个Container,所以UI使用jQuery Mobile(Single Page、脚本嵌入page div内部)。使用“Cordova :3.4.0、 Andorid :4.1.1”平台测试通过。完整的源代码:www.rar,Android APK文件:CordovaSample-debug-unaligned.apk 

(1)主页面 
Html代码  收藏代码
  1. <!-- Main -->  
  2. <div data-role="page" id="main">  
  3.   <div data-role="header">  
  4.     <h1>Cordova Sample</h1>   
  5.   </div>  
  6.   <div data-role="content">  
  7.     <ul data-role="listview">  
  8.       <li><a href="#accelerometer" data-transition="slide">Accelerometer</a></li>  
  9.       <li><a href="#camera" data-transition="slide">Camera</a></li>  
  10.       <li><a href="#compass" data-transition="slide">Compass</a></li>  
  11.       <li><a href="#connection" data-transition="slide">Connection</a></li>  
  12.       <li><a href="#device" data-transition="slide">Device</a></li>  
  13.       <li><a href="#geolocation" data-transition="slide">Geolocation</a></li>  
  14.       <li><a href="#notification" data-transition="slide">Notification</a></li>  
  15.       <li><a href="#contacts" data-transition="slide">Contacts</a></li>  
  16.       <li><a href="#file" data-transition="slide">File</a></li>  
  17.       <li><a href="#inAppBrowser" data-transition="slide">InAppBrowser</a></li>  
  18.       <li><a href="#storage" data-transition="slide">Storage</a></li>  
  19.       <li><a href="#database" data-transition="slide">Database</a></li>  
  20.     </ul>  
  21.   </div>  
  22. </div>  

 

(2)Accelerometer(加速计传感器) 
Html代码  收藏代码
  1. <!-- Accelerometer   
  2.       $ cordova plugin add org.apache.cordova.device-motion  
  3. -->  
  4. <div data-role="page" id="accelerometer">  
  5.   <div data-role="header">  
  6.     <a data-role="button" data-rel="back" data-direction="reverse" data-icon="arrow-l">Back</a>  
  7.     <h1>Accelerometer</h1>   
  8.   </div>  
  9.   <div data-role="content">  
  10.       <a href="#" data-role="button" id="startWatch">Start Watching</a><br>  
  11.       <a href="#" data-role="button" id="stopWatch">Stop Watching</a><br>  
  12.       <div id="accvals">Waiting for accelerometer...</div>  
  13.       <br><br>  
  14.       <a href="#" data-role="button" id="startWatchOrientation">Start Watch Orientation</a><br>  
  15.       <a href="#" data-role="button" id="stopWatchOrientation">Stop Watch Orientation</a><br>  
  16.       <div id="orivals">Waiting for orientation...</div>  
  17.   </div>  
  18.   <script type="text/javascript">  
  19.     var watchID = null;  
  20.   
  21.     document.addEventListener('deviceready', onDeviceReady, false);  
  22.     function onDeviceReady() {  
  23.       $("#startWatch").on("click", startWatch);  
  24.       $("#stopWatch").on("click", stopWatch);  
  25.       $("#startWatchOrientation").on("click", startWatchOrientation);  
  26.       $("#stopWatchOrientation").on("click", stopWatchOrientation);  
  27.     }  
  28.   
  29.     function startWatch() {  
  30.       alert("startWatch");  
  31.   
  32.       var options = { frequency: 3000 };  
  33.       watchID = navigator.accelerometer.watchAcceleration(onAccelSuccess, onAccelError, options);  
  34.     }  
  35.   
  36.     function stopWatch() {  
  37.       alert("stopWatch");  
  38.   
  39.       if (watchID) {  
  40.         navigator.accelerometer.clearWatch(watchID);  
  41.         watchID = null;  
  42.       }  
  43.     }  
  44.   
  45.     function onAccelSuccess(acceleration) {  
  46.       var element = document.getElementById('accvals');  
  47.       element.innerHTML = '<strong>Accel X:</strong> ' + acceleration.x.toFixed(1) * -1 + '<br />' +  
  48.                           '<strong>Accel Y:</strong> ' + acceleration.y.toFixed(1) + '<br />' +  
  49.                           '<strong>Accel Z:</strong> ' + acceleration.z.toFixed(1) + '<br />' +  
  50.                           '<strong>Timestamp:</strong> ' + acceleration.timestamp + '<br />';  
  51.     }  
  52.   
  53.     function onAccelError() {  
  54.       alert('Could not Retrieve Accelerometer Data!');  
  55.     }  
  56.   
  57.     function deviceOrientationEvent(eventData) {  
  58.       var alpha = Math.round(eventData.alpha);  
  59.       var beta = Math.round(eventData.beta);  
  60.       var gamma = Math.round(eventData.gamma);  
  61.       var element = document.getElementById('orivals');  
  62.       element.innerHTML = ("alpha = " + alpha + " beta = " + beta + " gamma = " + gamma);  
  63.     }  
  64.     function startWatchOrientation() {  
  65.       alert("startWatchOrientation");  
  66.       window.addEventListener('deviceorientation', deviceOrientationEvent);  
  67.     }  
  68.     function stopWatchOrientation() {  
  69.       alert("stopWatchOrientation");  
  70.       window.removeEventListener('deviceorientation', deviceOrientationEvent);  
  71.     }  
  72.   </script>  
  73. </div>  

 

(3)Camera(摄像头) 
Html代码  收藏代码
  1. <!-- Camera   
  2.       $ cordova plugin add org.apache.cordova.camera  
  3. -->  
  4. <div data-role="page" id="camera">  
  5.   <div data-role="header">  
  6.     <a data-role="button" data-rel="back" data-direction="reverse" data-icon="arrow-l">Back</a>  
  7.     <h1>Camera</h1>   
  8.   </div>  
  9.   <div data-role="content">  
  10.       <a href="#" data-role="button" id="capturePhoto">Capture Photo</a><br>  
  11.       <img style="display:none;" id="smallImage" src="" /><p id="smTitle"></p>  
  12.       <a href="#" data-role="button" id="browsePhoto">Browse Photo Album</a><br>  
  13.       <img style="display:none;" id="largeImage" src="" /><p id="lgTitle"></p>  
  14.   </div>  
  15.   <script type="text/javascript">  
  16.     var pictureSource;  
  17.     var destinationType; //  
  18.   
  19.     document.addEventListener('deviceready', onDeviceReady, false);  
  20.     function onDeviceReady() {  
  21.       pictureSource = navigator.camera.PictureSourceType;  
  22.       destinationType = navigator.camera.DestinationType;  
  23.   
  24.       $("#capturePhoto").on("click", capturePhoto);  
  25.       $("#browsePhoto").on("click", browsePhoto);  
  26.     }  
  27.   
  28.     function capturePhoto() {  
  29.       alert("capturePhoto");  
  30.   
  31.       if (!navigator.camera) {  
  32.           alert("Camera API not supported", "Error");  
  33.           return;  
  34.       }  
  35.       navigator.camera.getPicture(onPhotoDataSuccess, onFail,   
  36.           { quality: 50,   
  37.             allowEdit: true,   
  38.             destinationType: destinationType.DATA_URL });  
  39.     }  
  40.   
  41.     function browsePhoto() {  
  42.       alert("browsePhoto");  
  43.   
  44.       navigator.camera.getPicture(onPhotoURISuccess, onFail,   
  45.           { quality: 50,  
  46.             destinationType: destinationType.FILE_URI,  
  47.             sourceType: pictureSource.PHOTOLIBRARY });  
  48.     }  
  49.     //sourceType 0:Photo Library, 1=Camera2=Saved Album  
  50.     //encodingType 0=JPG 1=PNG  
  51.   
  52.     function onFail(message) {  
  53.       alert('Response: ' + message);  
  54.     }  
  55.   
  56.     function onPhotoDataSuccess(imageData) {  
  57.       var smallImage = document.getElementById('smallImage');  
  58.       smallImage.style.display = 'block';  
  59.       smallImage.src = "data:image/jpeg;base64," + imageData;  
  60.     }  
  61.   
  62.     function onPhotoURISuccess(imageURI) {  
  63.       var largeImage = document.getElementById('largeImage');  
  64.       largeImage.style.display = 'block';  
  65.       largeImage.src = imageURI;  
  66.     }  
  67.   </script>  
  68. </div>  

 

(4)Compass(罗盘) 
Html代码  收藏代码
  1. <!-- Compass   
  2.       $ cordova plugin add org.apache.cordova.device-orientation  
  3. -->  
  4. <div data-role="page" id="compass">  
  5.   <div data-role="header">  
  6.     <a data-role="button" data-rel="back" data-direction="reverse" data-icon="arrow-l">Back</a>  
  7.     <h1>Compass</h1>   
  8.   </div>  
  9.   <div data-role="content">  
  10.       <a href="#" data-role="button" id="startWatchCompass">Start Watch Compass</a><br>  
  11.       <a href="#" data-role="button" id="stopWatchCompass">Stop Watch Compass</a><br>  
  12.       <div id="heading">Waiting for heading...</div>  
  13.   </div>  
  14.   <script type="text/javascript">  
  15.     var watchIDCompass = null;  
  16.   
  17.     document.addEventListener("deviceready", onDeviceReady, false);  
  18.     function onDeviceReady() {  
  19.       $("#startWatchCompass").on("click", startWatchCompass);  
  20.       $("#stopWatchCompass").on("click", stopWatchCompass);  
  21.     }  
  22.     function startWatchCompass() {  
  23.       alert("startWatchCompass");  
  24.   
  25.       var options = { frequency: 3000 };  
  26.       watchIDCompass = navigator.compass.watchHeading(onCompassSuccess, onCompassError, options);  
  27.     }  
  28.     function stopWatchCompass() {  
  29.       alert("stopWatchCompass");  
  30.   
  31.       if (watchIDCompass) {  
  32.         navigator.compass.clearWatchCompass(watchIDCompass);  
  33.         watchIDCompass = null;  
  34.       }  
  35.     }  
  36.     function onCompassSuccess(heading) {  
  37.      var element = document.getElementById('heading');  
  38.       element.innerHTML = 'Current Heading: ' + (heading.magneticHeading).toFixed(2);  
  39.     }  
  40.     function onCompassError(compassError) {  
  41.       alert('Compass error: ' + compassError.code);  
  42.     }  
  43.   </script>  
  44. </div>  

 

(5)Connection(网络连接状态) 
Html代码  收藏代码
  1. <!-- Connection   
  2.       $ cordova plugin add org.apache.cordova.network-information  
  3. -->  
  4. <div data-role="page" id="connection">  
  5.   <div data-role="header">  
  6.     <a data-role="button" data-rel="back" data-direction="reverse" data-icon="arrow-l">Back</a>  
  7.     <h1>Connection</h1>   
  8.   </div>  
  9.   <div data-role="content">  
  10.       <a href="#" data-role="button" id="checkConnection">Check Connection</a><br>  
  11.       <div id="connectiontype">Waiting for Connection type...</div>  
  12.   </div>  
  13.   <script type="text/javascript">  
  14.     document.addEventListener("deviceready", onDeviceReady, false);  
  15.     function onDeviceReady() {  
  16.       $("#checkConnection").on("click", checkConnection);  
  17.     }  
  18.   
  19.     function checkConnection() {  
  20.       alert("checkConnection");  
  21.   
  22.       var networkState = navigator.connection.type;  
  23.       var states = {};  
  24.       states[Connection.UNKNOWN] = 'Unknown connection';  
  25.       states[Connection.ETHERNET] = 'Ethernet connection';  
  26.       states[Connection.WIFI] = 'WiFi connection';  
  27.       states[Connection.CELL_2G] = 'Cell 2G connection';  
  28.       states[Connection.CELL_3G] = 'Cell 3G connection';  
  29.       states[Connection.CELL_4G] = 'Cell 4G connection';  
  30.       states[Connection.CELL] = 'Cell generic connection';  
  31.       states[Connection.NONE] = 'No network connection';  
  32.   
  33.       var element = document.getElementById('connectiontype');  
  34.       element.innerHTML = 'Connection type: ' + states[networkState];  
  35.     }  
  36.   </script>  
  37. </div>  

 

(6)Device(设备信息) 
Html代码  收藏代码
  1. <!-- Device   
  2.        $ cordova plugin add org.apache.cordova.device  
  3. -->  
  4. <div data-role="page" id="device">  
  5.   <div data-role="header">  
  6.     <a data-role="button" data-rel="back" data-direction="reverse" data-icon="arrow-l">Back</a>  
  7.     <h1>Device</h1>   
  8.   </div>  
  9.   <div data-role="content">  
  10.       <a href="#" data-role="button" id="getDeviceProperties">Get Device Properties</a><br>  
  11.       <div id="deviceProperties">Loading device properties...</div>  
  12.   </div>  
  13.   <script type="text/javascript">  
  14.     document.addEventListener("deviceready", onDeviceReady, false);  
  15.     function onDeviceReady() {  
  16.       $("#getDeviceProperties").on("click", getDeviceProperties);  
  17.     }  
  18.   
  19.     function getDeviceProperties() {  
  20.        alert("getDeviceProperties");  
  21.   
  22.        var element = document.getElementById('deviceProperties');  
  23.        element.innerHTML = 'Device Model (Android: product name): ' + device.model + '<br />' +  
  24.        'Cordova version: ' + device.cordova + '<br />' +  
  25.        'Operating system: ' + device.platform + '<br />' +  
  26.        'Device UUID: ' + device.uuid + '<br />' +  
  27.        'Operating system version: ' + device.version + '<br />';  
  28.     }  
  29.   </script>  
  30. </div>  

 

(7)Geolocation(GPS地理位置服务) 
Html代码  收藏代码
  1. <!-- Geolocation   
  2.       $ cordova plugin add org.apache.cordova.geolocation  
  3. -->  
  4. <div data-role="page" id="geolocation">  
  5.   <div data-role="header">  
  6.     <a data-role="button" data-rel="back" data-direction="reverse" data-icon="arrow-l">Back</a>  
  7.     <h1>Geolocation</h1>   
  8.   </div>  
  9.   <div data-role="content">  
  10.     <a href="#" data-role="button" id="startGeolocationg">Start Geolocationg</a><br>  
  11.     <a href="#" data-role="button" id="stopGeolocationg">Stop Geolocation</a><br>  
  12.     <br><br>  
  13.     <a href="#" data-role="button" id="getCurrentPosition">Get Current Position </a><br>  
  14.     <div id="geovals">Waiting for geolocation...</div>  
  15.   </div>  
  16.   <script type="text/javascript">  
  17.     var watchGeoID = null;  
  18.   
  19.     document.addEventListener("deviceready", onDeviceReady, false);  
  20.     function onDeviceReady() {  
  21.       $("#startGeolocationg").on("click", startGeolocationg);  
  22.       $("#stopGeolocationg").on("click", stopGeolocationg);  
  23.       $("#getCurrentPosition").on("click", getCurrentPosition);  
  24.     }  
  25.   
  26.     function startGeolocationg() {  
  27.       alert('startGeolocationg');  
  28.       var element = document.getElementById('geovals');  
  29.       element.innerHTML = 'Finding geolocation every 30 seconds...'  
  30.       var options = { enableHighAccuracy: true, timeout: 30000 };  
  31.       watchGeoID = navigator.geolocation.watchPosition(onGeoSuccess, onGeoError, options);  
  32.     }  
  33.   
  34.     function onGeoSuccess(position) {  
  35.       var element = document.getElementById('geovals');  
  36.       element.innerHTML =   
  37.       '<strong>Latitude:</strong> ' + position.coords.latitude + '<br />' +  
  38.       '<strong>Longitude: </strong> ' + position.coords.longitude + ' <br />' +  
  39.       '<strong>Altitude</strong> (in meters): ' + position.coords.altitude + ' <br />' +  
  40.       '<strong>Accuracy</strong> (in meters): ' + position.coords.accuracy + ' <br />' +  
  41.       '<strong>Altitude Accuracy:</strong> ' + position.coords.altitudeAccuracy + ' <br />' +  
  42.       '<strong>Heading</strong> (direction of travel): ' + position.coords.heading + ' <br />' +  
  43.       '<strong>Speed</strong> (meters per second): ' + position.coords.speed + ' <br />' +  
  44.       '<strong>Timestamp:</strong> ' + position.timestamp + ' <br />';  
  45.     }  
  46.     function onGeoError(error) {  
  47.       var element = document.getElementById('geovals');  
  48.       element.innerHTML =+ '<br>' + error.code + error.message;  
  49.     }  
  50.   
  51.     function stopGeolocationg() {  
  52.       alert('stopGeolocationg');  
  53.   
  54.       var element = document.getElementById('geovals');  
  55.       element.innerHTML = '<span style="color:red">Geolocation turned off.</span>';  
  56.       if (watchGeoID) {  
  57.         navigator.geolocation.clearWatch(watchGeoID);  
  58.         watchGeoID = null;  
  59.       }  
  60.     }  
  61.   
  62.     function getCurrentPosition() {  
  63.       alert('getCurrentPosition');  
  64.       navigator.geolocation.getCurrentPosition(onPositionSuccess, onPositionError);  
  65.     }  
  66.     function onPositionSuccess(position) {  
  67.       var element = document.getElementById('geovals');  
  68.       element.innerHTML =+ ('Latitude: ' + position.coords.latitude + '\n' +   
  69.                             'Longitude: ' + position.coords.longitude + '\n');   
  70.     };  
  71.     function onPositionError(error) {  
  72.       var element = document.getElementById('geovals');  
  73.       element.innerHTML =+('Error getting GPS Data');  
  74.     }  
  75.   </script>  
  76. </div>  

 

(8)Notification(消息提示) 
Html代码  收藏代码
  1. <!-- Notification   
  2.       $ cordova plugin add org.apache.cordova.dialogs  
  3.       $ cordova plugin add org.apache.cordova.vibration  
  4. -->  
  5. <div data-role="page" id="notification">  
  6.   <div data-role="header">  
  7.     <a data-role="button" data-rel="back" data-direction="reverse" data-icon="arrow-l">Back</a>  
  8.     <h1>Notification</h1>   
  9.   </div>  
  10.   <div data-role="content">  
  11.     <a href="#" data-role="button" id="showAlert">Show Alert popup</a><br>  
  12.     <a href="#" data-role="button" id="showConfirm">Show Confirm popup</a><br>  
  13.     <a href="#" data-role="button" id="showPrompt">Show Prompt popup</a><br>  
  14.     <br><br>  
  15.     <a href="#" data-role="button" id="playBeep">Play Beep sound</a><br>  
  16.     <a href="#" data-role="button" id="vibrate">Vibrate the device</a><br>  
  17.   </div>  
  18.   <script type="text/javascript">  
  19.     var watchGeoID = null;  
  20.   
  21.     document.addEventListener("deviceready", onDeviceReady, false);  
  22.     function onDeviceReady() {  
  23.       $("#showAlert").on("click", showAlert);  
  24.       $("#showConfirm").on("click", showConfirm);  
  25.       $("#showPrompt").on("click", showPrompt);  
  26.       $("#playBeep").on("click", playBeep);  
  27.       $("#vibrate").on("click", vibrate);  
  28.     }  
  29.   
  30.     function showAlert() {  
  31.       navigator.notification.alert(  
  32.         'Alert dialog: You are on fire!',  
  33.         alertDismissed, //callback  
  34.         'Game Over',  
  35.         'Done'  
  36.       );  
  37.     }  
  38.     /*  
  39.     // Override default HTML alert with native dialog  
  40.     document.addEventListener('deviceready', function () {  
  41.         if (navigator.notification) {   
  42.             window.alert = function (message) {  
  43.                 navigator.notification.alert(  
  44.                     message,  
  45.                     null,  
  46.                     "My App",  
  47.                     'OK'  
  48.                 );  
  49.             };  
  50.         }  
  51.     }, false);  
  52.     */  
  53.     function alertDismissed() {  
  54.       alert('You dismissed the Alert.');  
  55.     }  
  56.     function onConfirm(buttonIndex) {  
  57.       alert('You selected button ' + buttonIndex + '\n(button 1 = Restart, button 2 = Exit.)');  
  58.     }  
  59.     function showConfirm() {  
  60.       navigator.notification.confirm(  
  61.         'Confirm dialog: You are the winner!',  
  62.         onConfirm,  
  63.         'Game Over',  
  64.         ['Restart','Exit']  
  65.       );  
  66.     }  
  67.     function onPrompt(results) {  
  68.       alert("You selected button number " + results.buttonIndex + " and entered " + results.input1 + '\n(button 2 = Exit, button 1 = OK.)');  
  69.     }  
  70.     function showPrompt() {  
  71.       navigator.notification.prompt(  
  72.         'Please enter your name',  
  73.         onPrompt,  
  74.         'Registration',  
  75.         ['Ok','Exit'],  
  76.         'Jane Doe?'  
  77.       );  
  78.     }  
  79.     function playBeep() {  
  80.       navigator.notification.beep(3);  
  81.     }  
  82.     function vibrate() {  
  83.       navigator.notification.vibrate(2000);  
  84.     }  
  85.   </script>  
  86. </div>  

 

(9)Contacts(联系人) 
Html代码  收藏代码
  1. <!-- Contacts   
  2.         $ cordova plugin add org.apache.cordova.contacts  
  3. -->  
  4. <div data-role="page" id="contacts">  
  5.   <div data-role="header">  
  6.     <a data-role="button" data-rel="back" data-direction="reverse" data-icon="arrow-l">Back</a>  
  7.     <h1>Contacts</h1>   
  8.   </div>  
  9.   <div data-role="content">  
  10.     <label for="fname">First Name:</label>  
  11.     <input type="text" name="fname" id="fname" value="REN"><br>  
  12.     <label for="lname">Last Name:</label>  
  13.     <input type="text" name="lname" id="lname" value="SANNING"><br>  
  14.     <label for="email">Email:</label>  
  15.     <input type="text" name="email" id="email" value="rensanning@gmail.com"><br>  
  16.     <label for="tel">TEL:</label>  
  17.     <input type="text" name="tel" id="tel" value="18812345678"><br>  
  18.     <br>  
  19.     <a href="#" data-role="button" id="saveContacts">Save</a><br>  
  20.   </div>  
  21.   <script type="text/javascript">  
  22.   
  23.     document.addEventListener("deviceready", onDeviceReady, false);  
  24.     function onDeviceReady() {  
  25.       $("#saveContacts").on("click", saveContacts);  
  26.     }  
  27.   
  28.     function saveContacts() {  
  29.       alert('saveContacts');  
  30.   
  31.       if (!navigator.contacts) {  
  32.           alert("Contacts API not supported", "Error");  
  33.           return;  
  34.       }  
  35.       var contact = navigator.contacts.create();  
  36.       var name = new ContactName();  
  37.       name.givenName = $('#fname').val();  
  38.       name.familyName = $('#lname').val();  
  39.       contact.name = name;  
  40.       contact.displayName = $('#fname').val() + " " + $('#lname').val();  
  41.       contact.emails = [new ContactField('home', $('#email').val(), false)];  
  42.       contact.phoneNumbers = [new ContactField('home', $('#tel').val(), false)];  
  43.       contact.save(  
  44.         function() {  
  45.           alert("OK!");  
  46.         },  
  47.         function() {  
  48.           alert("Error!");  
  49.         }  
  50.       );  
  51.     }  
  52.   </script>  
  53. </div>  

 

(10)File(文件系统处理 ) 
Html代码  收藏代码
  1. <!-- File   
  2.         $ cordova plugin add org.apache.cordova.file  
  3.         $ cordova plugin add org.apache.cordova.file-transfer  
  4. -->  
  5. <div data-role="page" id="file">  
  6.   <div data-role="header">  
  7.     <a data-role="button" data-rel="back" data-direction="reverse" data-icon="arrow-l">Back</a>  
  8.     <h1>File</h1>   
  9.   </div>  
  10.   <div data-role="content">  
  11.     <input type="text" id="userInput" name="userInput" value="I'm rensanning."><br>  
  12.     <a href="#" data-role="button" id="writeToFile">Write To File</a><br>  
  13.   
  14.     <a href="#" data-role="button" id="readFile">Read File</a><br>  
  15.     <p id="data1"></p><p id="data2"></p><br>  
  16.   
  17.     <a href="#" data-role="button" id="deleteFile">Delete File</a><br>  
  18.   </div>  
  19.   <script type="text/javascript">  
  20.   
  21.     document.addEventListener("deviceready", onDeviceReady, false);  
  22.     function onDeviceReady() {  
  23.       $("#writeToFile").on("click", writeToFile);  
  24.       $("#readFile").on("click", readFile);  
  25.       $("#deleteFile").on("click", deleteFile);  
  26.     }  
  27.   
  28.     function writeToFile() {  
  29.       window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFSForWrite, fail);  
  30.     }  
  31.     function gotFSForWrite(fileSystem) {  
  32.       fileSystem.root.getFile("CordovaSample.txt", {create: true, exclusive: false}, gotWriteFileEntry, fail);  
  33.     }  
  34.     function gotWriteFileEntry(fileEntry) {  
  35.       fileEntry.createWriter(gotFileWriter, fail);  
  36.     }  
  37.     function gotFileWriter(writer) {  
  38.      var userText = $('#userInput').val();  
  39.      writer.seek(writer.length);  
  40.      writer.write('\n\n' + userText);  
  41.      writer.onwriteend = function(evt){  
  42.        alert("You wrote ' " + userText + " ' at the end of the file.");  
  43.      }   
  44.      $('#userInput').val("");  
  45.     }  
  46.   
  47.     function readFile() {  
  48.       window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFSForRead, fail);  
  49.     }  
  50.     function gotFSForRead(fileSystem) {  
  51.       fileSystem.root.getFile("CordovaSample.txt", null, gotReadFileEntry, fail);  
  52.     }  
  53.     function gotReadFileEntry(fileEntry) {  
  54.       fileEntry.file(gotFileRead, fail);  
  55.     }  
  56.     function gotFileRead(file){  
  57.       readDataUrl(file);  
  58.       readAsText(file);  
  59.     }  
  60.     function readDataUrl(file) {  
  61.       var reader = new FileReader();  
  62.       reader.onloadend = function(evt) {  
  63.         var element = document.getElementById('data1');  
  64.         element.innerHTML = '<strong>Read as data URL:</strong> <br><pre>' + evt.target.result + '</pre>';  
  65.       };  
  66.       reader.readAsDataURL(file);  
  67.     }  
  68.     function readAsText(file) {  
  69.       var reader = new FileReader();  
  70.       reader.onloadend = function(evt) {  
  71.         var element = document.getElementById('data2');  
  72.         element.innerHTML = '<strong>Read as data text:</strong> <br><pre>' + evt.target.result + '</pre>';  
  73.       };  
  74.       reader.readAsText(file);  
  75.     }  
  76.   
  77.     function deleteFile() {  
  78.       window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFSForRemove, fail);  
  79.     }  
  80.     function gotFSForRemove(fileSystem) {  
  81.       fileSystem.root.getFile("CordovaSample.txt", {create: false, exclusive: false}, gotRemoveFileEntry, fail);  
  82.     }  
  83.     function gotRemoveFileEntry(fileEntry){  
  84.       fileEntry.remove(  
  85.         function(entry) {  
  86.           alert("Removal succeeded");  
  87.         },   
  88.         function(error) {  
  89.           alert("Error removing file: " + error.code);  
  90.       });  
  91.     }  
  92.   
  93.     function fail(error) {  
  94.       alert(error.code);  
  95.     }  
  96.   </script>  
  97. </div>  

 

(11)InAppBrowser(Web浏览) 
Html代码  收藏代码
  1. <!-- InAppBrowser  
  2.         $ cordova plugin add org.apache.cordova.inappbrowser  
  3. -->  
  4. <div data-role="page" id="inAppBrowser">  
  5.   <div data-role="header">  
  6.     <a data-role="button" data-rel="back" data-direction="reverse" data-icon="arrow-l">Back</a>  
  7.     <h1>InAppBrowser</h1>   
  8.   </div>  
  9.   <div data-role="content">  
  10.     <label for="url">URL:</label>  
  11.     <input type="text" id="url" name="url" value="http://www.baidu.com"><br>  
  12.     <a href="#" data-role="button" id="openURL">Open URL</a><br>  
  13.   </div>  
  14.   <script type="text/javascript">  
  15.     document.addEventListener("deviceready", onDeviceReady, false);  
  16.     function onDeviceReady() {  
  17.       $("#openURL").on("click", openURL);  
  18.     }  
  19.   
  20.     function openURL() {  
  21.       alert('openURL');  
  22.   
  23.       var ref = window.open($('#url').val(), '_blank', 'location=yes');  
  24.       ref.addEventListener('loadstart', function(event) { alert('start: ' + event.url); });  
  25.       ref.addEventListener('loadstop', function(event) { alert('stop: ' + event.url); });  
  26.       ref.addEventListener('loaderror', function(event) { alert('error: ' + event.message); });  
  27.       ref.addEventListener('exit', function(event) { alert(event.type); });  
  28.     }  
  29.   </script>  
  30. </div>  

     

(12)Storage(数据存储) 
Html代码  收藏代码
  1. <!-- Storage -->  
  2. <div data-role="page" id="storage">  
  3.   <div data-role="header">  
  4.     <a data-role="button" data-rel="back" data-direction="reverse" data-icon="arrow-l">Back</a>  
  5.     <h1>Storage</h1>   
  6.   </div>  
  7.   <div data-role="content">  
  8.     <label for="key">Key:</label>  
  9.     <input type="text" id="key" name="key" value="item_name"><br>  
  10.     <label for="val">Value:</label>  
  11.     <input type="text" id="val" name="val" value="item_value"><br>  
  12.     <a href="#" data-role="button" id="saveItem">Save Item</a><br>  
  13.     <a href="#" data-role="button" id="getItem">Get Item</a><br>  
  14.     <a href="#" data-role="button" id="deleteItem">Delete Item</a><br>  
  15.   </div>  
  16.   <script type="text/javascript">  
  17.     document.addEventListener("deviceready", onDeviceReady, false);  
  18.     function onDeviceReady() {  
  19.       $("#saveItem").on("click", saveItem);  
  20.       $("#getItem").on("click", getItem);  
  21.       $("#deleteItem").on("click", deleteItem);  
  22.     }  
  23.   
  24.     function saveItem() {  
  25.       alert('saveItem');  
  26.       window.localStorage.setItem($('#key').val(), $('#val').val());  
  27.     }  
  28.     function getItem() {  
  29.       alert('getItem');  
  30.       var item_value = window.localStorage.getItem($('#key').val());  
  31.       alert(item_value);  
  32.     }  
  33.     function deleteItem() {  
  34.       alert('deleteItem');  
  35.       window.localStorage.removeItem($('#key').val());  
  36.     }  
  37.   </script>  
  38. </div>  

 

(13)Database(客户端数据库) 
Html代码  收藏代码
  1. <!-- Database -->  
  2. <div data-role="page" id="database">  
  3.   <div data-role="header">  
  4.     <a data-role="button" data-rel="back" data-direction="reverse" data-icon="arrow-l">Back</a>  
  5.     <h1>Database</h1>   
  6.   </div>  
  7.   <div data-role="content">  
  8.     <label for="id">ID:</label>  
  9.     <input type="text" id="id" name="id" value="12345"><br>  
  10.     <label for="data">Data:</label>  
  11.     <input type="text" id="data" name="data" value="Data Value"><br>  
  12.     <a href="#" data-role="button" id="saveToDatabase">Save To Database</a><br>  
  13.     <a href="#" data-role="button" id="getFromDatabase">Get From Database</a><br>  
  14.   </div>  
  15.   <script type="text/javascript">  
  16.     var db;  
  17.   
  18.     document.addEventListener("deviceready", onDeviceReady, false);  
  19.     function onDeviceReady() {  
  20.       $("#saveToDatabase").on("click", saveToDatabase);  
  21.       $("#getFromDatabase").on("click", getFromDatabase);  
  22.   
  23.       db = window.openDatabase("MyDatabase", "1.0", "Cordova Sample", 200000);  
  24.       db.transaction(function(tx) {  
  25.           tx.executeSql('DROP TABLE IF EXISTS MyTable');  
  26.           tx.executeSql('CREATE TABLE IF NOT EXISTS MyTable (id unique, data)');  
  27.         },   
  28.         function(err) {  
  29.           alert("Error processing SQL: " + err.code);  
  30.         });  
  31.     }  
  32.   
  33.     function saveToDatabase() {  
  34.       alert('saveToDatabase');  
  35.   
  36.       db.transaction(function(tx) {  
  37.         tx.executeSql("INSERT INTO MyTable (id, data) VALUES (?, ?)",  
  38.                       [$('#id').val(), $('#data').val()],  
  39.                       function(tx, rs) {  
  40.                           alert("Your SQLite query was successful!");  
  41.                       },  
  42.                       function(tx, e) {  
  43.                           alert("SQLite Error: " + e.message);  
  44.                       });  
  45.       });  
  46.     }  
  47.     function getFromDatabase() {  
  48.       alert('getFromDatabase');  
  49.   
  50.       db.transaction(function(tx) {  
  51.         tx.executeSql("SELECT id,data FROM MyTable ORDER BY id",  
  52.                       [],  
  53.                       function (tx, rs) {  
  54.                           for (var i = 0; i < rs.rows.length; i++) {  
  55.                               alert(rs.rows.item(i).id + "=" + rs.rows.item(i).data);  
  56.                           }  
  57.                       },  
  58.                       function(tx, e) {  
  59.                           alert("SQLite Error: " + e.message);  
  60.                       });  
  61.       });  
  62.     }  
  63.   </script>  
  64. </div>  

  • www.rar (581.8 KB)
  • 下载次数: 856
  • CordovaSample-debug-unaligned.rar (933.9 KB)
  • 下载次数: 478

0 0
原创粉丝点击