Code Snippets

Using Phonegap

Here is a quick guide to installing and using PhoneGap. For more details, refer to this blog post.

To get started with PhoneGap, it first needs to be installed. This is done by using the command-line 'npm install -g phone gap' with NodeJS already installed. Once installed you can create an empty helloworld project by typing 'phonegap create helloworld'. Building this helloworld app as an Android app simply requires typing 'cd helloworld && phonegap run android'. If you have the android SDK installed then this will create the android project, compile the project into an app, and run the compiled app on a device or in a simulator.

To create the iOS app you simply type 'phonegap run iOS'.  If the iOS SDK is installed then this will create the ios project, compile the application, and run the app on a device or in the simulator. After these few short steps, you've now created a cross-platform helloworld application in a matter of minutes.

An example of an application that accesses the camera. 

Type 'cordova plugin add org.apache.cordova.camera' in the terminal window to add the camera plugin to your phonegap application. Next we will modify the index.html file to include a button which accesses the camera API.

 

 <html>  
   <head>  
     <title>Hello World</title>  
     <script type="text/javascript" src="cordova.js"></script>  
     <script type="text/javascript">  
     // a function to capture a photo from the camera  
     function capturePhoto() {  
       if (!navigator.camera) {  
         alert("Camera API not supported", "Error");  
         return;  
       }  
       var options = {  
         quality: 50,  
         destinationType: Camera.DestinationType.DATA_URL,  
         sourceType: 1,   // 0:Photo Library, 1=Camera, 2=Saved Album  
         encodingType: 0   // 0=JPG 1=PNG  
       };  
       navigator.camera.getPicture(  
         function(imageData) {  
           var image = document.createElement("img");  
           image.setAttribute("src", "data:image/jpeg;base64," + imageData);  
           document.getElementById("photoImg").appendChild(image);  
         },  
         function() {  
           alert('Error taking picture', 'Error');  
         },  
         options);  
     </script>  
   </head>  
   <body>  
     <div id="photoImg"></div>  
     <div class="app">  
       <button onclick"capturePhoto()">Open Camera</button>  
     </div>  
   </body>  
 </html>  

 

 

Resource Tags: