Monday, 6 May 2013

Body Mass Index Calculator Android app

This tutorial will guide you to write a simple Android app using the available button and text widgets. What our app will do is ask user for his weight and the height and calculate the Body Mass Index (BMI) for him with the information that whether the user is underweight, normal or overweight.

1. Create the Eclipse Project for the Android App

First make sure you have installed the Android Development Tools by following my previous blog post, Installing Android Development Tools in Windows. After the setup, start eclipse, and click the menu File->New->Android Project.

Creating an Eclipse Project for Android Developments

In the "New Android Project" wizard, give a name to your project. 

Giving a project name for the Android App

I'm giving the name "com.blogger.android.meda.bmicalculator". Note my name forms from the package name convention of Java, starts with the opposite sequence of my url parts and then the name for the project. This will uniquely identify my project. Click 'Next' to continue.

Select the Android version you want to run the app. I will keep the Android 4.0 checked.
Selecting the Target Android SDK version

From the next window fill the information as following and click 'Finish' to finalize creating the project.

Adding Your Application Information

2. Design the User Interface (UI)
  
Designing a (UI) for an android app is very easy. You can do that by simply drag and drop of widgets like text box, buttons into the form in the WYSIWYG editor in Eclipse. To get to the UI Designer double click the res/main.xml file (shown below) under your project from Package Explorer window.
Locating the XML file to design the UI

When you open that file by double clicking, you will get to the WYSIWYG (Graphical Layout) editor. You will see there is a hello world greeting has been added by default. Just select the "Hello Wold, BMICalculatorActivity" label and delete it (by pressing the 'delete' button) to clean the form.

Get Familiar with the UI Editor


Now drag a medium size label widgets from the Platte to the form to get the following look for the UI.

Drag and Drop a Label (TextView Widget)

To edit the text of the label, right click on it and select "Edit Text...". That will give you the "Resource Chooser" form. 

The resource selection panel
From there, Click 'New String.." at the bottom of the form to declare a new string. This label should contain the String "Your Weight (lbs)". So in the new form put "Your Weight (lbs)" as the String and "weightLabel" as the R.String and click "OK".
Adding a new string


Click 'OK' in the Resource Chooser dialog box (make sure the string "weightLabel" is selected) and make sure your label contain the desired string value.

Next Drag a text field to allow user to input the weight. That should be a text field that allow user type decimal numbers (As users enter weight as decimal numbers). For that drag the text field labeled as 42.0 in the Palette to the form.
Drag and Drop a Text field (EditText widget)

Right click on the newly added text field and click "Edit ID". That allows you to provide a meaningful names to the text field. (So it is easier to refer them from your code). Give the ID "weightText" and click "OK".

Now add the following widgets to the form in the same order mentioned.
  1. A "Medium size label" and label with string value "Your Height (feets)" and R.String as "heightLabel". (You have to create a new string resource similar to the "Your Weight (lbs)" label mentioned above.)
  2. A text field with decimal numbers. Give it the id "heightText". (By right clicking the text field and clicking "Edit ID".)
  3. A Button. Right click and from the menu click "Other Properties" -> "All By Name" -> "Text" and add a new String Resource (String: Calculate and R.String: calculateButton). Similarly set the "onClick" property (You can choose it by right clicking and selecting "Other Properties" -> "All By Name"->onClick) to "calculateClickHandler". Set the button's id as "calculateButton".
  4. a Large Label. Give it the id "resultLabel". Set the text property of the label to a empty string. (with the R.String: emptyString)
That is the UI for the BMI Calculator app. Check whether you get the UI similar to this one.

The final UI for the App

If you click the main.xml tab in the bottom of the window, you can review or edit the strings and IDs you have associated with widgets. Check whether you got one similar to this one.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
 
    <TextView

        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/weightLabel"

        android:textAppearance="?android:attr/textAppearanceMedium" />
 
    <EditText
        android:id="@+id/weightText"
        android:layout_width="match_parent"

        android:layout_height="wrap_content"
        android:inputType="numberDecimal" >
 
        <requestFocus />
    </EditText>

 
    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:text="@string/heightLabel"
        android:textAppearance="?android:attr/textAppearanceMedium" />
 
    <EditText
        android:id="@+id/heightText"

        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="numberDecimal" />

 
    <Button
        android:id="@+id/calculateButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:onClick="calculateClickHandler"
        android:text="@string/calculateButton" />
 
    <TextView
        android:id="@+id/resultLabel"

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/EmptyString"
        android:textAppearance="?android:attr/textAppearanceLarge" />

 
</LinearLayout>


3. Writing Code for Your App

After designing the UI, we have to write a small piece of code, that trigger BMI calculation when user click the "Calculate" button. This is written in the src/com.blogger.android.meda.bmicalculator/BMICalculatorActivity.java file.

Check the below code and make sure you understand each step properly, specially on how to get references to the widgets in the UI and how to manipulate their texts.

package com.blogger.android.meda.bmicalculator;
 
import android.app.Activity;
import android.os.Bundle;
import android.view.View;

import android.widget.EditText;
import android.widget.TextView;
 
public class BMICalculatorActivity extends Activity {
    /** Called when the activity is first created. */

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

 
    public void calculateClickHandler(View view) {
     // make sure we handle the click of the calculator button

     if (view.getId() == R.id.calculateButton) {

      // get the references to the widgets
      EditText weightText = (EditText)findViewById(R.id.weightText);
      EditText heightText = (EditText)findViewById(R.id.heightText);
      TextView resultText = (TextView)findViewById(R.id.resultLabel);
 
      // get the users values from the widget references

      float weight = Float.parseFloat(weightText.getText().toString());
      float height = Float.parseFloat(heightText.getText().toString());
 
      // calculate the bmi value

      float bmiValue = calculateBMI(weight, height);
 
      // interpret the meaning of the bmi value
      String bmiInterpretation = interpretBMI(bmiValue);
 
      // now set the value in the result text

      resultText.setText(bmiValue + "-" + bmiInterpretation);
     }
    }
 
    // the formula to calculate the BMI index

    // check for http://en.wikipedia.org/wiki/Body_mass_index
    private float calculateBMI (float weight, float height) {

     return (float) (weight * 4.88 / (height * height));
    }

 
    // interpret what BMI means
    private String interpretBMI(float bmiValue) {

     if (bmiValue < 16) {
      return "Severely underweight";
     } else if (bmiValue < 18.5) {

      return "Underweight";
     } else if (bmiValue < 25) {

      return "Normal";
     } else if (bmiValue < 30) {

      return "Overweight";
     } else {
      return "Obese";
     }

    }
}

4. Running Your App in an Android Simulator

To create a virtual device to run you app, Goto Window -> AVD Manager from the eclipse. Click "New" to create a new android virtual device. Set the configurations similar to the below screenshot and click "CreateAVD".

Creating an Android virtual device (Simulator) to run your App

Then right click the project from the "Package Explorer" window and select "Run As" -> "Run Android Application". Wait for sometime till the devices is booted.

Android Virtual Device


Then then click the "Application Drawer" of the virtual device at the bottom and click the "BMI Calculator" app.

Running our App on Android Virtual Device


Put your weight and Height in the text boxes and check your BMI. I'm a bit overweight as all (good?) software developers should be:)


5. Running Your App in Your Android Phone

First you have to enable the "USB Debugging" mode in your phone. For that goto Settings -> Applications -> Development and check "USB debugging". And connect your phone to USB port of your computer.

Before launching the app, make sure the app is built with the SDK that compatible with your device. To check that, right click the project name from the "Package Explorer" window (in the eclipse IDE) and click "Properties". Select the Android tab, check the android version of your phone and click OK. And you have to make sure the min SDK version of the AndroidManifest.xml is also correct.

Now click, Run->Run Configuration. From the "Run Configuration" form, select the BMI project (named 'com.blogger.android.meda.bmicalculator') under the Android Application and click Target tab.

Running the App on a Manual Target (To select run it on the phone)


From there select "Manual" as the deployment target selection mode (as shown above), and press the "Run" button.

Selecting the phone as the running target


Then it show the connected android device or devices. Select the one you want to run your app and click the "OK" button. That will launch your app into your phone. Here is a screenshot of  BMI Calculor app in my phone.

Running the app on the phone

Hope you had fun developing this nice app and seeing it running on your phone. This is just a start. Hope you explore more and develop more awesome apps!!!

You can download the eclipse project and the android app that we created in this post from following links.

Download the eclipse project files (zipped)com.blogger.android.meda.bmicalculator.zip


Tuesday, 23 April 2013

Android Google Maps API v2


Android and Google Maps
This tutorial describes the usage of Google Maps in your Android application. It is based on Eclipse 4.2, Java 1.6 and Android 4.2.

1. Android Basics

The following assumes that you have already basic knowledge in Android development. Please check the Android development tutorial for the basics.

2. Google Maps

2.1. MapsView

Google provides via Google play a library for using Google Maps in your application. The following description is based on the Google Maps Android API v2 which provides significant improvements to the older API version.
The library provides the com.google.android.gms.maps.MapFragment class and the MapView class for displaying the map component.
You need to add additional information to your AndroidManifest.xml file to use Google Maps.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.vogella.android.locationapi.maps"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="17"
        android:targetSdkVersion="17" />

    <permission
        android:name="com.vogella.android.locationapi.maps.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <uses-permission android:name="com.vogella.android.locationapi.maps.permission.MAPS_RECEIVE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.vogella.android.locationapi.maps.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="your_apikey" />
    </application>

</manifest> 

2.2. MapFragment

The MapFragment class extends the Fragment class and provides the life-cycle management and the services for displaying a GoogleMap widget. GoogleMap is the class which shows the map. The MapFragment has thegetMap() method to access this class.
the LatLng class can be used to interact with the GoogleView class.

2.3. Markers

You can create markers on the map via the Marker class. This class can be highly customized.
The following code shows an example.
public class MainActivity extends Activity {
  static final LatLng HAMBURG = new LatLng(53.558, 9.927);
  static final LatLng KIEL = new LatLng(53.551, 9.993);
  private GoogleMap map;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
        .getMap();
    
    if (map!==null){
      Marker hamburg = map.addMarker(new MarkerOptions().position(HAMBURG)
          .title("Hamburg"));
      Marker kiel = map.addMarker(new MarkerOptions()
          .position(KIEL)
          .title("Kiel")
          .snippet("Kiel is cool")
          .icon(BitmapDescriptorFactory
              .fromResource(R.drawable.ic_launcher)));
    }
    
  } 
On the GoogleMap you can register a listener for the markers in your map via thesetOnMarkerClickListener(OnMarkerClickListener) method. The OnMarkerClickListener class defines the onMarkerClicked(Marker) method which is called if a marker is clicked.
Similar to you also listen to drag events and info window clicks.

2.4. Changing the GoogleView

The GoogleMap can be highly customized.
The following example code is taken from the offical Google webpage.
static final LatLng HAMBURG = new LatLng(53.558, 9.927);
static final LatLng KIEL = new LatLng(53.551, 9.993);

private GoogleMap map;
... // Obtain the map from a MapFragment or MapView.

//Move the camera instantly to hamburg with a zoom of 15.
map.moveCamera(CameraUpdateFactory.newLatLngZoom(HAMBURG, 15));

// Zoom in, animating the camera.
map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null); 

2.5. Android emulator and Google Maps

Unfortunately for using the Google Maps you have to test the application on a real device as the emulator is not supported.

3. Install Google Play services

Open the Android SDK Manager and install Extras → Google Play services
Install Google Services
Import the library which was downloaded into Eclipse via File → Import → Android → Existing Android Code into Workspace.
To use this library define a library dependency in your Android project.

4. Getting the Google Map key

4.1. Overview

To use Google Maps you need to create a valid Google Maps API key. The key is free, you can use it with any of your applications that call the Maps API, and it supports an unlimited number of users.
You get this key via the so-called Google APIS Console. You have to provide your application signature key and the application package name.
This is based on the key with which you sign your Android application during deployment. During development with Eclipse, Eclipse us automatically creates and uses a debug key.

4.2. Creating the SHA-1 for your signature key

The Eclipse debug key for signing your application can be found in the userhome/.android/debug.keystore file.
To create the SHA-1 for your debug keystore you use the keytool command from your JDK installation pointing to thedebug.keystore file.
keytool -list -v -alias androiddebugkey \
-keystore <path_to_debug_keystore>debug.keystore \
-storepass android -keypass android 
Copy the SHA-1 output, as you need this later.

4.3. Register with the Google APIs Console

You have to register in the Google APIs Console that you want to use Google Maps for Android. You can reach this console via the following link: Google APIs Console . Select here the Services entry.
Google APIs Console
Activate the Google Maps Android API v2.
Google APIs Console

4.4. Create key for your application

You need later to register your application via its package in this console together with the SHA-1 fingerprint of your signature key. For this you select the entry and click on the API Access entry. Afterwards click on the Create new Android key... entry.
Google APIs Console
Enter your SHA-1 fingerprint and the package of your application separated by a semicolon. For example you can use the com.vogella.android.locationapi.maps package.
Google APIs Console
The procedure is described in detail in the following link: Getting a Google Maps key .

5. Tutorial: Google Maps

5.1. Create Project

In the following chapter we will build an Android application which shows a GoogleMap.
Create a new Android project called com.vogella.android.locationapi.maps with an Activity calledShowMapActivity.
Change the AndroidManifest.xml file to the following code. Add the following permissions to your application.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.vogella.android.locationapi.maps"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="17"
        android:targetSdkVersion="17" />

    <permission
        android:name="com.vogella.android.locationapi.maps.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <uses-permission android:name="com.vogella.android.locationapi.maps.permission.MAPS_RECEIVE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.vogella.android.locationapi.maps.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="your_apikey" />
    </application>

</manifest> 
Get a valid API key for your application and enter this key in the AndroidManifest.xml file.

5.2. Adjust layout file

In this example we use the MapFragment. Change your layout file to the following code.
<RelativeLayout 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"
    tools:context=".MainActivity" >

    <fragment
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.MapFragment" />

</RelativeLayout> 

5.3. Activity

Change your Activity to the following.
package com.vogella.android.locationapi.maps;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends Activity {
  static final LatLng HAMBURG = new LatLng(53.558, 9.927);
  static final LatLng KIEL = new LatLng(53.551, 9.993);
  private GoogleMap map;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
        .getMap();
    Marker hamburg = map.addMarker(new MarkerOptions().position(HAMBURG)
        .title("Hamburg"));
    Marker kiel = map.addMarker(new MarkerOptions()
        .position(KIEL)
        .title("Kiel")
        .snippet("Kiel is cool")
        .icon(BitmapDescriptorFactory
            .fromResource(R.drawable.ic_launcher)));

    // Move the camera instantly to hamburg with a zoom of 15.
    map.moveCamera(CameraUpdateFactory.newLatLngZoom(HAMBURG, 15));

    // Zoom in, animating the camera.
    map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
  }

} 

5.4. Run and Test

Run and test your application. You should be able to zoom in and out and send new geo coordinates to your Activityvia the Emulator.

6. Thank you

Please help me to support this article:

Monday, 22 April 2013

Why we use dp instead of px in android ?


Due to different resolutions of devices we can’t use pixels (px) because it varies device to device ………

that’s why we use Density pixel (dp)  which is same for all devices ………… :)

Friday, 19 April 2013

BioZen Android app captures a wide range of biometric sensor data


The Department of Defense has releasedBioZen, a new mobile app designed to help service members access biofeedback services.
BioZen was developed by T2, The National Center for Telehealth and Technology, as a pilot project to study feasibility of using smartphones to receive signals from biosensor devices, including EEG, ECG, EMG, galvanic skin response (GSR), respiratory rate and temperature data all displayed within a single app.
T2 (@T2Health) bills the application as the first portable, low-cost method for clinicians and patients to use biofeedback both in and out of the clinic. While it may be a stretch to say this is the first such app to hit the market, its certainly the first to come out of a federal government agency. This could mean it will be the first to achieve significant scale as the military is likely to leverage the platform for ambulatory monitoring of all personnel. It also has potential for use by the VA to remotely monitor veterans.
“Mastering biofeedback successfully is difficult and frustrating for many people,” said Dr. David Cooper, T2 psychologist. “This app takes many of the large medical sensors found in a clinic and puts them in the hands of anyone with a smart phone. BioZen makes it easier for anyone to get started with biofeedback.”
At first glance, one thing that jumps out at me about BioZen is the fact that this application will probably be viewed by the current market leader in remote patient monitoring apps, San Diego-based AirStrip Technologies, to be in gross violation of the broad patent the company was awarded last year for the display for patient physiological data on a mobile device. AirStrip has already demonstrated clearly they have the will to defend their intellectual property, so it will be very interesting to see how they would respond were the BioZen app to achieve widespread adoption and threaten the startup’s position at the top of the mHealth market.
While the current focus for BioZen appears to be strictly the consumer or quantified self scene, it’s not a stretch to imagine a medical grade version of the app somewhere in the pipeline.
biozen3
biozen4
biozen1
The application is available only for Android currently and is compatible with several off-the-shelf sensor devices (listed below) available to consumers, ranging in price from $75-150.
NameManufacturerAvailable Parameters
BioHarness BTZephyr-TechnologyHeart rate, Respiration Rate, Skin Temp
BrainAthleteBrianAthlete(EEG) – Delta,Theta,Low Alpha,High Alpha,Low Beta,High Beta,Low Gamma,Mid Gamma,(e)Attention,(e)Meditation
MindBandNeuroSky(EEG) – Delta,Theta,Low Alpha,High Alpha,Low Beta,High Beta,Low Gamma,Mid Gamma,(e)Attention,(e)Meditation
Mindset MS001NeuroSky(EEG) – Delta,Theta,Low Alpha,High Alpha,Low Beta,High Beta,Low Gamma,Mid Gamma,(e)Attention,(e)Meditation
Mindwave MobileNeuroSky(EEG) – Delta,Theta,Low Alpha,High Alpha,Low Beta,High Beta,Low Gamma,Mid Gamma,(e)Attention,(e)Meditation
Shimmer2RShimmer-ResearchECG, GSR, EMG
BioZen is based on the open source framework Bluetooth Sensor Processing for Android (B-SPAN). Its one of ten applications developed by T2 and available on the organization’s website.

Monday, 15 April 2013

Current Location send via SMS Time scheduler in background Service Android


package com.umer.gpssms;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Service;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.telephony.SmsManager;
import android.util.Log;
import android.widget.Toast;

public class SmssendService extends Service implements LocationListener {
public double latitude = 00.00;
public double longitude = 00.00;

LocationManager locationManager;
private static final String TAG = "MyService";
public Timer timer;

@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
timer = new Timer();
onGPS();

try {
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 10 * 1000, (float) 10.0,
this);
locationManager
.requestLocationUpdates(LocationManager.GPS_PROVIDER,
90 * 1000, (float) 10.0, this);
Criteria criteria = new Criteria();
criteria.setPowerRequirement(Criteria.POWER_HIGH);
criteria.setAccuracy(Criteria.ACCURACY_FINE);
Location lastknownlocationGps = locationManager
.getLastKnownLocation("gps");

Location lastknownlocationNetwork = locationManager
.getLastKnownLocation("network");

if (lastknownlocationGps != null) {
latitude = lastknownlocationGps.getLatitude();
longitude = lastknownlocationGps.getLongitude();
Toast.makeText(this,
"GPS : lat: " + latitude + " long: " + longitude, 4000)
.show();
} else if (lastknownlocationNetwork != null) {
latitude = lastknownlocationNetwork.getLatitude();
longitude = lastknownlocationNetwork.getLongitude();
Toast.makeText(this,
"Network: lat: " + latitude + " long: " + longitude,
4000).show();
}
} catch (Exception e) {

}
}

@Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
timer.cancel();
try {
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", false);
sendBroadcast(intent);
} catch (Exception e) {

}
}

@Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {

public void run() {

// Do whatever you want to do every “INTERVAL”
sendSms();

}

}, 0, 20000);

Log.d(TAG, "onStart");

}

@Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub

latitude = arg0.getLatitude();
longitude = arg0.getLongitude();

}

@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}

@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}

public void sendSms() {
SmsManager sm = SmsManager.getDefault();
sm.sendTextMessage(" ur number like 03336851469", null, "Current Location: lat:"
+ latitude + "  lng:: " + longitude, null, null);
}

private void onGPS() {
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// ** check GPS status.
boolean isGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// ** checkListner method is start background thread which count time
if (!isGPS) {
try {
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
sendBroadcast(intent);
} catch (Exception e) {

}
} else {
}
}
}