Friday, September 16, 2011

Location Based Services in Android


Location Based Services
  •   Android gives our applications access to the location services through the classes in the android.location package.
  •  We can utilize GPS and Android’s Network Location Provider to acquire the user location.
  •   GPS provider:
    •  GPS is most accurate.
    •  It works only outdoors.
    •  Quickly consumes battery power.
    •  Doesn't return the location as quickly as user want.
  •  Network Location Provider:
    •  Determines the user location using the cell-tower and Wi-Fi signals.
    • It works indoors and outdoors.
    • Responds faster.
    • It uses less battery.
  • To obtain the user location we can use both GPS and Network Location Provider or just one.
  • Key classes:
    • LocationManager.
    • LocationProvider.
  • LcoationManager provides access to the system location services. This is done through getSystemService.
  • Using LocationManager class we can obtain periodic updates of the locations.
  • We can request location updates of devices using requestLocationUpdates() method. This method takes four parameters:
    •  Provider - The name of the location provider you wish to use.
    • minTime - The minimum time interval for notifications, in milliseconds.
    •  minDistance - The minimum distance interval for notifications, in meters.
    • listener - An object whose onLocationChanged() method will be called for each location update.
  •  In order to receive location updates we must request user permissions.
    •    NETWORK_PROVIDER – android.permission.ACCESS_COARSE_LOCATION.
    • GPS_PROVIDER -  android.permission.ACCESS_FINE_LOCATION.
  • The following statement should be added to the AndroidManifest.xml
    • < uses-permission android:name=”android.permission.ACCESS_FINE_LOCATION” />
  • If we are using both NETWORK_PROVIDER and GPS_PROVIDER, then we need to request only the ACCESS_FINE_LOCATION permission, because it includes permission for both providers.
  •   Using DDMS we can simulate location data in several ways through Emulator Controls. They are as follows:
    • Manually send individual longitude/latitude coordinates to the device.
    • Use a GPX file describing a route for playback to the device.
    • Use a KML file describing individual place marks for sequenced playback to the device.
  • To send location data through DDMS we must be sure that a device selected in the Devices panel. (Available from Window > Show View > Other > Devices).
Ø  Example:
Main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
    <Button
       android:id="@+id/retrieve_location_button"
       android:text="Get Location"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       />
</LinearLayout>

GeoCoderActivity.java:
          package com.snigdha.android;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class GeoCoderExampleActivity extends Activity {
    /** Called when the activity is first created. */
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1;
    private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000;
    protected LocationManager locationManager;
   protected Button retrieveLocationButton;
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
 retrieveLocationButton = (Button) findViewById(R.id.retrieve_location_button);
 locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER,                              MINIMUM_TIME_BETWEEN_UPDATES,MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
                                   new MyLocationListener()   );
   retrieveLocationButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) { showCurrentLocation();
                               }
                       });                              
                       }  
   protected void showCurrentLocation() {
   Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    if (location != null) {
  String message = String.format( "Current Location \n Longitude: %1$s \n Latitude: %2$s",   location.getLongitude(), location.getLatitude()   );
   Toast.makeText(GeoCoderExampleActivity.this, message,                    Toast.LENGTH_LONG).show();
                  }
              } 
   private class MyLocationListener implements LocationListener {
       public void onLocationChanged(Location location) {
    String message = String.format( "New Location \n Longitude: %1$s \n Latitude: 2$s",   location.getLongitude(), location.getLatitude()       );
 Toast.makeText(GeoCoderExampleActivity.this, message, oast.LENGTH_LONG).show();
                           }
      public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(GeoCoderExampleActivity.this, "Provider status changed",
                                       Toast.LENGTH_LONG).show();
                           }
 public void onProviderDisabled(String s) {
Toast.makeText(GeoCoderExampleActivity.this, "Provider disabled by the user. GPS turned off", Toast.LENGTH_LONG).show();
        }
 public void onProviderEnabled(String s) {                        Toast.makeText(GeoCoderExampleActivity.this, "Provider enabled by the user. GPS turned on", Toast.LENGTH_LONG).show();
                           }
}
}
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.snigdha.android"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="8" />
   
    <uses-permission  android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

 <application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".GeoCoderExampleActivity"
                  android:label="@string/app_name">
      <intent-filter>
            <action android:name="android.intent.action.MAIN" />
      <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
        </activity>

    </application>                                     
</manifest>
Screen Shots:

Figure-1                                                    


Figure - 2
Figure - 4
Figure - 3


                                                                                                                                                


  •  Figure-2 displaying the current location data retrieved by the provider.
  • Figure-3 and Figure -4 showing a toast messages when the GPS is disabled and enabled by the user.

No comments:

Post a Comment