`
rensanning
  • 浏览: 3552621 次
  • 性别: Icon_minigender_1
  • 来自: 大连
博客专栏
Efef1dba-f7dd-3931-8a61-8e1c76c3e39f
使用Titanium Mo...
浏览量:38217
Bbab2146-6e1d-3c50-acd6-c8bae29e307d
Cordova 3.x入门...
浏览量:607600
C08766e7-8a33-3f9b-9155-654af05c3484
常用Java开源Libra...
浏览量:682778
77063fb3-0ee7-3bfa-9c72-2a0234ebf83e
搭建 CentOS 6 服...
浏览量:89534
E40e5e76-1f3b-398e-b6a6-dc9cfbb38156
Spring Boot 入...
浏览量:402149
Abe39461-b089-344f-99fa-cdfbddea0e18
基于Spring Secu...
浏览量:69760
66a41a70-fdf0-3dc9-aa31-19b7e8b24672
MQTT入门
浏览量:91835
社区版块
存档分类
最新评论

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

阅读更多
移动设备的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)主页面
<!-- Main -->
<div data-role="page" id="main">
  <div data-role="header">
    <h1>Cordova Sample</h1> 
  </div>
  <div data-role="content">
    <ul data-role="listview">
      <li><a href="#accelerometer" data-transition="slide">Accelerometer</a></li>
      <li><a href="#camera" data-transition="slide">Camera</a></li>
      <li><a href="#compass" data-transition="slide">Compass</a></li>
      <li><a href="#connection" data-transition="slide">Connection</a></li>
      <li><a href="#device" data-transition="slide">Device</a></li>
      <li><a href="#geolocation" data-transition="slide">Geolocation</a></li>
      <li><a href="#notification" data-transition="slide">Notification</a></li>
      <li><a href="#contacts" data-transition="slide">Contacts</a></li>
      <li><a href="#file" data-transition="slide">File</a></li>
      <li><a href="#inAppBrowser" data-transition="slide">InAppBrowser</a></li>
      <li><a href="#storage" data-transition="slide">Storage</a></li>
      <li><a href="#database" data-transition="slide">Database</a></li>
    </ul>
  </div>
</div>



(2)Accelerometer(加速计传感器)
<!-- Accelerometer 
      $ cordova plugin add org.apache.cordova.device-motion
-->
<div data-role="page" id="accelerometer">
  <div data-role="header">
    <a data-role="button" data-rel="back" data-direction="reverse" data-icon="arrow-l">Back</a>
    <h1>Accelerometer</h1> 
  </div>
  <div data-role="content">
      <a href="#" data-role="button" id="startWatch">Start Watching</a><br>
      <a href="#" data-role="button" id="stopWatch">Stop Watching</a><br>
      <div id="accvals">Waiting for accelerometer...</div>
      <br><br>
      <a href="#" data-role="button" id="startWatchOrientation">Start Watch Orientation</a><br>
      <a href="#" data-role="button" id="stopWatchOrientation">Stop Watch Orientation</a><br>
      <div id="orivals">Waiting for orientation...</div>
  </div>
  <script type="text/javascript">
    var watchID = null;

    document.addEventListener('deviceready', onDeviceReady, false);
    function onDeviceReady() {
      $("#startWatch").on("click", startWatch);
      $("#stopWatch").on("click", stopWatch);
      $("#startWatchOrientation").on("click", startWatchOrientation);
      $("#stopWatchOrientation").on("click", stopWatchOrientation);
    }

    function startWatch() {
      alert("startWatch");

      var options = { frequency: 3000 };
      watchID = navigator.accelerometer.watchAcceleration(onAccelSuccess, onAccelError, options);
    }

    function stopWatch() {
      alert("stopWatch");

      if (watchID) {
        navigator.accelerometer.clearWatch(watchID);
        watchID = null;
      }
    }

    function onAccelSuccess(acceleration) {
      var element = document.getElementById('accvals');
      element.innerHTML = '<strong>Accel X:</strong> ' + acceleration.x.toFixed(1) * -1 + '<br />' +
                          '<strong>Accel Y:</strong> ' + acceleration.y.toFixed(1) + '<br />' +
                          '<strong>Accel Z:</strong> ' + acceleration.z.toFixed(1) + '<br />' +
                          '<strong>Timestamp:</strong> ' + acceleration.timestamp + '<br />';
    }

    function onAccelError() {
      alert('Could not Retrieve Accelerometer Data!');
    }

    function deviceOrientationEvent(eventData) {
      var alpha = Math.round(eventData.alpha);
      var beta = Math.round(eventData.beta);
      var gamma = Math.round(eventData.gamma);
      var element = document.getElementById('orivals');
      element.innerHTML = ("alpha = " + alpha + " beta = " + beta + " gamma = " + gamma);
    }
    function startWatchOrientation() {
      alert("startWatchOrientation");
      window.addEventListener('deviceorientation', deviceOrientationEvent);
    }
    function stopWatchOrientation() {
      alert("stopWatchOrientation");
      window.removeEventListener('deviceorientation', deviceOrientationEvent);
    }
  </script>
</div>



(3)Camera(摄像头)
<!-- Camera 
      $ cordova plugin add org.apache.cordova.camera
-->
<div data-role="page" id="camera">
  <div data-role="header">
    <a data-role="button" data-rel="back" data-direction="reverse" data-icon="arrow-l">Back</a>
    <h1>Camera</h1> 
  </div>
  <div data-role="content">
      <a href="#" data-role="button" id="capturePhoto">Capture Photo</a><br>
      <img style="display:none;" id="smallImage" src="" /><p id="smTitle"></p>
      <a href="#" data-role="button" id="browsePhoto">Browse Photo Album</a><br>
      <img style="display:none;" id="largeImage" src="" /><p id="lgTitle"></p>
  </div>
  <script type="text/javascript">
    var pictureSource;
    var destinationType; //

    document.addEventListener('deviceready', onDeviceReady, false);
    function onDeviceReady() {
      pictureSource = navigator.camera.PictureSourceType;
      destinationType = navigator.camera.DestinationType;

      $("#capturePhoto").on("click", capturePhoto);
      $("#browsePhoto").on("click", browsePhoto);
    }

    function capturePhoto() {
      alert("capturePhoto");

      if (!navigator.camera) {
          alert("Camera API not supported", "Error");
          return;
      }
      navigator.camera.getPicture(onPhotoDataSuccess, onFail, 
          { quality: 50, 
            allowEdit: true, 
            destinationType: destinationType.DATA_URL });
    }

    function browsePhoto() {
      alert("browsePhoto");

      navigator.camera.getPicture(onPhotoURISuccess, onFail, 
          { quality: 50,
            destinationType: destinationType.FILE_URI,
            sourceType: pictureSource.PHOTOLIBRARY });
    }
    //sourceType 0:Photo Library, 1=Camera, 2=Saved Album
    //encodingType 0=JPG 1=PNG

    function onFail(message) {
      alert('Response: ' + message);
    }

    function onPhotoDataSuccess(imageData) {
      var smallImage = document.getElementById('smallImage');
      smallImage.style.display = 'block';
      smallImage.src = "data:image/jpeg;base64," + imageData;
    }

    function onPhotoURISuccess(imageURI) {
      var largeImage = document.getElementById('largeImage');
      largeImage.style.display = 'block';
      largeImage.src = imageURI;
    }
  </script>
</div>



(4)Compass(罗盘)
<!-- Compass 
      $ cordova plugin add org.apache.cordova.device-orientation
-->
<div data-role="page" id="compass">
  <div data-role="header">
    <a data-role="button" data-rel="back" data-direction="reverse" data-icon="arrow-l">Back</a>
    <h1>Compass</h1> 
  </div>
  <div data-role="content">
      <a href="#" data-role="button" id="startWatchCompass">Start Watch Compass</a><br>
      <a href="#" data-role="button" id="stopWatchCompass">Stop Watch Compass</a><br>
      <div id="heading">Waiting for heading...</div>
  </div>
  <script type="text/javascript">
    var watchIDCompass = null;

    document.addEventListener("deviceready", onDeviceReady, false);
    function onDeviceReady() {
      $("#startWatchCompass").on("click", startWatchCompass);
      $("#stopWatchCompass").on("click", stopWatchCompass);
    }
    function startWatchCompass() {
      alert("startWatchCompass");

      var options = { frequency: 3000 };
      watchIDCompass = navigator.compass.watchHeading(onCompassSuccess, onCompassError, options);
    }
    function stopWatchCompass() {
      alert("stopWatchCompass");

      if (watchIDCompass) {
        navigator.compass.clearWatchCompass(watchIDCompass);
        watchIDCompass = null;
      }
    }
    function onCompassSuccess(heading) {
     var element = document.getElementById('heading');
      element.innerHTML = 'Current Heading: ' + (heading.magneticHeading).toFixed(2);
    }
    function onCompassError(compassError) {
      alert('Compass error: ' + compassError.code);
    }
  </script>
</div>



(5)Connection(网络连接状态)
<!-- Connection 
      $ cordova plugin add org.apache.cordova.network-information
-->
<div data-role="page" id="connection">
  <div data-role="header">
    <a data-role="button" data-rel="back" data-direction="reverse" data-icon="arrow-l">Back</a>
    <h1>Connection</h1> 
  </div>
  <div data-role="content">
      <a href="#" data-role="button" id="checkConnection">Check Connection</a><br>
      <div id="connectiontype">Waiting for Connection type...</div>
  </div>
  <script type="text/javascript">
    document.addEventListener("deviceready", onDeviceReady, false);
    function onDeviceReady() {
      $("#checkConnection").on("click", checkConnection);
    }

    function checkConnection() {
      alert("checkConnection");

      var networkState = navigator.connection.type;
      var states = {};
      states[Connection.UNKNOWN] = 'Unknown connection';
      states[Connection.ETHERNET] = 'Ethernet connection';
      states[Connection.WIFI] = 'WiFi connection';
      states[Connection.CELL_2G] = 'Cell 2G connection';
      states[Connection.CELL_3G] = 'Cell 3G connection';
      states[Connection.CELL_4G] = 'Cell 4G connection';
      states[Connection.CELL] = 'Cell generic connection';
      states[Connection.NONE] = 'No network connection';

      var element = document.getElementById('connectiontype');
      element.innerHTML = 'Connection type: ' + states[networkState];
    }
  </script>
</div>



(6)Device(设备信息)
<!-- Device 
       $ cordova plugin add org.apache.cordova.device
-->
<div data-role="page" id="device">
  <div data-role="header">
    <a data-role="button" data-rel="back" data-direction="reverse" data-icon="arrow-l">Back</a>
    <h1>Device</h1> 
  </div>
  <div data-role="content">
      <a href="#" data-role="button" id="getDeviceProperties">Get Device Properties</a><br>
      <div id="deviceProperties">Loading device properties...</div>
  </div>
  <script type="text/javascript">
    document.addEventListener("deviceready", onDeviceReady, false);
    function onDeviceReady() {
      $("#getDeviceProperties").on("click", getDeviceProperties);
    }

    function getDeviceProperties() {
       alert("getDeviceProperties");

       var element = document.getElementById('deviceProperties');
       element.innerHTML = 'Device Model (Android: product name): ' + device.model + '<br />' +
       'Cordova version: ' + device.cordova + '<br />' +
       'Operating system: ' + device.platform + '<br />' +
       'Device UUID: ' + device.uuid + '<br />' +
       'Operating system version: ' + device.version + '<br />';
    }
  </script>
</div>



(7)Geolocation(GPS地理位置服务)
<!-- Geolocation 
      $ cordova plugin add org.apache.cordova.geolocation
-->
<div data-role="page" id="geolocation">
  <div data-role="header">
    <a data-role="button" data-rel="back" data-direction="reverse" data-icon="arrow-l">Back</a>
    <h1>Geolocation</h1> 
  </div>
  <div data-role="content">
    <a href="#" data-role="button" id="startGeolocationg">Start Geolocationg</a><br>
    <a href="#" data-role="button" id="stopGeolocationg">Stop Geolocation</a><br>
    <br><br>
    <a href="#" data-role="button" id="getCurrentPosition">Get Current Position </a><br>
    <div id="geovals">Waiting for geolocation...</div>
  </div>
  <script type="text/javascript">
    var watchGeoID = null;

    document.addEventListener("deviceready", onDeviceReady, false);
    function onDeviceReady() {
      $("#startGeolocationg").on("click", startGeolocationg);
      $("#stopGeolocationg").on("click", stopGeolocationg);
      $("#getCurrentPosition").on("click", getCurrentPosition);
    }

    function startGeolocationg() {
      alert('startGeolocationg');
      var element = document.getElementById('geovals');
      element.innerHTML = 'Finding geolocation every 30 seconds...'
      var options = { enableHighAccuracy: true, timeout: 30000 };
      watchGeoID = navigator.geolocation.watchPosition(onGeoSuccess, onGeoError, options);
    }

    function onGeoSuccess(position) {
      var element = document.getElementById('geovals');
      element.innerHTML = 
      '<strong>Latitude:</strong> ' + position.coords.latitude + '<br />' +
      '<strong>Longitude: </strong> ' + position.coords.longitude + ' <br />' +
      '<strong>Altitude</strong> (in meters): ' + position.coords.altitude + ' <br />' +
      '<strong>Accuracy</strong> (in meters): ' + position.coords.accuracy + ' <br />' +
      '<strong>Altitude Accuracy:</strong> ' + position.coords.altitudeAccuracy + ' <br />' +
      '<strong>Heading</strong> (direction of travel): ' + position.coords.heading + ' <br />' +
      '<strong>Speed</strong> (meters per second): ' + position.coords.speed + ' <br />' +
      '<strong>Timestamp:</strong> ' + position.timestamp + ' <br />';
    }
    function onGeoError(error) {
      var element = document.getElementById('geovals');
      element.innerHTML =+ '<br>' + error.code + error.message;
    }

    function stopGeolocationg() {
      alert('stopGeolocationg');

      var element = document.getElementById('geovals');
      element.innerHTML = '<span style="color:red">Geolocation turned off.</span>';
      if (watchGeoID) {
        navigator.geolocation.clearWatch(watchGeoID);
        watchGeoID = null;
      }
    }

    function getCurrentPosition() {
      alert('getCurrentPosition');
      navigator.geolocation.getCurrentPosition(onPositionSuccess, onPositionError);
    }
    function onPositionSuccess(position) {
      var element = document.getElementById('geovals');
      element.innerHTML =+ ('Latitude: ' + position.coords.latitude + '\n' + 
                            'Longitude: ' + position.coords.longitude + '\n'); 
    };
    function onPositionError(error) {
      var element = document.getElementById('geovals');
      element.innerHTML =+('Error getting GPS Data');
    }
  </script>
</div>



(8)Notification(消息提示)
<!-- Notification 
      $ cordova plugin add org.apache.cordova.dialogs
      $ cordova plugin add org.apache.cordova.vibration
-->
<div data-role="page" id="notification">
  <div data-role="header">
    <a data-role="button" data-rel="back" data-direction="reverse" data-icon="arrow-l">Back</a>
    <h1>Notification</h1> 
  </div>
  <div data-role="content">
    <a href="#" data-role="button" id="showAlert">Show Alert popup</a><br>
    <a href="#" data-role="button" id="showConfirm">Show Confirm popup</a><br>
    <a href="#" data-role="button" id="showPrompt">Show Prompt popup</a><br>
    <br><br>
    <a href="#" data-role="button" id="playBeep">Play Beep sound</a><br>
    <a href="#" data-role="button" id="vibrate">Vibrate the device</a><br>
  </div>
  <script type="text/javascript">
    var watchGeoID = null;

    document.addEventListener("deviceready", onDeviceReady, false);
    function onDeviceReady() {
      $("#showAlert").on("click", showAlert);
      $("#showConfirm").on("click", showConfirm);
      $("#showPrompt").on("click", showPrompt);
      $("#playBeep").on("click", playBeep);
      $("#vibrate").on("click", vibrate);
    }

    function showAlert() {
      navigator.notification.alert(
        'Alert dialog: You are on fire!',
        alertDismissed, //callback
        'Game Over',
        'Done'
      );
    }
    /*
    // Override default HTML alert with native dialog
    document.addEventListener('deviceready', function () {
        if (navigator.notification) { 
            window.alert = function (message) {
                navigator.notification.alert(
                    message,
                    null,
                    "My App",
                    'OK'
                );
            };
        }
    }, false);
    */
    function alertDismissed() {
      alert('You dismissed the Alert.');
    }
    function onConfirm(buttonIndex) {
      alert('You selected button ' + buttonIndex + '\n(button 1 = Restart, button 2 = Exit.)');
    }
    function showConfirm() {
      navigator.notification.confirm(
        'Confirm dialog: You are the winner!',
        onConfirm,
        'Game Over',
        ['Restart','Exit']
      );
    }
    function onPrompt(results) {
      alert("You selected button number " + results.buttonIndex + " and entered " + results.input1 + '\n(button 2 = Exit, button 1 = OK.)');
    }
    function showPrompt() {
      navigator.notification.prompt(
        'Please enter your name',
        onPrompt,
        'Registration',
        ['Ok','Exit'],
        'Jane Doe?'
      );
    }
    function playBeep() {
      navigator.notification.beep(3);
    }
    function vibrate() {
      navigator.notification.vibrate(2000);
    }
  </script>
</div>



(9)Contacts(联系人)
<!-- Contacts 
        $ cordova plugin add org.apache.cordova.contacts
-->
<div data-role="page" id="contacts">
  <div data-role="header">
    <a data-role="button" data-rel="back" data-direction="reverse" data-icon="arrow-l">Back</a>
    <h1>Contacts</h1> 
  </div>
  <div data-role="content">
    <label for="fname">First Name:</label>
    <input type="text" name="fname" id="fname" value="REN"><br>
    <label for="lname">Last Name:</label>
    <input type="text" name="lname" id="lname" value="SANNING"><br>
    <label for="email">Email:</label>
    <input type="text" name="email" id="email" value="rensanning@gmail.com"><br>
    <label for="tel">TEL:</label>
    <input type="text" name="tel" id="tel" value="18812345678"><br>
    <br>
    <a href="#" data-role="button" id="saveContacts">Save</a><br>
  </div>
  <script type="text/javascript">

    document.addEventListener("deviceready", onDeviceReady, false);
    function onDeviceReady() {
      $("#saveContacts").on("click", saveContacts);
    }

    function saveContacts() {
      alert('saveContacts');

      if (!navigator.contacts) {
          alert("Contacts API not supported", "Error");
          return;
      }
      var contact = navigator.contacts.create();
      var name = new ContactName();
      name.givenName = $('#fname').val();
      name.familyName = $('#lname').val();
      contact.name = name;
      contact.displayName = $('#fname').val() + " " + $('#lname').val();
      contact.emails = [new ContactField('home', $('#email').val(), false)];
      contact.phoneNumbers = [new ContactField('home', $('#tel').val(), false)];
      contact.save(
        function() {
          alert("OK!");
        },
        function() {
          alert("Error!");
        }
      );
    }
  </script>
</div>



(10)File(文件系统处理 )
<!-- File 
        $ cordova plugin add org.apache.cordova.file
        $ cordova plugin add org.apache.cordova.file-transfer
-->
<div data-role="page" id="file">
  <div data-role="header">
    <a data-role="button" data-rel="back" data-direction="reverse" data-icon="arrow-l">Back</a>
    <h1>File</h1> 
  </div>
  <div data-role="content">
    <input type="text" id="userInput" name="userInput" value="I'm rensanning."><br>
    <a href="#" data-role="button" id="writeToFile">Write To File</a><br>

    <a href="#" data-role="button" id="readFile">Read File</a><br>
    <p id="data1"></p><p id="data2"></p><br>

    <a href="#" data-role="button" id="deleteFile">Delete File</a><br>
  </div>
  <script type="text/javascript">

    document.addEventListener("deviceready", onDeviceReady, false);
    function onDeviceReady() {
      $("#writeToFile").on("click", writeToFile);
      $("#readFile").on("click", readFile);
      $("#deleteFile").on("click", deleteFile);
    }

    function writeToFile() {
      window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFSForWrite, fail);
    }
    function gotFSForWrite(fileSystem) {
      fileSystem.root.getFile("CordovaSample.txt", {create: true, exclusive: false}, gotWriteFileEntry, fail);
    }
    function gotWriteFileEntry(fileEntry) {
      fileEntry.createWriter(gotFileWriter, fail);
    }
    function gotFileWriter(writer) {
     var userText = $('#userInput').val();
     writer.seek(writer.length);
     writer.write('\n\n' + userText);
     writer.onwriteend = function(evt){
       alert("You wrote ' " + userText + " ' at the end of the file.");
     } 
     $('#userInput').val("");
    }

    function readFile() {
      window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFSForRead, fail);
    }
    function gotFSForRead(fileSystem) {
      fileSystem.root.getFile("CordovaSample.txt", null, gotReadFileEntry, fail);
    }
    function gotReadFileEntry(fileEntry) {
      fileEntry.file(gotFileRead, fail);
    }
    function gotFileRead(file){
      readDataUrl(file);
      readAsText(file);
    }
    function readDataUrl(file) {
      var reader = new FileReader();
      reader.onloadend = function(evt) {
        var element = document.getElementById('data1');
        element.innerHTML = '<strong>Read as data URL:</strong> <br><pre>' + evt.target.result + '</pre>';
      };
      reader.readAsDataURL(file);
    }
    function readAsText(file) {
      var reader = new FileReader();
      reader.onloadend = function(evt) {
        var element = document.getElementById('data2');
        element.innerHTML = '<strong>Read as data text:</strong> <br><pre>' + evt.target.result + '</pre>';
      };
      reader.readAsText(file);
    }

    function deleteFile() {
      window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFSForRemove, fail);
    }
    function gotFSForRemove(fileSystem) {
      fileSystem.root.getFile("CordovaSample.txt", {create: false, exclusive: false}, gotRemoveFileEntry, fail);
    }
    function gotRemoveFileEntry(fileEntry){
      fileEntry.remove(
        function(entry) {
          alert("Removal succeeded");
        }, 
        function(error) {
          alert("Error removing file: " + error.code);
      });
    }

    function fail(error) {
      alert(error.code);
    }
  </script>
</div>



(11)InAppBrowser(Web浏览)
<!-- InAppBrowser
        $ cordova plugin add org.apache.cordova.inappbrowser
-->
<div data-role="page" id="inAppBrowser">
  <div data-role="header">
    <a data-role="button" data-rel="back" data-direction="reverse" data-icon="arrow-l">Back</a>
    <h1>InAppBrowser</h1> 
  </div>
  <div data-role="content">
    <label for="url">URL:</label>
    <input type="text" id="url" name="url" value="http://www.baidu.com"><br>
    <a href="#" data-role="button" id="openURL">Open URL</a><br>
  </div>
  <script type="text/javascript">
    document.addEventListener("deviceready", onDeviceReady, false);
    function onDeviceReady() {
      $("#openURL").on("click", openURL);
    }

    function openURL() {
      alert('openURL');

      var ref = window.open($('#url').val(), '_blank', 'location=yes');
      ref.addEventListener('loadstart', function(event) { alert('start: ' + event.url); });
      ref.addEventListener('loadstop', function(event) { alert('stop: ' + event.url); });
      ref.addEventListener('loaderror', function(event) { alert('error: ' + event.message); });
      ref.addEventListener('exit', function(event) { alert(event.type); });
    }
  </script>
</div>

   

(12)Storage(数据存储)
<!-- Storage -->
<div data-role="page" id="storage">
  <div data-role="header">
    <a data-role="button" data-rel="back" data-direction="reverse" data-icon="arrow-l">Back</a>
    <h1>Storage</h1> 
  </div>
  <div data-role="content">
    <label for="key">Key:</label>
    <input type="text" id="key" name="key" value="item_name"><br>
    <label for="val">Value:</label>
    <input type="text" id="val" name="val" value="item_value"><br>
    <a href="#" data-role="button" id="saveItem">Save Item</a><br>
    <a href="#" data-role="button" id="getItem">Get Item</a><br>
    <a href="#" data-role="button" id="deleteItem">Delete Item</a><br>
  </div>
  <script type="text/javascript">
    document.addEventListener("deviceready", onDeviceReady, false);
    function onDeviceReady() {
      $("#saveItem").on("click", saveItem);
      $("#getItem").on("click", getItem);
      $("#deleteItem").on("click", deleteItem);
    }

    function saveItem() {
      alert('saveItem');
      window.localStorage.setItem($('#key').val(), $('#val').val());
    }
    function getItem() {
      alert('getItem');
      var item_value = window.localStorage.getItem($('#key').val());
      alert(item_value);
    }
    function deleteItem() {
      alert('deleteItem');
      window.localStorage.removeItem($('#key').val());
    }
  </script>
</div>



(13)Database(客户端数据库)
<!-- Database -->
<div data-role="page" id="database">
  <div data-role="header">
    <a data-role="button" data-rel="back" data-direction="reverse" data-icon="arrow-l">Back</a>
    <h1>Database</h1> 
  </div>
  <div data-role="content">
    <label for="id">ID:</label>
    <input type="text" id="id" name="id" value="12345"><br>
    <label for="data">Data:</label>
    <input type="text" id="data" name="data" value="Data Value"><br>
    <a href="#" data-role="button" id="saveToDatabase">Save To Database</a><br>
    <a href="#" data-role="button" id="getFromDatabase">Get From Database</a><br>
  </div>
  <script type="text/javascript">
    var db;

    document.addEventListener("deviceready", onDeviceReady, false);
    function onDeviceReady() {
      $("#saveToDatabase").on("click", saveToDatabase);
      $("#getFromDatabase").on("click", getFromDatabase);

      db = window.openDatabase("MyDatabase", "1.0", "Cordova Sample", 200000);
      db.transaction(function(tx) {
          tx.executeSql('DROP TABLE IF EXISTS MyTable');
          tx.executeSql('CREATE TABLE IF NOT EXISTS MyTable (id unique, data)');
        }, 
        function(err) {
          alert("Error processing SQL: " + err.code);
        });
    }

    function saveToDatabase() {
      alert('saveToDatabase');

      db.transaction(function(tx) {
        tx.executeSql("INSERT INTO MyTable (id, data) VALUES (?, ?)",
                      [$('#id').val(), $('#data').val()],
                      function(tx, rs) {
                          alert("Your SQLite query was successful!");
                      },
                      function(tx, e) {
                          alert("SQLite Error: " + e.message);
                      });
      });
    }
    function getFromDatabase() {
      alert('getFromDatabase');

      db.transaction(function(tx) {
        tx.executeSql("SELECT id,data FROM MyTable ORDER BY id",
                      [],
                      function (tx, rs) {
                          for (var i = 0; i < rs.rows.length; i++) {
                              alert(rs.rows.item(i).id + "=" + rs.rows.item(i).data);
                          }
                      },
                      function(tx, e) {
                          alert("SQLite Error: " + e.message);
                      });
      });
    }
  </script>
</div>

  • 大小: 31.8 KB
  • 大小: 31.6 KB
  • 大小: 13.6 KB
  • 大小: 17.5 KB
  • 大小: 14.7 KB
  • 大小: 26.7 KB
  • 大小: 20.4 KB
  • 大小: 23.4 KB
  • 大小: 21.9 KB
  • 大小: 14.2 KB
  • 大小: 26.1 KB
  • 大小: 38.3 KB
  • 大小: 19 KB
  • 大小: 18.2 KB
  • www.rar (581.8 KB)
  • 下载次数: 1726
分享到:
评论
11 楼 lqixv 2015-11-26  
1280055207 写道
我擦,博主,gps定位根本不能用啊,

我直接下了作者的 apk,运行后,也获取不到当前位置。但可以打开 gps
10 楼 1280055207 2015-11-17  
我擦,博主,gps定位根本不能用啊,
9 楼 xiaocaoxiansheng 2015-09-11  
安装到android手机上发现定位功能不能用,是咋回事呢?
8 楼 yangguoyk 2015-05-22  
君不语 写道

      
7 楼 君不语 2014-12-24  
6 楼 xf326521 2014-09-12  
楼主jqueryMobile 都说比较慢 你怎么看
5 楼 stonefeng 2014-07-24  
这个系列文章很好!
4 楼 zhupinghuang 2014-04-10  
非常棒这个系列!!!
3 楼 x7341616 2014-04-09  
以前的ChildBrowser是可以进行图片缩放的,效果很酷。现在这个InAppBrowser插件咋就不行了呢,还是需要做什么控制才能实现么?网上找了很久,都没有用InAppBrowser插件进行图片手势缩放的。期待楼主能指点一二
2 楼 x7341616 2014-04-09  
楼主,能请教下么?InAppBrowser如果传的是一个图片地址,图片不能进行手势缩放,手机浏览器不是都能进行缩放的么,这个是phonegap框架限制图片手势缩放导致的么?有什么办法能解决么?
1 楼 watson243671 2014-03-08  
你这个系列的文章非常不错! 谢谢!

相关推荐

    Cordova 3.x 实用插件(1) -- Google地图Maps

    在“Cordova 3.x 实用插件(1) -- Google地图Maps”这个主题中,我们将探讨如何在Cordova项目中集成Google Maps API,以实现地图功能。 首先,我们需要安装Google Maps插件。在Cordova 3.x 中,这通常通过命令行...

    Cordova 3.x入门

    在本书中,作者rensanning将带领读者入门Cordova 3.x,涵盖了基础知识点、实用插件、源码分析和实例开发等方面的内容。 首先,作者介绍了如何在Windows和Android环境下搭建Cordova开发环境,这是开发移动应用的第一...

    PhoneGap 3.x Mobile Application Development Hotshot.2014.pdf

    ### PhoneGap 3.x Mobile Application Development Key Knowledge Points #### Overview **PhoneGap 3.x Mobile Application Development Hotshot.2014.pdf** is a comprehensive guide designed to help ...

    Node.js-Android美女拼图游戏

    不过,由于提到的是Node.js,这可能意味着开发者选择了一个不那么传统的路线,使用Web技术栈(HTML5、CSS3和JavaScript)并通过Cordova或者React Native等框架将游戏打包成原生Android应用。 在压缩包子文件...

    cordova-blackberry:[不推荐使用] Apache Cordova blackberry

    适用于BlackBerry 10的Apache Cordova ... Windows XP (32位), Windows 7 (32位和64位)或Mac OS X 10.6.4+ Node.js (&gt; 0.9.9) BlackBerry 10 Native SDK 。 安装Native SDK之后,必须将其工具添加

    reactreduxreactrouter40webpack2x重构DianpingApp

    5. **混合移动开发**: 由于项目标签为“JavaScript开发-混合移动开发”,这意味着这个应用可能使用了React Native或Cordova等技术,使得基于Web的React应用能够跨平台运行在移动设备上,实现了原生应用的用户体验。...

    x-fan:一个仅拥有前端的Fanfou客户

    对于iOS和Android应用的构建,X-fan可能使用了Cordova或React Native这样的技术,它们能够将Web应用打包成原生应用,同时保持跨平台兼容性。 许可证方面,X-fan选择了MIT License,这是一种非常宽松的开源软件许可...

    (安卓平台上的JavaScript自动化工具).zip

    在安卓平台上,JavaScript自动化工具为开发者提供了极大的便利,它们能够帮助进行测试、性能优化、调试以及应用程序接口(API)的自动化调用等任务。在这个压缩包中,包含了一个名为"AutoX_dev-test.zip"的文件和一...

    avantx.github.io

    这些接口通常是基于Cordova或React Native等现有技术实现的,确保了与原生平台的紧密集成。 此外,AvantX可能还支持热更新功能,允许开发者在不通过应用商店的情况下远程更新应用的部分代码,从而提高了迭代速度。...

    android+H5 的jar包

    6. **Hybrid框架**:除了直接使用`WebView`,还可以选择使用一些成熟的Hybrid框架,如Cordova、React Native或Ionic等。这些框架提供了更高级的API,简化了H5与Android的交互,同时提供了更好的性能和稳定性。 7. *...

    AUM-Moodle-Mobile-2

    同时,为了适配不同操作系统如 iOS 和 Android,可能会采用 Cordova 或 React Native 这样的跨平台开发工具,它们允许使用单一的 JavaScript 代码库来构建原生应用。 在源代码仓库中,"AUM-Moodle-Mobile-2-master...

    使用Visual Studio 2015在基于x86和ARM的设备上定位Android应用

    这个文档可能涵盖了跨平台开发的各个方面,如使用Gradle构建系统、处理API兼容性问题、调试技巧,以及如何打包和签名应用以便发布到Google Play或其他应用商店。 总之,通过Visual Studio 2015,开发者能够充分利用...

    Angular2.design:讨论Angular v2.0设计思想的地方

    9. **移动优化**:Angular 2的设计考虑到了移动设备的兼容性,支持Web Components标准,并且可以通过NativeScript或Cordova进行原生应用开发。 10. **社区和工具链**:Angular 2拥有庞大的开发者社区,提供了丰富的...

Global site tag (gtag.js) - Google Analytics