how to create service which shoul run on start up and in background?
<p>i am new to android..i have created activity in which i have to send user location info. to server...but i want to run this apps as a service in background and should run on start up as well..i have tried lot of things...but i am confused that how do i create only service..plz help..</p>

<pre><code>GPSTracker.java

package com.example.meragps;


import java.io.IOException;
import java.util.Date;
import java.util.List;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.format.DateFormat;
import android.util.Log;


public class GPSTracker extends Service implements LocationListener 
{


String imei="";
String simSerialNumber="";
String stAdd="";
String currentTime="";
String resultData="";


private static final String SOAP_ACTION = "http://tempuri.org/GetCurrentLocation";
private static final String METHOD_NAME = "GetCurrentLocation";
private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "http://"my static ip"/GPSTracker/Service1.asmx";


private final Context mContext;

// flag for GPS status
boolean isGPSEnabled = false;

// flag for network status
boolean isNetworkEnabled = false;

// flag for GPS status
boolean canGetLocation = false;

Location location; // location
double latitude; // latitude
double longitude; // longitude

 // The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1000; // 1000 meters

// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 20; // 20 minute

// Declaring a Location Manager
protected LocationManager locationManager;






public GPSTracker(Context context) 
{
    this.mContext = context;
    getLocation();




}
@Override
public int onStartCommand(Intent intent, int flags, int startId) 
{
  //TODO do something useful
    gpsTraking();
    passing();

  return Service.START_NOT_STICKY;
}

public Location getLocation() 
    {

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

        // getting GPS status
        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled &amp;&amp; !isNetworkEnabled) 
    {
            // no network provider is enabled
    } 
        else 
    {
            this.canGetLocation = true;
            // First get location from Network Provider
            if (isNetworkEnabled) 
    {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network");
                if (locationManager != null) 
    {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) 
    {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
    }
    }
    }
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
                if (location == null) 
    {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) 
    {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) 
    {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
    }
    }
    }
    }
    }

    } catch (Exception e) 
    {
        e.printStackTrace();
    }

    return location;
    }


public void gpsTraking()
{
      // create class object


    // check if GPS enabled
    if(true)
    {

        double latitude = getLatitude();
        double longitude = getLongitude();
        Geocoder gc=new Geocoder(getBaseContext());
        try 
        {
            stAdd="";
            List&lt;Address&gt; list= gc.getFromLocation(latitude, longitude, 2);

            Address a= list.get(0);

            for(int i=0;i&lt;=a.getMaxAddressLineIndex();i++)
            {
                    stAdd=stAdd+"\n "+a.getAddressLine(i);
            }
            stAdd=stAdd+" "+a.getLocality()+"\n"+a.getFeatureName();

        } 
        catch (IOException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    // \n is for new line
        CharSequence d = DateFormat.format("dd-MM-yyyy hh:mm:ss", new Date());
        currentTime= d.toString();
       Log.d("currentTime",currentTime);

        TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
     // get IMEI
     imei = tm.getDeviceId();
     // get SimSerialNumber
   simSerialNumber = tm.getSimSerialNumber();




    }

    else
    {
        /* can't get location
        GPS or Network is not enabled
        Ask user to enable GPS/network in settings*/
        showSettingsAlert();
    }

    }

public void passing()
{
      SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

       request.addProperty("strIMEINumber",imei);
       request.addProperty("strSIMNumber",simSerialNumber);
       //request.addProperty("strAddress","Rajasthan 400031");
       request.addProperty("strAddress",stAdd);
       request.addProperty("strTime",currentTime);




           SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
           envelope.dotNet = true;
           envelope.encodingStyle=SoapSerializationEnvelope.ENC;
           envelope.setOutputSoapObject(request);
           System.setProperty("http.keepAlive", "false");

            try 
            {
                HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
                androidHttpTransport.call(SOAP_ACTION, envelope);
                //SoapObject response = (SoapObject) envelope.getResponse();
                SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
                resultData= result.toString();              
                //editText.setText(resultData);
                Log.d("response", resultData);
            }
           catch (Exception e) 
            {
                // TODO Auto-generated catch block

                Log.d("My Error", ""+e.getMessage());

            }




    } 

/**
 * Stop using GPS listener
 * Calling this function will stop using GPS in your app
 * */
public void stopUsingGPS(){
    if(locationManager != null)
{
        locationManager.removeUpdates(GPSTracker.this);
}
}

/**
 * Function to get latitude
 * */
public double getLatitude()
{
    if(location != null)
{
        latitude = location.getLatitude();
}

    // return latitude
    return latitude;
}

/**
 * Function to get longitude
 * */
public double getLongitude()
{
    if(location != null)
{
        longitude = location.getLongitude();
}

    // return longitude
    return longitude;
}

/**
 * Function to check GPS/wifi enabled
 * @return boolean
 * */
public boolean canGetLocation() 
{
    return this.canGetLocation;
}

/**
 * Function to show settings alert dialog
 * On pressing Settings button will launch Settings Options
 * */
public void showSettingsAlert()
{
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

    // Setting Dialog Title
    alertDialog.setTitle("GPS is settings");

    // Setting Dialog Message
    alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

    // On pressing Settings button
    alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() 
{
        public void onClick(DialogInterface dialog,int which) 
{
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            mContext.startActivity(intent);
}
});

    // on pressing cancel button
    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() 
{
        public void onClick(DialogInterface dialog, int which) 
{
        dialog.cancel();
}
});

    // Showing Alert Message
    alertDialog.show();
}

@Override
public void onLocationChanged(Location location) 
{
}

@Override
public void onProviderDisabled(String provider) 
{
}

@Override
public void onProviderEnabled(String provider) 
{
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) 
{
}



@Override
public IBinder onBind(Intent arg0) 
{
    return null;
}
}
</code></pre>

<p>MyReceiver.java</p>

<pre><code>    package com.example.meragps;

    package com.example.meragps;

    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.util.Log;

    public class MyReceiver extends BroadcastReceiver {


     public static final String TAG = "com.example.meragps";
     @Override
     public void onReceive(Context context, Intent intent) {
      // just make sure we are getting the right intent (better safe than sorry)
      /*if( "android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) 
      {
       ComponentName comp = new ComponentName(context.getPackageName(),
       LocationLoggerServiceManager.class.getName());
       ComponentName service = context.startService(new Intent().setComponent(comp));
       if (null == service){
        // something really wrong here
        Log.e(TAG, "Could not start service " + comp.toString());
       }
      } else {
       Log.e(TAG, "Received unexpected intent " + intent.toString());   
      }*/
         try
         { 
             Intent serviceIntent = new Intent(context, GPSTracker.class);
            context.startService(serviceIntent);     
         }
         catch(Exception e)
         {
             Log.e("My Service Error",e.getMessage());
         }


    }



    }
</code></pre>

<p>MeraGPS Manifest.xml</p>

<pre><code>  &lt;manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.example.meragps"
  android:versionCode="1"
  android:versionName="1.0" &gt;
     &lt;uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /&gt; 
      &lt;uses-permission android:name="android.permission.READ_PHONE_STATE" /&gt; 
      &lt;uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /&gt;
       &lt;uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /&gt;
      &lt;uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /&gt; 
      &lt;uses-permission android:name="android.permission.INTERNET" /&gt; 
        &lt;application
    android:allowBackup="true"&gt;


   &lt;receiver android:name=".MyReceiver" 
     android:enabled="true" 
     android:exported="false"
     android:label="MyReceiver"&gt;
  &lt;intent-filter&gt;
    &lt;action android:name="android.intent.action.BOOT_COMPLETED" /&gt;
  &lt;/intent-filter&gt;
    &lt;/receiver&gt;


  &lt;intent-filter&gt;

    &lt;action android:name="android.intent.action.MAIN" /&gt;
      &lt;category android:name="android.intent.category.LAUNCHER" /&gt;
      &lt;/intent-filter&gt; 


      &lt;/application&gt;

      &lt;/manifest&gt;
</code></pre>
