Adding Cordova APIs to Android via CLI: Compass, Connection, Device


In this article, we are in part 2 of exploring the Cordova APIs, which started in http://iphonedevlog.wordpress.com/2014/01/31/adding-cordova-apis-to-android-via-cli-accelerometer-and-camera/ Refer to that article to set up your Cordova PhoneGap project files. You’ll need to follow the “Set Up the Android Project” section through step 9 inclusive. On this page, we’ll explore the Compass, Connection, and Device APIs.

You can continue the code by copying/pasting from this page into that project’s index.html page, or start a new page and link to it via a button on that page (which is what I did). If you are starting a second page, copy/paste this HTML skeleton into a page2.html page to follow along:

<!-- ********************* HMTL5 Skeleton begin *********************** -->
<!DOCTYPE html>
<html>
 <head>
 <meta charset="utf-8" />
 <meta name="format-detection" content="telephone=no" />
 <!-- WARNING from Cordova: for iOS 7, remove the width=device-width and height=device-height attributes. See https://issues.apache.org/jira/browse/CB-4323 -->
 <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<title>Cordova APIs</title>
<style type="text/css">
 .buttonClass {
 border-radius:8px; background-color:#fff;
 border:#878787 solid 1px; padding:1em .5em;margin:.5em;
 width: 46%;
 font-family: "Helvetica"; color: #000; font-size:1em; text-align:center;
 -webkit-appearance:none;
 } 
 .segment {
 display:block; border-radius:8px; background-color:#eee;
 border:#878787 solid 1px; padding:1em; margin:.5em;
 font-family: "Helvetica"; color: #000; font-size:1.3em; text-align:left;
 -webkit-appearance:none; 
 }
 @media screen and (max-width:700px) {
 .buttonClass { width: 100%;}
 }
 </style>
 <script type="text/javascript" src="cordova.js"></script> 
</head> 
<body>
</body> 
</html> 
<!-- ********************* HMTL5 Skeleton end *********************** -->

Compass

The compass indicates the compass direction the device is facing. We’ll follow this page from the docs to set it up: http://docs.phonegap.com/en/3.3.0/cordova_compass_compass.md.html#Compass Please review the page to gain an understanding of the steps we’ll be following.

1. Set the directory in Terminal and download the plugin:

cordova plugin add org.apache.cordova.device-orientation

2. Make sure it’s downloaded:

cordova plugin ls

3. Open CordovaAPI/platforms/android/res/xml/config.xml in a text file and add the following to just above </widget> and save:

<feature name="Compass">
 <param name="android-package" value="org.apache.cordova.deviceorientation.CompassListener" />
</feature>

4. In platforms/android/AndroidManifest.xml,

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

5. In index.html, remove everything between the <body></body> tags and replace with the following.

<!-- ********************* Compass begin *********************** -->
<div class="segment"><h2>Compass</h2>
<p style="font-style:italic;">This gives the compass readout every 3 seconds. 
<br>360 or 0 = North. 90 = East. 180 = South. 270 = West. 
<br>A negative value = heading can't be determined.</p>
<div id="heading">Waiting for heading...</div>
 <input type="button" class="buttonClass" onclick="startWatch();"value="Start Watching">
 <input type="button" class="buttonClass" onclick="stopWatch();"value="Stop Watching">
 <input type="button" class="buttonClass" onclick='window.location="http://iphonedevlog.wordpress.com/2014/02/06/adding-cordova-apis-to-android-via-cli-compass-connection-device/"' value="View Code On iPhoneDevLog">
</div>
<script type="text/javascript" charset="utf-8">
// The watch id references the current `watchHeading`
 var watchIDCompass = null;
// Wait for device API libraries to load
 document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
 function onDeviceReady() {
 startWatchCompass();
 }
// Start watching the compass
 function startWatchCompass() {
// Update compass every 3 seconds
 var options = { frequency: 3000 };
watchIDCompass = navigator.compass.watchHeading(onSuccess, onError, options);
 }
// Stop watching the compass
 function stopWatchCompass() {
 if (watchIDCompass) {
 navigator.compass.clearWatchCompass(watchIDCompass);
 watchIDCompass = null;
 }
 }
// onSuccess: Get the current heading
 function onSuccess(heading) {
 var element = document.getElementById('heading');
 element.innerHTML = 'Heading: ' + heading.magneticHeading;
 }
// onError: Failed to get the heading
 function onError(compassError) {
 alert('Compass error: ' + compassError.code);
 }
</script>
<!-- ********************* Compass end *********************** -->

6. In Terminal, prepare the files:

cordova prepare android

7. Create the apk file:

cordova compile android

8. Navigate to /platforms/android/bin and copy the CordovaAPI-debug.apk file and copy it to your device to test. (I copied it to DropBox on my computer and retrieved it from the DropBox app on my device.)

9. With the device in hand and the app running, point it in any direction and hold. The number updates every 3 seconds.

compass

Connection

The connection object, exposed via navigator.connection, provides information about the device’s cellular and wifi connection. You’ll find out what kind of connection you have, if any.

1. Set the directory in Terminal and download the plugin:

cordova plugin add org.apache.cordova.network-information

2. Make sure it’s downloaded:

cordova plugin ls

3. Open CordovaAPI/platforms/android/res/xml/config.xml in a text file and add the following to just above </widget> and save:

<feature name="NetworkStatus">
 <param name="android-package" value="org.apache.cordova.networkinformation.NetworkManager" />
</feature>

4. In platforms/android/AndroidManifest.xml,

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

5. In index.html, add the following to just above </body>:

<!-- ********************* Connection begin *********************** -->
<div class="segment"><h2>Connection</h2>
<p>Connection type will show in a popup.</p>
 <input type="button" class="buttonClass" onclick="checkConnection()" value="Check Connection Again">
 <input type="button" class="buttonClass" onclick='window.location="http://iphonedevlog.wordpress.com/2014/02/06/adding-cordova-apis-to-android-via-cli-compass-connection-device/"' value="View Code On iPhoneDevLog">
</div>
<script type="text/javascript" charset="utf-8">
// Wait for device API libraries to load
 document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available

 function onDeviceReady() {
 checkConnection();
 }
function 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';
alert('Connection type: ' + states[networkState]);
 }
 </script>
<!-- ********************* Connection end *********************** -->

6. In Terminal, prepare the files:

cordova prepare android

7. Create the apk file:

cordova compile android

8. Navigate to /platforms/android/bin and copy the CordovaAPI-debug.apk  and copy the file to your device to test.

9. With the device in hand and the app running, you should see an alert message telling what kind of connection you have. For instance, mine read: “Connection type: WiFi connection.”

connection

Device

The device object describes the device’s hardware and software. We’ll incorporate the code from this page: http://docs.phonegap.com/en/3.3.0/cordova_device_device.md.html#Device Please read for more details on how it works.

1. Set the directory in Terminal and download the plugin:

cordova plugin add org.apache.cordova.device

2. Make sure it’s downloaded:

cordova plugin ls

3. Open CordovaAPI/platforms/android/res/xml/config.xml in a text file and add the following to just above </widget> and save:

<feature name="Device">
 <param name="android-package" value="org.apache.cordova.device.Device" />
</feature>

5. In index.html, add the following to just above </body>:

<!-- ********************* Device begin *********************** -->
<div class="segment"><h2>Device</h2>
<p id="deviceProperties">Loading device properties...</p>
 <input type="button" class="buttonClass" onclick='window.location="http://iphonedevlog.wordpress.com/2014/02/06/adding-cordova-apis-to-android-via-cli-compass-connection-device/"' value="View Code On iPhoneDevLog">
</div>
<script type="text/javascript" charset="utf-8">
// Wait for device API libraries to load
 document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
 function onDeviceReady() {
 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>
<!-- ********************* Device end *********************** -->

6. In Terminal, prepare the files:

cordova prepare android

7. Create the apk file:

cordova compile android

8. Navigate to /platforms/android/bin and copy the CordovaAPI-debug.apk  file to your device to test.

9. With the device in hand and the app running, you should see the device information appear.

device

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s