Pages

Wednesday, May 30, 2012

Difference between two times in javascript


var secondsPerMinute = 60;
var minutesPerHour = 60;

function convertSecondsToHHMMSS(intSecondsToConvert) {
var hours = convertHours(intSecondsToConvert);
var minutes = getRemainingMinutes(intSecondsToConvert);
minutes = (minutes == 60) ? "00" : minutes;
var seconds = getRemainingSeconds(intSecondsToConvert);
return hours+":"+minutes;
}

function convertHours(intSeconds) {
var minutes = convertMinutes(intSeconds);
var hours = Math.floor(minutes/minutesPerHour);
return hours;
}
function convertMinutes(intSeconds) {
return Math.floor(intSeconds/secondsPerMinute);
}
function getRemainingSeconds(intTotalSeconds) {
return (intTotalSeconds%secondsPerMinute);
}
function getRemainingMinutes(intSeconds) {
var intTotalMinutes = convertMinutes(intSeconds);
return (intTotalMinutes%minutesPerHour);
}

function HMStoSec1(T) { // h:m:s
  var A = T.split(/\D+/) ; return (A[0]*60 + +A[1])*60 + +A[2] }
 
Sample code to get difference between two times using javascript 
var time1 = HMStoSec1("10:00:00");
var time2 = HMStoSec1("12:05:00");
var diff = time2 - time1;
document.write(convertSecondsToHHMMSS(diff));

Tuesday, January 31, 2012

Get the process id in java

Each application is treated as Process in our JVM. So how to get our running application in runtime. In java in lang package we are having a class called ManagementFactory. Which will help us to trace out process id of our running application.

     ManagementFactory.getRuntimeMXBean().getName()

It will returns the id in String format.
We need to use this command after each process or thread.
 
For Eg see the below examples: 
  
To Get the process id.  
import java.awt.BorderLayout;
import java.awt.Color;
import java.lang.management.ManagementFactory;

import javax.swing.JFrame;
import javax.swing.JTextArea;

public class SwingDemo {
     public static void main(String[] args) {
         try {
                JFrame f = new JFrame(System.nanoTime()+"");
                f.setSize(450, 450);
                f.setLocation(300,200);
                f.getContentPane().add(BorderLayout.CENTER, new JTextArea(10, 40));
                f.setVisible(true);
                f.setForeground(Color.BLUE);
              
                    //Process process = Runtime.getRuntime().exec("notepad.exe");
                    System.out.println("P id::=>" +
                                ManagementFactory.getRuntimeMXBean().getName()
                    );           
                    System.out.println("T id::=>" );
                    //    process.destroy();
            
             } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
          
          }
}

To Kill the process id       

  // serviceName should be the process id  which we got from the above application.
  // taskkill /IM command will work on windows only. Check out in web for OS dependent commands.
  public static void killProcess(String serviceName) throws Exception {

          Runtime.getRuntime().exec("taskkill /IM " + serviceName);  
  }


To check whether Process is running or not.

  public static boolean isProcessRunning(String serviceName) throws Exception {

         Process p = Runtime.getRuntime().exec(TASKLIST);
         Thread.sleep(1000);
         BufferedReader reader = new BufferedReader(new InputStreamReader(
           p.getInputStream()));
         String line;
         while ((line = reader.readLine()) != null) {

          System.out.println("om ::"+ line);
          if (line.contains(serviceName)) {
           return true;
          }
         }

         return false;
}

So i hope with the help of above sample code you can achieve process id of your applications.

Friday, January 20, 2012

Eclipse plugin for PhoneGap




Get the MDS AppLaud 1.2 Eclipse Plug-In!
  • In Eclipse ADT, Select Help -> Install New Software
  • Click Add to enter a new Repository site
  • The Name field is optional, "MDS AppLaud 1.2" suggested
  • In Location, enter the download site: https://svn.codespot.com/a/eclipselabs.org/mobile-web-development-with-phonegap/tags/r1.2/download
  • Select OK
  • Select the New Site and Check the box to the left of PhoneGap for Android
  • Click Finish and Follow the prompts
  • If your Eclipse installation doesn't yet include a web page editor for html files. Necessary for new Classic or Java editions.
    • Install New Software -> Work with: Indigo (or Helios) ->Web, XML Java EE, and OSGi Enterprise Development -> Web Page Editor
REF LINK: http://www.mobiledevelopersolutions.com/home/download

Camera Access using PhoneGap.

CAMERA 
         The camera object provides access to the device's default camera application.
Methods:
         camera.getPicture
           
             Takes a photo using the camera or retrieves a photo from the device's album. The image is returned as a base64 encoded String or as the URI of an image file. 

  navigator.camera.getPicture( cameraSuccess, cameraError, [ cameraOptions ] );  
Description 
  
Function camera.getPicture opens the device's default camera application so that the user can take a picture (if Camera.sourceType = Camera.PictureSourceType.CAMERA, which is the default). Once the photo is taken, the camera application closes and your application is restored.
If Camera.sourceType = Camera.PictureSourceType.PHOTOLIBRARY or Camera.PictureSourceType.SAVEDPHOTOALBUM, then a photo chooser dialog is shown, from which a photo from the album can be selected.
The return value will be sent to the cameraSuccess function, in one of the following formats, depending on the cameraOptions you specify:
  • A String containing the Base64 encoded photo image (default).
  • A String representing the image file location on local storage.
You can do whatever you want with the encoded image or URI, for example:
  • Render the image in an <img> tag (see example below)
  • Save the data locally (LocalStorage, Lawnchair, etc)
  • Post the data to a remote server
Note: The image quality of pictures taken using the camera on newer devices is quite good. Encoding such images using Base64 has caused memory issues on some of these devices (iPhone 4, BlackBerry Torch 9800). Therefore, using FILE_URI as the 'Camera.destinationType' is highly recommended.

Supported Platforms:
  • Android
  • Blackberry WebWorks (OS 5.0 and higher)
  • iPhone
  • Windows Phone 7 ( Mango )
Quick Example:  
  Take photo and retrieve Base64-encoded image:   
   navigator.camera.getPicture(onSuccess, onFail, { quality: 50 }); 
  function onSuccess(imageData) {
      var image = document.getElementById('myImage');
      image.src = "data:image/jpeg;base64," + imageData;
  }
  function onFail(message) {
      alert('Failed because: ' + message);
  } 

Take photo and retrieve image file location:  
   navigator.camera.getPicture(onSuccess, onFail, { quality: 50, 
      destinationType: Camera.DestinationType.FILE_URI }); 
  function onSuccess(imageURI) {
      var image = document.getElementById('myImage');
      image.src = imageURI;
  }
  function onFail(message) {
      alert('Failed because: ' + message);
  } 
 
 
FULL EXAMPLE:    
 


<!DOCTYPE html>
<html>
  <head>
    <title>Capture Photo</title>

    <script type="text/javascript" charset="utf-8" src="phonegap.js"></script>
    <script type="text/javascript" charset="utf-8">

    var pictureSource;   // picture source
    var destinationType; // sets the format of returned value 

    // Wait for PhoneGap to connect with the device
    //
    document.addEventListener("deviceready",onDeviceReady,false);

    // PhoneGap is ready to be used!
    //
    function onDeviceReady() {
        pictureSource=navigator.camera.PictureSourceType;
        destinationType=navigator.camera.DestinationType;
    }

    // Called when a photo is successfully retrieved
    //
    function onPhotoDataSuccess(imageData) {
      // Uncomment to view the base64 encoded image data
      // console.log(imageData);

      // Get image handle
      //
      var smallImage = document.getElementById('smallImage');

      // Unhide image elements
      //
      smallImage.style.display = 'block';

      // Show the captured photo
      // The inline CSS rules are used to resize the image
      //
      smallImage.src = "data:image/jpeg;base64," + imageData;
    }

    // Called when a photo is successfully retrieved
    //
    function onPhotoURISuccess(imageURI) {
      // Uncomment to view the image file URI 
      // console.log(imageURI);

      // Get image handle
      //
      var largeImage = document.getElementById('largeImage');

      // Unhide image elements
      //
      largeImage.style.display = 'block';

      // Show the captured photo
      // The inline CSS rules are used to resize the image
      //
      largeImage.src = imageURI;
    }

    // A button will call this function
    //
    function capturePhoto() {
      // Take picture using device camera and retrieve image as base64-encoded string
      navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50 });
    }

    // A button will call this function
    //
    function capturePhotoEdit() {
      // Take picture using device camera, allow edit, and retrieve image as base64-encoded string  
      navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 20, allowEdit: true }); 
    }

    // A button will call this function
    //
    function getPhoto(source) {
      // Retrieve image file location from specified source
      navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 50, 
        destinationType: destinationType.FILE_URI,
        sourceType: source });
    }

    // Called if something bad happens.
    // 
    function onFail(message) {
      alert('Failed because: ' + message);
    }

    </script>
  </head>
  <body>
    <button onclick="capturePhoto();">Capture Photo</button> <br>
    <button onclick="capturePhotoEdit();">Capture Editable Photo</button> <br>
    <button onclick="getPhoto(pictureSource.PHOTOLIBRARY);">From Photo Library</button><br>
    <button onclick="getPhoto(pictureSource.SAVEDPHOTOALBUM);">From Photo Album</button><br>
    <img style="display:none;width:60px;height:60px;" id="smallImage" src="" />
    <img style="display:none;" id="largeImage" src="" />
  </body></html>  
 
Camera Success 
onSuccess callback function that provides the image data.  
function(imageData) {
    // Do something with the image
}
Parameter 
   imageData: Base64 encoding of the image data, OR the image file URI, 
   depending on cameraOptions used. (String) 
 
 Example: 
// Show image
//
function cameraCallback(imageData) {
    var image = document.getElementById('myImage');
    image.src = "data:image/jpeg;base64," + imageData;
}
 Camera Error  
     onError callback function that provides an error me
function(message) {
    // Show a helpful message
} 
 parameters: 
     message: The message is provided by the device's native code. (String) 
 
Camera Options  
 Optional parameters to customize the camera settings.
{ quality : 75, 
  destinationType : Camera.DestinationType.DATA_URL, 
  sourceType : Camera.PictureSourceType.CAMERA, 
  allowEdit : true,
  encodingType: Camera.EncodingType.JPEG,
  targetWidth: 100,
  targetHeight: 100 }; 
Options: 
  • quality: Quality of saved image. Range is [0, 100]. (Number)
  • destinationType: Choose the format of the return value. Defined in navigator.camera.DestinationType (Number)
Camera.DestinationType = {                                                       
        DATA_URL : 0,                // Return image as base64 encoded string    
        FILE_URI : 1                 // Return image file URI                    
    };                                                                           
sourceType: Set the source of the picture.  Defined in 
nagivator.camera.PictureSourceType (Number) 
Camera.PictureSourceType = {
    PHOTOLIBRARY : 0,
    CAMERA : 1,
    SAVEDPHOTOALBUM : 2
};
  • allowEdit: Allow simple editing of image before selection. (Boolean)
  • EncodingType: Choose the encoding of the returned image file. Defined in navigator.camera.EncodingType (Number)
Camera.EncodingType = {                                                          
        JPEG : 0,               // Return JPEG encoded image                     
        PNG : 1                 // Return PNG encoded image                      
    };                                                                           
  • targetWidth: Width in pixels to scale image. Must be used with targetHeight. Aspect ratio is maintained. (Number)
  • targetHeight: Height in pixels to scale image. Must be used with targetWidth. Aspect ratio is maintained. (Number)
  • MediaType: Set the type of media to select from. Only works when PictureSourceType is PHOTOLIBRARY or SAVEDPHOTOALBUM. Defined in nagivator.camera.
    MediaType (Number)Camera.MediaType = {
    PICTURE: 0,             // allow selection of still pictures only. DEFAULT. Will return format specified via DestinationType
    VIDEO: 1,               // allow selection of video only, WILL ALWAYS RETURN FILE_URI
    ALLMEDIA : 2            // allow selection from all media types
 
 
 
                                                                                                                                                                                                                    
REF Link:                                                                                                                                                                                                            
http://docs.phonegap.com/en/1.2.0/phonegap_camera_camera.md.html#camera.getPicture_full_example                        
     
              

 
 
 
 
 

PHONEGAP with Android


1. Requirements

  • Eclipse 3.4+
There is also a Terminal version of this tutorial that doesn't use Eclipse.

2. Install SDK + PhoneGap


3. Setup New Project


  • Launch Eclipse, then under the File menu select New > Android Project

  • In the root directory of the project, create two new directories:
    • /libs
    • /assets/www
  • Copy phonegap.js from your PhoneGap download earlier to /assets/www
  • Copy phonegap.jar from your PhoneGap download earlier to /libs
  • Copy xml folder from your PhoneGap download earlier to /res
  • Make a few adjustments too the project's main Java file found in the src folder in Eclipse: (view image below)
    • Change the class's extend from Activity to DroidGap
    • Replace the setContentView() line with super.loadUrl("file:///android_asset/www/index.html");
    • Add import com.phonegap.*;
    • Remove import android.app.Activity;
    •  
  • You might experience an error here, where Eclipse can't find phonegap-1.0.0.jar. In this case, right click on the /libs folder and go to Build Paths/ > Configure Build Paths. Then, in the Libraries tab, add phonegap-1.0.0.jar to the Project. If Eclipse is being temperamental, you might need to refresh (F5) the project once again.
  • Right click on AndroidManifest.xml and select Open With > Text Editor
  • Paste the following permissions under versionName: (view image below) 


  • < supports-screens android:largeScreens="true" android:normalScreens="true" android:smallScreens="true" android:resizeable="true" android:anyDensity="true" /> <uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.VIBRATE" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.RECEIVE_SMS" /> <uses-permission android:name="android.permission.RECORD_AUDIO" /> <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" /> <uses-permission android:name="android.permission.READ_CONTACTS" /> <uses-permission android:name="android.permission.WRITE_CONTACTS" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.GET_ACCOUNTS" /> <uses-permission android:name="android.permission.BROADCAST_STICKY" />
  • Add android:configChanges="orientation|keyboardHidden" to the activity tag in AndroidManifest. (view image below)
  • Add a second activity under you appliction tag in AndroidManifest. (view image below)

<activity name="com.phonegap.DroidGap" label="@string/app_name" configchanges="orientation|keyboardHidden">
<intent-filter>
</intent-filter>
</activity>

4. Hello World

Now create and open a new file named index.html in the /assets/www directory. Paste the following code:



<!DOCTYPE HTML>
<html>
<head>
<title>PhoneGap</title>
<script type="text/javascript" charset="utf-8" src="phonegap.js"></script>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>



*phonegap.js might need to be replaced with phonegap.<version numer>.js

5A. Deploy to Simulator


  • Right click the project and go to Run As and click Android Application
  • Eclipse will ask you to select an appropriate AVD. If there isn't one, then you'll need to create it.

5B. Deploy to Device

  • Make sure USB debugging is enabled on your device and plug it into your system. (Settings > Applications > Development)
  • Right click the project and go to Run As and click Android Application