Cordova – Media Capture ”; Previous Next This plugin is used for accessing device”s capture options. Step 1 – Installing Media Capture Plugin To install this plugin, we will open command prompt and run the following code − C:UsersusernameDesktopCordovaProject>cordova plugin add cordova-plugin-media-capture Step 2 – Add Buttons Since we want to show you how to capture audio, image and video, we will create three buttons in index.html. <button id = “audioCapture”>AUDIO</button> <button id = “imageCapture”>IMAGE</button> <button id = “videoCapture”>VIDEO</button> Step 3 – Add Event Listeners The next step is adding event listeners inside onDeviceReady in index.js. document.getElementById(“audioCapture”).addEventListener(“click”, audioCapture); document.getElementById(“imageCapture”).addEventListener(“click”, imageCapture); document.getElementById(“videoCapture”).addEventListener(“click”, videoCapture); Step 4A – Capture Audio Function The first callback function in index.js is audioCapture. To start sound recorder, we will use captureAudio method. We are using two options − limit will allow recording only one audio clip per single capture operation and duration is number of seconds of a sound clip. function audioCapture() { var options = { limit: 1, duration: 10 }; navigator.device.capture.captureAudio(onSuccess, onError, options); function onSuccess(mediaFiles) { var i, path, len; for (i = 0, len = mediaFiles.length; i < len; i += 1) { path = mediaFiles[i].fullPath; console.log(mediaFiles); } } function onError(error) { navigator.notification.alert(”Error code: ” + error.code, null, ”Capture Error”); } } When we press AUDIO button, sound recorder will open. Console will show returned array of objects that users captured. Step 4B – Capture Image Function The function for capturing image will be the same as the last one. The only difference is that we are using captureImage method this time. function imageCapture() { var options = { limit: 1 }; navigator.device.capture.captureImage(onSuccess, onError, options); function onSuccess(mediaFiles) { var i, path, len; for (i = 0, len = mediaFiles.length; i < len; i += 1) { path = mediaFiles[i].fullPath; console.log(mediaFiles); } } function onError(error) { navigator.notification.alert(”Error code: ” + error.code, null, ”Capture Error”); } } Now we can click IMAGE button to start the camera. When we take picture, the console will log the array with image object. Step 4C – Capture Video Function Let”s repeat the same concept for capturing video. We will use videoCapture method this time. function videoCapture() { var options = { limit: 1, duration: 10 }; navigator.device.capture.captureVideo(onSuccess, onError, options); function onSuccess(mediaFiles) { var i, path, len; for (i = 0, len = mediaFiles.length; i < len; i += 1) { path = mediaFiles[i].fullPath; console.log(mediaFiles); } } function onError(error) { navigator.notification.alert(”Error code: ” + error.code, null, ”Capture Error”); } } If we press VIDEO button, the camera will open and we can record the video. Once the video is saved, the console will return array once more. This time with video object inside. Print Page Previous Next Advertisements ”;
Category: cordova
Cordova – Network Information ”; Previous Next This plugin provides information about device”s network. Step 1 – Installing Network Information Plugin To install this plugin, we will open command prompt and run the following code − C:UsersusernameDesktopCordovaProject>cordova plugin add cordova-plugin-network-information Step 2 – Add Buttons Let”s create one button in index.html that will be used for getting info about network. <button id = “networkInfo”>INFO</button> Step 3 – Add Event Listeners We will add three event listeners inside onDeviceReady function in index.js. One will listen for clicks on the button we created before and the other two will listen for changes in connection status. document.getElementById(“networkInfo”).addEventListener(“click”, networkInfo); document.addEventListener(“offline”, onOffline, false); document.addEventListener(“online”, onOnline, false); Step 4 – Creating Functions networkInfo function will return info about current network connection once button is clicked. We are calling type method. The other functions are onOffline and onOnline. These functions are listening to the connection changes and any change will trigger the corresponding alert message. function networkInfo() { 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]); } function onOffline() { alert(”You are now offline!”); } function onOnline() { alert(”You are now online!”); } When we start the app connected to the network, onOnline function will trigger alert. If we press INFO button the alert will show our network state. If we disconnect from the network, onOffline function will be called. Print Page Previous Next Advertisements ”;
Cordova – Geolocation
Cordova – Geolocation ”; Previous Next Geolocation is used for getting info about device”s latitude and longitude. Step 1 – Installing Plugin We can install this plugin by typing the following code to command prompt window. C:UsersusernameDesktopCordovaProject>cordova plugin add cordova-plugin-geolocation Step 2 – Add Buttons In this tutorial we will show you how to get current position and how to watch for changes. We first need to create buttons that will call these functions. <button id = “getPosition”>CURRENT POSITION</button> <button id = “watchPosition”>WATCH POSITION</button> Step 3 – Add Event Listeners Now we want to add event listeners when the device is ready. We will add the code sample below to onDeviceReady function in index.js. document.getElementById(“getPosition”).addEventListener(“click”, getPosition); document.getElementById(“watchPosition”).addEventListener(“click”, watchPosition); Step 3 – Create Functions Two functions have to be created for two event listeners. One will be used for getting the current position and the other for watching the position. function getPosition() { var options = { enableHighAccuracy: true, maximumAge: 3600000 } var watchID = navigator.geolocation.getCurrentPosition(onSuccess, onError, options); function onSuccess(position) { alert(”Latitude: ” + position.coords.latitude + ”n” + ”Longitude: ” + position.coords.longitude + ”n” + ”Altitude: ” + position.coords.altitude + ”n” + ”Accuracy: ” + position.coords.accuracy + ”n” + ”Altitude Accuracy: ” + position.coords.altitudeAccuracy + ”n” + ”Heading: ” + position.coords.heading + ”n” + ”Speed: ” + position.coords.speed + ”n” + ”Timestamp: ” + position.timestamp + ”n”); }; function onError(error) { alert(”code: ” + error.code + ”n” + ”message: ” + error.message + ”n”); } } function watchPosition() { var options = { maximumAge: 3600000, timeout: 3000, enableHighAccuracy: true, } var watchID = navigator.geolocation.watchPosition(onSuccess, onError, options); function onSuccess(position) { alert(”Latitude: ” + position.coords.latitude + ”n” + ”Longitude: ” + position.coords.longitude + ”n” + ”Altitude: ” + position.coords.altitude + ”n” + ”Accuracy: ” + position.coords.accuracy + ”n” + ”Altitude Accuracy: ” + position.coords.altitudeAccuracy + ”n” + ”Heading: ” + position.coords.heading + ”n” + ”Speed: ” + position.coords.speed + ”n” + ”Timestamp: ” + position.timestamp + ”n”); }; function onError(error) { alert(”code: ” + error.code + ”n” +”message: ” + error.message + ”n”); } } In example above we are using two methods − getCurrentPosition and watchPosition. Both functions are using three parameters. Once we click CURRENT POSITION button, the alert will show geolocation values. If we click WATCH POSITION button, the same alert will be triggered every three seconds. This way we can track movement changes of the user”s device. NOTE This plugin is using GPS. Sometimes it can”t return the values on time and the request will return timeout error. This is why we specified enableHighAccuracy: true and maximumAge: 3600000. This means that if a request isn”t completed on time, we will use the last known value instead. In our example, we are setting maximumAge to 3600000 milliseconds. Print Page Previous Next Advertisements ”;
Cordova – Contacts
Cordova – Contacts ”; Previous Next This plugin is used for accessing the contacts database of the device. In this tutorial we will show you how to create, query and delete contacts. Step 1 – Install Contacts Plugin C:UsersusernameDesktopCordovaProject>cordova plugin add cordova-plugincontacts Step 2 – Adding Buttons The button will be used for calling the createContact function. We will place it in the div class = “app” in index.html file. <button id = “createContact”>ADD CONTACT</button> <button id = “findContact”>FIND CONTACT</button> <button id = “deleteContact”>DELETE CONTACT</button> Step 2 – Add Event Listeners Open index.js and copy the following code snippet into the onDeviceReady function. document.getElementById(“createContact”).addEventListener(“click”, createContact); document.getElementById(“findContact”).addEventListener(“click”, findContact); document.getElementById(“deleteContact”).addEventListener(“click”, deleteContact); Step 3A – Callback Function (navigator.contacts.create) Now, we do not have any contacts stored on the device. Our first callback function will call the navigator.contacts.create method where we can specify the new contact data. This will create a contact and assign it to the myContact variable but it will not be stored on the device. To store it, we need to call the save method and create success and error callback functions. function createContact() { var myContact = navigator.contacts.create({“displayName”: “Test User”}); myContact.save(contactSuccess, contactError); function contactSuccess() { alert(“Contact is saved!”); } function contactError(message) { alert(”Failed because: ” + message); } } When we click the ADD CONTACT button, new contact will be stored to the device contact list. Step 3B – Callback Function (navigator.contacts.find) Our second callback function will query all contacts. We will use the navigator.contacts.find method. The options object has filter parameter which is used to specify the search filter. multiple = true is used since we want to return all contacts from device. The field key to search contacts by displayName since we used it when saving contact. After the options are set, we are using find method to query contacts. The alert message will be triggered for every contact that is found. function findContacts() { var options = new ContactFindOptions(); options.filter = “”; options.multiple = true; fields = [“displayName”]; navigator.contacts.find(fields, contactfindSuccess, contactfindError, options); function contactfindSuccess(contacts) { for (var i = 0; i < contacts.length; i++) { alert(“Display Name = ” + contacts[i].displayName); } } function contactfindError(message) { alert(”Failed because: ” + message); } } When we press the FIND CONTACT button, one alert popup will be triggered since we have saved only one contact. Step 3C – Callback function (delete) In this step, we will use the find method again but this time we will set different options. The options.filter is set to search that Test User which has to be deleted. After the contactfindSuccess callback function has returned the contact we want, we will delete it by using the remove method that requires its own success and error callbacks. function deleteContact() { var options = new ContactFindOptions(); options.filter = “Test User”; options.multiple = false; fields = [“displayName”]; navigator.contacts.find(fields, contactfindSuccess, contactfindError, options); function contactfindSuccess(contacts) { var contact = contacts[0]; contact.remove(contactRemoveSuccess, contactRemoveError); function contactRemoveSuccess(contact) { alert(“Contact Deleted”); } function contactRemoveError(message) { alert(”Failed because: ” + message); } } function contactfindError(message) { alert(”Failed because: ” + message); } } Now, we have only one contact stored on the device. We will manually add one more to show you the deleting process. We will now click the DELETE CONTACT button to delete the Test User. If we check the contact list again, we will see that the Test User does not exist anymore. Print Page Previous Next Advertisements ”;
Cordova – File Transfer
Cordova – File Transfer ”; Previous Next This plugin is used for uploading and downloading files. Step 1 – Installing File Transfer Plugin We need to open command prompt and run the following command to install the plugin. C:UsersusernameDesktopCordovaProject>cordova plugin add cordova-plugin-file-transfer Step 2 – Create Buttons In this chapter, we will show you how to upload and download files. Let”s create two buttons in index.html <button id = “uploadFile”>UPLOAD</button> <button id = “downloadFile”>DOWNLOAD</button> Step 3 – Add Event Listeners Event listeners will be created in index.js inside the onDeviceReady function. We are adding click events and callback functions. document.getElementById(“uploadFile”).addEventListener(“click”, uploadFile); document.getElementById(“downloadFile”).addEventListener(“click”, downloadFile); Step 4A – Download Function This function will be used for downloading the files from server to device. We uploaded file to postimage.org to make things more simple. You will probably want to use your own server. The function is placed in index.js and will be triggered when the corresponding button is pressed. uri is the server download link and fileURI is the path to the DCIM folder on our device. function downloadFile() { var fileTransfer = new FileTransfer(); var uri = encodeURI(“http://s14.postimg.org/i8qvaxyup/bitcoin1.jpg”); var fileURL = “///storage/emulated/0/DCIM/myFile”; fileTransfer.download( uri, fileURL, function(entry) { console.log(“download complete: ” + entry.toURL()); }, function(error) { console.log(“download error source ” + error.source); console.log(“download error target ” + error.target); console.log(“download error code” + error.code); }, false, { headers: { “Authorization”: “Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA==” } } ); } Once we press the DOWNLOAD button, the file will be downloaded from the postimg.org server to our mobile device. We can check the specified folder and see that myFile is there. The console output will look like this − Step 4B – Upload Function Now let”s create a function that will take the file and upload it to the server. Again, we want to simplify this as much as possible, so we will use posttestserver.com online server for testing. The uri value will be linked for posting to posttestserver. function uploadFile() { var fileURL = “///storage/emulated/0/DCIM/myFile” var uri = encodeURI(“http://posttestserver.com/post.php”); var options = new FileUploadOptions(); options.fileKey = “file”; options.fileName = fileURL.substr(fileURL.lastIndexOf(”/”)+1); options.mimeType = “text/plain”; var headers = {”headerParam”:”headerValue”}; options.headers = headers; var ft = new FileTransfer(); ft.upload(fileURL, uri, onSuccess, onError, options); function onSuccess(r) { console.log(“Code = ” + r.responseCode); console.log(“Response = ” + r.response); console.log(“Sent = ” + r.bytesSent); } function onError(error) { alert(“An error has occurred: Code = ” + error.code); console.log(“upload error source ” + error.source); console.log(“upload error target ” + error.target); } } Now we can press the UPLOAD button to trigger this function. We will get a console output as confirmation that the uploading was successful. We can also check the server to make sure that the file was uploaded. Print Page Previous Next Advertisements ”;
Cordova – First Application
Cordova – First Application ”; Previous Next We have understood how to install Cordova and set up the environment for it. Once everything is ready, we can create our first hybrid Cordova application. Step 1 – Creating App Open the directory where you want the app to be installed in command prompt. We will create it on desktop. C:UsersusernameDesktop>cordova create CordovaProject io.cordova.hellocordova CordovaApp CordovaProject is the directory name where the app is created. io.cordova.hellocordova is the default reverse domain value. You should use your own domain value if possible. CordovaApp is the title of your app. Step 2 – Adding Platforms You need to open your project directory in the command prompt. In our example, it is the CordovaProject. You should only choose platforms that you need. To be able to use the specified platform, you need to have installed the specific platform SDK. Since we are developing on windows, we can use the following platforms. We have already installed Android SDK, so we will only install android platform for this tutorial. C:UsersusernameDesktopCordovaProject>cordova platform add android There are other platforms that can be used on Windows OS. C:UsersusernameDesktopCordovaProject>cordova platform add wp8 C:UsersusernameDesktopCordovaProject>cordova platform add amazon-fireos C:UsersusernameDesktopCordovaProject>cordova platform add windows C:UsersusernameDesktopCordovaProject>cordova platform add blackberry10 C:UsersusernameDesktopCordovaProject>cordova platform add firefoxos If you are developing on Mac, you can use − $ cordova platform add IOS $ cordova platform add amazon-fireos $ cordova platform add android $ cordova platform add blackberry10 $ cordova platform add firefoxos You can also remove platform from your project by using − C:UsersusernameDesktopCordovaProject>cordova platform rm android Step 3 – Building and Running In this step we will build the app for a specified platform so we can run it on mobile device or emulator. C:UsersusernameDesktopCordovaProject>cordova build android Now we can run our app. If you are using the default emulator you should use − C:UsersusernameDesktopCordovaProject>cordova emulate android If you want to use the external emulator or real device you should use − C:UsersusernameDesktopCordovaProject>cordova run android NOTE − We will use the Genymotion android emulator since it is faster and more responsive than the default one. You can find the emulator here. You can also use real device for testing by enabling USB debugging from the options and connecting it to your computer via USB cable. For some devices, you will also need to install the USB driver. Once we run the app, it will install it on the platform we specified. If everything is finished without errors, the output should show the default start screen of the app. In our next tutorial, we will show you how to configure the Cordova Application. Print Page Previous Next Advertisements ”;
Cordova – Splash Screen
Cordova – Splash Screen ”; Previous Next This plugin is used to display a splash screen on application launch. Step 1 – Installing Splash Screen Plugin Splash screen plugin can be installed in command prompt window by running the following code. C:UsersusernameDesktopCordovaProject>cordova plugin add cordova-plugin-splashscreen Step 2 – Add Splash Screen Adding splash screen is different from adding the other Cordova plugins. We need to open config.xml and add the following code snippets inside the widget element. First snippet is SplashScreen. It has value property which is the name of the images in platform/android/res/drawable– folders. Cordova offers default screen.png images that we are using in this example, but you will probably want to add your own images. Important thing is to add images for portrait and landscape view and also to cover different screen sizes. <preference name = “SplashScreen” value = “screen” /> Second snippet we need to add is SplashScreenDelay. We are setting value to 3000 to hide the splash screen after three seconds. <preference name = “SplashScreenDelay” value = “3000” /> The last preference is optional. If value is set to true, the image will not be stretched to fit screen. If it is set to false, it will be stretched. <preference name = “SplashMaintainAspectRatio” value = “true” /> Now when we run the app, we will see the splash screen. Print Page Previous Next Advertisements ”;
Cordova – InAppBrowser
Cordova – InAppBrowser ”; Previous Next This plugin is used for opening web browser inside Cordova app. Step 1 – Installing Plugin We need to install this plugin in command prompt window before we are able to use it. C:UsersusernameDesktopCordovaProject>cordova plugin add cordova-plugin-inappbrowser Step 2 – Add button We will add one button that will be used for opening inAppBrowser window in index.html. Step 3 – Add Event Listener Now let”s add event listener for our button in onDeviceReady function in index.js. document.getElementById(“openBrowser”).addEventListener(“click”, openBrowser); Step 4 – Create Function In this step we are creating function that will open browser inside our app. We are assigning it to the ref variable that we can use later to add event listeners. function openBrowser() { var url = ”https://cordova.apache.org”; var target = ”_blank”; var options = “location = yes” var ref = cordova.InAppBrowser.open(url, target, options); ref.addEventListener(”loadstart”, loadstartCallback); ref.addEventListener(”loadstop”, loadstopCallback); ref.addEventListener(”loaderror”, loaderrorCallback); ref.addEventListener(”exit”, exitCallback); function loadstartCallback(event) { console.log(”Loading started: ” + event.url) } function loadstopCallback(event) { console.log(”Loading finished: ” + event.url) } function loaderrorCallback(error) { console.log(”Loading error: ” + error.message) } function exitCallback() { console.log(”Browser is closed…”) } } If we press BROWSER button, we will see the following output on screen. Console will also listen to events. loadstart event will fire when URL is started loading and loadstop will fire when URL is loaded. We can see it in console. Once we close the browser, exit event will fire. There are other possible options for InAppBrowser window. We will explain it in the table below. S.No option & details 1 location Used to turn the browser location bar on or off. Values are yes or no. 2 hidden Used to hide or show inAppBrowser. Values are yes or no. 3 clearCache Used to clear browser cookie cache. Values are yes or no. 4 clearsessioncache Used to clear session cookie cache. Values are yes or no. 5 zoom Used to hide or show Android browser”s zoom controls. Values are yes or no. 6 hardwareback yes to use the hardware back button to navigate back through the browser history. no to close the browser once back button is clicked. We can use ref (reference) variable for some other functionalities. We will show you just quick examples of it. For removing event listeners we can use − ref.removeEventListener(eventname, callback); For closing InAppBrowser we can use − ref.close(); If we opened hidden window, we can show it − ref.show(); Even JavaScript code can be injected to the InAppBrowser − var details = “javascript/file/url” ref.executeScript(details, callback); The same concept can be used for injecting CSS − var details = “css/file/url” ref.inserCSS(details, callback); Print Page Previous Next Advertisements ”;
Cordova – Home
Cordova Tutorial PDF Version Quick Guide Resources Job Search Discussion Cordova is a platform that is used for building mobile apps using HTML, CSS and JS. We can think of Cordova as a container for connecting our web app with native mobile functionalities. Web applications cannot use native mobile functionalities by default. This is where Cordova comes into picture. It offers a bridge for connection between web app and mobile device. By using Cordova, we can make hybrid mobile apps that can use camera, geolocation, file system and other native mobile functions. Audience We are creating this tutorial for HTML, CSS and JavaScript developers that want to learn about mobile development. During the course we will go through most of the Cordova key points and we will show you how to use most of the Cordova plugins. All of the examples provided can be used as a starting point in your own apps. We will also try to explain theory behind Cordova so you can get better picture of building process of hybrid mobile apps. We will try to show you examples as simple as possible so you can understand the essential principle of the Cordova development. Prerequisites You need to be familiar with HTML, CSS and JavaScript. If you ever created single page apps (SPA), that knowledge will be useful when working with Cordova but it is not necessary to understand most of the things this tutorial offers. Print Page Previous Next Advertisements ”;
Cordova – Back Button
Cordova – Back Button ”; Previous Next Handling Back Button You will usually want to use Android back button for some app functionality like returning to previous screen. To be able to implement your own functionality, you first need to disable exiting the app when the back button is pressed. document.addEventListener(“backbutton”, onBackKeyDown, false); function onBackKeyDown(e) { e.preventDefault(); alert(”Back Button is Pressed!”); } Now when we press the native Android back button, the alert will appear on the screen instead of exiting the app. This is done by using e.preventDefault(). Print Page Previous Next Advertisements ”;