Wednesday, November 20, 2013

PHP Equivalent for DESede/CBC/PKCS5Padding

Recently I tried porting an encryption implementation to PHP from Java.

It was not possible to touch the existing encryption/ decryption implementation So the requirement is to have the similar encryption implementation in PHP which will give same result as in Java.


The Java implementation is
    public String encryptTest(String message) throws Exception {
     final MessageDigest messageDigest = MessageDigest.getInstance("md5");
     String keyString = "AB12CD3EF4";
  final byte[] passwordDigest = messageDigest.digest(keyString.getBytes("utf-8"));
     final byte[] keyBytes = paddKeyString(passwordDigest);
     final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
     cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyBytes, "DESede"), new IvParameterSpec(new byte[8]));
     final byte[] encryptedText = cipher.doFinal(message.getBytes("utf-8"));
     return Base64.encodeBase64String(encryptedText);
    }

 private byte[] paddKeyString(final byte[] passwordDigest) {
  final byte[] keyBytes = Arrays.copyOf(passwordDigest, 24);
  int pos = 16;
     for (int index = 0; index < 8;) {
      keyBytes[pos++] = keyBytes[index++];
     }
  return keyBytes;
 }

After couple of hours of trial and error , got the following PHP implementation which will produce the same result as the Java counterpart.
function encryptText_3des($plainText, $key) {
 $key = hash("md5", $key, TRUE); 
 for ($x=0;$x<8;$x++) {
  $key = $key.substr($key, $x, 1);
 }
 $padded = pkcs5_pad($plainText,
        mcrypt_get_block_size(MCRYPT_3DES, MCRYPT_MODE_CBC));
 $encrypted = base64_encode(mcrypt_encrypt(MCRYPT_3DES, $key, $padded, MCRYPT_MODE_CBC));
    return $encrypted;
}
Note: pkcs5_pad method is available here http://php.net/manual/en/ref.mcrypt.php
PHP is fun , I am going to give it little more time :)

Tuesday, November 12, 2013

Links for Configuring Apache , PHP in Windows with SSL


Installing Apache with PHP and SSL is relatively easy, But still there were couple of tricky steps. Following are the links I used for installing and configuring Apache with SSL, PHP (including cURL module).

Installing Apache in Windows

Remember to download the correct Apache binary. For example - the one I downloaded is 'httpd-2.2.25-win32-x86-openssl-0.9.8y.msi' as I required SSL also.
I choose to go with the default options.

If everything succeeds , you will be able to see "It Works!" when you try the URL "localhost" or "localhost:8080"

Installing PHP and configuring Apache

Follow this link http://www.thesitewizard.com/php/install-php-5-apache-windows.shtml
Quick summary- following entries will need to be added to httpd.conf file 
  1. LoadModule php5_module c:/php/php5apache2_2.dll
  2. AddType application/x-httpd-php .php
  3. PHPIniDir "c:/php"
Create a sample php file PHPinfo.php in the htdocs folder with content 
<!DOCTYPE html>
<html>
<body>
<?php
PHPinfo();
?>
</body>
</html>
 Try the link 'http://localhost/PHPinfo.php', You will see the information about PHP if everything succeeds.
If you are planning to use cURL module remember to enable those lines in the php.ini file
e.g.- extension=php_curl.dll
Note: If this is not working , add 'c:\php' and 'c:\php\ext' to PATH environment variable.


For me things worked only after creating a symbolic link for 'C:\Program Files (x86)\Apache Software Foundation'.





Sunday, August 11, 2013

Android Free Preschooler Number Learning Application


Kids Number Learning app is a free Android application which will help the preschoolers in learning numbers and the parents in checking the skill of their kids. 
If you are looking for a free and simple app for your preschoolers then this is a must.

Rating : 4.5/5

Game Play
The application has three modes

  • One digit
  • Two digit
  • Three digit
The application will display a number in letters based on the mode selected. Child should enter the number in digits. The app uses randomization so that the child gets different numbers every time.

Links
Market URL : https://play.google.com/store/apps/details?id=com.fortytwo.mathapps.kidsnumberlearning.activity

You may also search for 'com.fortytwo.mathapps' in PlayStore to locate the application.

Screen shots





    Saturday, June 22, 2013

    Top Free Android Game Beach Buggy Blitz Review


    Beach Buggy Blitz is a gyroscopic game which is a combination of end less running and racing.
    If you are a fan of games like Subway Surfers then you will love this game.

    Rating 4.5/5

    Game Play
    Use your beach buggy to go as far as possible. You will start with 30 seconds and there are different check points on the way which will extend the time.
    There are various obstacles on the way like giant Crabs, huts , birds and so on. Though it is kind of cool to hit these , it will slow you down from reaching the next check point.

    Positives

    • Good customization and controls.

                It is possible to control the vehicle through 
      1. Tilting the device
      2. Touching the edges of the device.
      3. Using the Game Pad.
      4. Controls for break
    • Customized for Tablets.
      • Customized version available for tablets to make use of the full potential. 
    • Graphics is good.
    • Integrated to Google Play Game Service.
      • One of the early applications to do this.
    • All together one of the best free games available in Android market.

    Negatives

    • Graphics can be still improved.
      • Even though Graphics is good and enjoyable , at some times it clearly shows the need for improvement.
      • For example, the way the birds move , behave when they get hit is not good. Some times the birds just sync in to the sand.
    • The time gets added in each check point is too short for the children.
      • Children try hitting the different obstacles on the way, so even reaching the first check point is difficult for them.
    • Other riders are not collecting the gold coins. 
      • It will be more interesting if other riders (CPU) also collect the available gold coins.
    Other Details
    Description from Google Play Store
    Drive your hot-rod beach buggy as far as you can into the uncharted depths of a mysterious tropical island!
    Swerve and smash through a gorgeously detailed and completely destructible world packed with Tiki statues, grass shacks, giant crabs, lava monsters...even yetis! Explore sun-swept beaches, secret caves, fog-shrouded swamps, ruined temples and erupting volcanoes in this action-packed quest of discovery and mayhem!
    Build a performance-boosting collection of upgrades and powerups! Unlock new vehicles like the Lightning muscle car and Rock Stomper monster truck. Upgrade your cars and customize their paint jobs. Collect wacky new characters. Unlock and upgrade amazing powerups like the fire-spitting Boost, the coin-tastic Coin Bubble, and a Shield that turns you into a unstoppable smash-everything force of destruction!
    Developer Website
    http://www.vectorunit.com/

    Screenshots






    Tuesday, June 18, 2013

    Google Play Store containing Adult Content


    What is more difficult than convincing your wife that you don't need a haircut?  It is finding a good application  easily in Google Play Store!

    To top the difficulty , there are enough adult content freely available in the play store.
    Now imagine , browsing the Play Store with your four year old daughter to find her favorite puzzle game and finding the adult games with nude pictures listed as the 'top free' apps.

    Check the screenshot below, this is taken from the 'Top Free apps'


    I do understand that , people of all age groups use Google Play Store. But being a responsible company, why cant Google set the default content filter to avoid showing the adult content?

    Until Google realize this, we will have to explicitly set the content filter to avoid adult content.

    Open Google Play Store
        Go to Context Menu
        Click on Settings

    Click on 'Content Filtering'

    Select 'Every one'/ 'Low Maturity'

    Click on 'OK' and provide a PIN when asked for.
    This should prevent the adult content from appearing.


    Saturday, June 15, 2013

    Samsung Galaxy Tab is Sluggish and Hangs after JellyBean Upgrade


    My Samsung Galaxy Tab2 10.1 started behaving weirdly all of a sudden.
    Symptoms

    • Applications are not responding
    • Accessing settings options hangs or not responding for a long time.

    The main events which happened before this issue are

    • Online upgrade to JellyBean from ICS.
    • New micro SD card is added

    Ideally none of the above should cause the device 'Sluggish', But the fact is that my tab became unusable.

    After a quick internet research , I was 'happy' to realize that there are many unfortunate souls out there who faced the same issue after JellyBean upgrade.

    'Factory Reset' seems to be the only solution for this issue.
    But before that I decided to try other options like -

    1. The data in the tablet was getting back up to Google server. This could be a costly service So disabled it from the Settings -> Backup And Restore.
    2. Installed AVG anti virus for tab : In the first scan it identified and disabled an unathorized service which was performing Network access.
    3. Uninstalled all applications.
    4. Removed SD card.

    Restarted the tablet (Press and hold the power button), and it started working normally.
    But the happiness was short lived, after some time I inserted the micro SD card again. And the hang issues started again!

    With this I agreed that Samsung won and I lost and decided to go ahead with the 'Factory Reset'.
    For doing this- select the option from Settings-> Backup and Restore-> Factory Reset-> Erase all data.

    This operation takes only couple of minutes.
    After this , the devices is back to normal state.

    Note:

    1. Backup all the data before performing the factory reset.
    2. Try other options mentioned above before executing Factory reset, it may solve the problem.


    Sunday, June 2, 2013

    Moving Apps to External Storage in Samsung Galaxy Tab


    After updating the Samsung Galaxy Tab2 to JellyBean, I realized that it is no longer possible to move the applications to external storage.

    Application like 'App2SD' is giving the error message -
    "the device does not have a real primary external storage, or the primary external storage is emulated"

    The reason is -Android removed the support for moving the apps to external storage in the newer releases of the OS! So if you are using a device with Android version later than 3.0 then moving apps to SD card is not possible.
    There is no easy and reliable app or workaround which will help you to do this.

    There are different theories why this happened -

    1. Google in general trying to kill SD cards.
      1. Remember, google devices like Nexus does not support external storage.
    2. Any thing to do with the Patent issues with Microsoft?
      1. Android is said to be the most successful mobile operating system of Microsoft, as Microsoft gets $$ for each Android phone sold. 
    Read about Google's explanation for the lack of SD card support in Nexus devices here

    May be the basic users will not even notice the lack of SD card support, But this IS a disadvantage for the advanced users. With the new games increasing in size it will be pain to decide which ones to uninstall before installing a new one.

    Looks like experts at Google are telling that 8Gb/16Gb in a mobile device is enough for any one.
    I hope they will remember another famous quote by Bill Gates 
    "640K ought to be enough for anybody "

    Monday, May 27, 2013

    Looking for Technical Leaders and Senior Developers


    There are openings in NokiaSiemensNetworks for the positions of Technical Leaders and Senior Developers for Bangalore location.

    Please send the resume , if you have

    • Minimum three years of experience.
    • Very good  technical strength.
    • Good software design knowledge.

    Sunday, May 26, 2013

    Upgrading Samsung Galaxy Tab2 to JellyBean



    To my surprise, the Samsung Galaxy Tab2 PT5100 I bought was having Android ICS. So started the experiments on how to get it upgraded to JellyBean.

    First what I tried was using the Samsung Kies software available in my laptop for upgrading the firmware, but that was not even recognizing the device!

    As any good user of Microsoft Windows does, I too uninstalled Kies completely and installed again the latest version downloaded from Kies download link . Started the new Kies application thinking that will magically upgrade my Tab to JellyBean. But life is never that easy when it comes to Samsung Kies software.

    It started giving the error "the ordinal 9272 could not be located in the ..."
    After some research - came to the possible solution of installing the latest '.Net' framework
    .Net Framework

     The moment I see such 'for programmer' error message from any software, I know things will not be smooth. Here also, on restart Kies started giving another error "

    The ordinal 7426 could not be located in the dynamic link library mfc90u.dll"

    This time possible solution was updating the VisualC++ libraries from here VisualC++ download
    Also have a look at this Microsoft discussion thread discussion forum.

    Luckily the problems with the Kies disappeared now(Frankly I was expecting to see couple of more cryptic error messages). But the Kies proudly reported that my Tab is having the latest software and no upgrade is available!
    With this I stopped my efforts to upgrade the software using Kies.
    But luckily the next day , a notification appeared in Tab indicating that an "Upgrade is available", I jumped and accepted the notification before it disappears. In around 20 min the device was upgraded to Android 4.1.2 JellyBean. Looks like we can still believe in miracles in this world!

    A request to Samsung -
    If the intention behind creating Kies is helping the customers in tasks like upgrading Firmware, then there are multiple areas which needs improvement. Starting with the first perception point of executing the software successfully. 
    But if the intention is teaching customers about what kind of 'ordinals' are in the mfc dll then it is doing the job beautifully.


      

    Sunday, April 28, 2013

    Kanban Board Digital


    Recently I attended a short meeting explaining the benefits of adopting Kanban, it was impressive.
    What Wikipedia tells about Kanban -
    Kanban is a method for developing software products and processes with an emphasis on just-in-time delivery while not overloading the software developers. In this approach, the process, from definition of a task to its delivery to the customer, is displayed for participants to see and developers pull work from a queue.

    Over all I think the Kanban implementation will help the scrum teams in managing the Feature Components in a more efficient way.

    Since having some free time now (having short vacation ;) ), I thought of developing a digital Kanban Board.

    1. This is a Java Swing based tool. No third party libraries used.
    2. No installation is required.
    3. Completely Free to use. 

    You can download the tool from here.
    Contents of the zip file are -
    • BacklogNames.txt
      • The names of the backlogs you want to have in the KanbanBoard. Feel free to edit the content.
    • KanbanBoard.jar
      • Jar file containing all Java code. You can execute this by 'double clicking ' on it or by executing the command 'java -jar KanbanBoard.jar' without quotes in a command prompt.
    • run.bat
      • Batch file to execute the program in windows machines.  Execute the batch file file double clicking on it.
    Complete source code is available here 
    Please note: This is provide AsIs and there is no guarantee on the quality. Please use it at your own risk.

    Look at the video of the tool 

    Screenshot#1

    Screenshot#2

    Current version of the tool uses the file system for persisting the data. But it can be easily enhanced to use database if required.

    In the next version I will provide the option to integrate with any database. 

    Friday, March 1, 2013

    Creating SoS Android Application in 30 minutes using TelephonyManager


    There are number of free and paid 'SoS' applications in the Android market , which will help the user to send a message with location details to pre-configured numbers.

    Let us check here how to develop such an Android application in less than 30 minutes.

    Development Environment :
    Android Development Tools Bundle
    Build - v21.0.1-543035

    We can start by creating an 'Android Application Project'



    Click 'next' on this and the next two screens.
    Select 'FullScreenActivity' in the 'Create Activity' page


    Give the activity name as 'BachaoActivity' and click on 'Finish'
    The generated activity will have some code for using systemUiHider, we can remove these as the functionality is not required.

    After doing the cleanup , the activity code will be like below


    package com.team.bachao;
    package com.team.bachao;
    
    import com.team.bachao.util.BachaoUtility;
    import android.app.Activity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Toast;
    
    /**
     * An example full-screen activity that shows and hides the system UI (i.e.
     * status bar and navigation/system bar) with user interaction.
     * 
     */
    public class BachaoActivity extends Activity {
    
     @Override
     protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
    
      setContentView(R.layout.activity_bachao);
     }
    
     @Override
     protected void onPostCreate(Bundle savedInstanceState) {
      super.onPostCreate(savedInstanceState);
    
     }
    
    }
    

    Next we need a add a on click listener to the button. This can be done by using android:onClick
    Complete activity_bachao.xml layout content is given below

    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#0099cc"
        tools:context=".BachaoActivity" >
    
        <!--
             This FrameLayout insets its children based on system windows using
             android:fitsSystemWindows.
        -->
    
        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true" >
    
            <LinearLayout
                android:id="@+id/fullscreen_content_controls"
                style="?buttonBarStyle"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical|center_horizontal"
                android:background="@color/black_overlay"
                android:orientation="horizontal"
                tools:ignore="UselessParent" >
    
                <Button
                    android:id="@+id/dummy_button"
                    style="?buttonBarButtonStyle"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="@string/dummy_button"
                    android:onClick="onBachao" />
            </LinearLayout>
        </FrameLayout>
    
    </FrameLayout>
    

    Now the basic stuff is available. Let us look at what needs to be done when user clicks on the SoS button.
    First we need to read the network information like country code, operator ID and operator name, for this we  can use the TelephonyManager provided by android.


    TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
      if (telephonyManager != null) {
       operatorInfo.countryCode = telephonyManager.getNetworkCountryIso(); 
       operatorInfo.operatorID = telephonyManager.getNetworkOperator();
       operatorInfo.operatorName = telephonyManager.getNetworkOperatorName();
      } else {
       Toast.makeText(context, "Unable to read telephony manager"  
          , Toast.LENGTH_SHORT).show();
      }
    


    Another information which will be useful to collect will be the cell location. But this will be possible only for the GSM connections

    if (telephonyManager.getPhoneType() == TelephonyManager.PHONE_TYPE_GSM) {
        GsmCellLocation cellLocation = (GsmCellLocation)telephonyManager.getCellLocation();
        operatorInfo.cellID = cellLocation.getCid();
        operatorInfo.locationAreaCode = cellLocation.getLac();
       }
    


    Next information we want to read is the location coordinates like Lat and Lon For this we can use the LocationManager provided by Android
    final LocationManager locationManager;
    locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    

    Using the location manager instance, we can find the list of location providers available in the device. Some of the possible providers are GPS_PROVIDER - Use GPS to find the location NETWORK_PROVIDER - Use Network to find the location PASSIVE_PROVIDER - This is of not much use to us in this context.
    List<String> providerNames = locationManager.getProviders(true);
      
      String providerName = null;
      if (providerNames != null && providerNames.size() > 0) {
       if (providerNames.contains(LocationManager.GPS_PROVIDER)) {
        providerName = LocationManager.GPS_PROVIDER;
       } else if (providerNames.contains(LocationManager.NETWORK_PROVIDER)) {
        providerName = LocationManager.NETWORK_PROVIDER;
       }
      }
    


    We can also find the provider from location manager which is matching a set of conditions.
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_COARSE);
    criteria.setAltitudeRequired(false);
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    String providerName = locationManager.getBestProvider(criteria, true);
    

    Once the provider is available we can request for the current location information. But for this we need to use a location listener.
    location = locationManager.getLastKnownLocation(providerName);
       
       LocationListener locationListener = new LocationListener() {
    
       public void onLocationChanged(Location location) {
        Toast.makeText(context, "on location changed " , Toast.LENGTH_SHORT).show();
        
        locationManager.removeUpdates(this);
        processLocation(context, location);
       }
    
       public void onProviderDisabled(String arg0) {
        Log.e("WTF", "provider disabled!");
        Toast.makeText(context, "disabled " , Toast.LENGTH_SHORT).show();
       }
    
       public void onProviderEnabled(String arg0) {
        // do nothing.
       }
    
       public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
        // Do nothing.
       }
       
      };
      
      locationManager.requestLocationUpdates(providerName, 0, 0, locationListener);
    

    onLocationChanged method will be called when the new location is available from the provider.

    Now we have all the information available to send to the emergency contacts. So let us send an SMS with this information. For this we can use the SmsManager provided by Android
    StringBuilder sb = new StringBuilder();
      sb.append("Emergency! Please reach out\n");
      if (location != null) {
       sb.append("Lat : " + location.getLatitude() + " Lon : " + location.getLongitude());
      }
      sb.append(" CountryCode : " + operatorInfo.countryCode);
      sb.append(" OperatorID : " + operatorInfo.operatorID);
      sb.append(" OperatorName : " + operatorInfo.operatorName);
      sb.append(" \nCellID : " + operatorInfo.cellID);
      sb.append(" LocationAreaCode : " + operatorInfo.locationAreaCode);
    
      SmsManager smsManager = SmsManager.getDefault();
      smsManager.sendTextMessage("%emergencyContactNumber%", null, sb.toString(), null, null);
    


    Replace %emergencyContactNumber% with actual mobile number. Another way to send SMS is through using Intent, but this will only open the default SMS application with the message , will not send it.
    Intent smsIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("sms:%emergencyContactNumber%"));
    smsIntent.putExtra("sms_body", sb.toString());
    context.startActivity(smsIntent);
    


    But before we use test this application, required permission requests must be added in the AndroidManifest file
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION">
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION">
    <uses-permission android:name="android.permission.READ_PHONE_STATE">
    <uses-permission android:name="android.permission.SEND_SMS">
    </uses-permission></uses-permission></uses-permission></uses-permission>
    


    Complete code for BachaoActivity.java
    package com.team.bachao;
    
    import com.team.bachao.util.BachaoUtility;
    import com.team.bachao.util.SystemUiHider;
    
    import android.annotation.TargetApi;
    import android.app.Activity;
    import android.os.Build;
    import android.os.Bundle;
    import android.os.Handler;
    import android.view.MotionEvent;
    import android.view.View;
    import android.widget.Toast;
    
    /**
     * An example full-screen activity that shows and hides the system UI (i.e.
     * status bar and navigation/system bar) with user interaction.
     * 
     * @see SystemUiHider
     */
    public class BachaoActivity extends Activity {
     private BachaoUtility handler;
    
     @Override
     protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
    
      setContentView(R.layout.activity_bachao);
      handler = new BachaoUtility(BachaoActivity.this);
      Toast.makeText(BachaoActivity.this, "Initialized", Toast.LENGTH_LONG).show();
     }
    
     @Override
     protected void onPostCreate(Bundle savedInstanceState) {
      super.onPostCreate(savedInstanceState);
    
     }
    
     public void onBachao(View view) {
      handler.bachao();
     }
     
    }
    

    Complete code for BachaoUtility.java
    package com.team.bachao.util;
    
    import java.util.List;
    
    import com.team.bachao.BachaoActivity;
    
    import android.content.Context;
    import android.location.Location;
    import android.location.LocationListener;
    import android.location.LocationManager;
    import android.os.Bundle;
    import android.telephony.SmsManager;
    import android.telephony.TelephonyManager;
    import android.telephony.gsm.GsmCellLocation;
    import android.util.Log;
    import android.widget.Toast;
    
    public class BachaoUtility {
     
     private Location location;
     private OperatorInfo operatorInfo;
     private BachaoActivity context;
     
     public BachaoUtility(BachaoActivity context) {
      this.context = context;
     }
     
     public void bachao() {
      operatorInfo = new OperatorInfo(); 
      TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
      if (telephonyManager != null) {
       operatorInfo.countryCode = telephonyManager.getNetworkCountryIso(); 
       operatorInfo.operatorID = telephonyManager.getNetworkOperator();
       operatorInfo.operatorName = telephonyManager.getNetworkOperatorName();
       if (telephonyManager.getPhoneType() == TelephonyManager.PHONE_TYPE_GSM) {
        GsmCellLocation cellLocation = (GsmCellLocation)telephonyManager.getCellLocation();
        operatorInfo.cellID = cellLocation.getCid();
        operatorInfo.locationAreaCode = cellLocation.getLac();
       }
      } else {
       Toast.makeText(context, "Unable to read telephony manager"  
          , Toast.LENGTH_SHORT).show();
      }
      
      //
      // Get the location service.
      
      final LocationManager locationManager;
      locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
      
      
      //
      // Get location coordinates
    //  Criteria criteria = new Criteria();
    //  criteria.setAccuracy(Criteria.ACCURACY_COARSE);
    //  criteria.setAltitudeRequired(false);
    //  criteria.setPowerRequirement(Criteria.POWER_LOW);
    //  String providerName = locationManager.getBestProvider(criteria, true);
      List<String> providerNames = locationManager.getProviders(true);
      
      String providerName = null;
      if (providerNames != null && providerNames.size() > 0) {
       if (providerNames.contains(LocationManager.GPS_PROVIDER)) {
        providerName = LocationManager.GPS_PROVIDER;
       } else if (providerNames.contains(LocationManager.NETWORK_PROVIDER)) {
        providerName = LocationManager.NETWORK_PROVIDER;
       }
      }
    
       
      if (providerName != null) {
       location = locationManager.getLastKnownLocation(providerName);
       
       LocationListener locationListener = new LocationListener() {
    
       public void onLocationChanged(Location location) {
        Toast.makeText(context, "on location changed " , Toast.LENGTH_SHORT).show();
        
        locationManager.removeUpdates(this);
        processLocation(context, location);
       }
    
       public void onProviderDisabled(String arg0) {
        Log.e("WTF", "provider disabled!");
        Toast.makeText(context, "disabled " , Toast.LENGTH_SHORT).show();
       }
    
       public void onProviderEnabled(String arg0) {
        // do nothing.
       }
    
       public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
        // Do nothing.
       }
       
      };
      
      locationManager.requestLocationUpdates(providerName, 0, 0, locationListener);
      }
      
      sendMessage();
    
      //
      // Send facebook update
      
      //
      // Send twitter update
      
      //
      // record audio
      
      //
      // record video
      
      //
      // Send mail
     }
     
     public void processLocation(BachaoActivity context, Location location) {
      Toast.makeText(context, "Lat : " + location.getLatitude()
        + "\n Lon : " + location.getLatitude(), Toast.LENGTH_LONG).show();
      this.location = location;
      //
      // Send message
      sendMessage();
      
     }
    
     private void sendMessage() {
      StringBuilder sb = new StringBuilder();
      sb.append("Emergency! Please reach out\n");
      if (location != null) {
       sb.append("Lat : " + location.getLatitude() + " Lon : " + location.getLongitude());
      }
      sb.append(" CountryCode : " + operatorInfo.countryCode);
      sb.append(" OperatorID : " + operatorInfo.operatorID);
      sb.append(" OperatorName : " + operatorInfo.operatorName);
      sb.append(" \nCellID : " + operatorInfo.cellID);
      sb.append(" LocationAreaCode : " + operatorInfo.locationAreaCode);
    
    //  Intent smsIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("sms:%emergencyContactNumber%"));
    //  smsIntent.putExtra("sms_body", sb.toString());
    //  context.startActivity(smsIntent);
      
      SmsManager smsManager = SmsManager.getDefault();
      smsManager.sendTextMessage("%emergencyContactNumber%", null, sb.toString(), null, null);
     }
    }
    

    In the next version I will integrate audio/ video recording, sending the data via mail , updating in facebook/twitter.