Saturday 30 November 2013

Android GPS with LocationManager to get current location – Example

In this article, we will create an Android application which displays latitude and longitude of the current location using GPS and Android’s LocationManager API.

An extension to this application is available in the article titled “Showing current location in Google Maps with GPS and LocationManager in Android“, where current location is displayed in Google Map.
This application is developed in Eclipse ( 4.2.0 ) with ADT plugin ( 20.0.3 ) and Android SDK ( R20.0.3 )

Delete Android’s backward compatibility support library from the project, if exists
By default Eclipse ( 4.2.0) adds Android Support Library to  Android application project. For this application, we don’t need to use this support library. So the library file libs/android-support-v4.jar may be removed manually via ProjectExplorer by simply right click on the file and then clicking the menu item “delete”.

<resources>
    <string name="app_name">LocationFromGPS</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">Location From GPS</string>
    <string name="str_tv_location">Current Location</string>
</resources>
 
Update the file res/layout/activity_main.xml
 
<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" >
 
    <TextView
        android:id="@+id/tv_location"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:text="@string/str_tv_location"
        android:textStyle="bold" />
 
    <TextView
        android:id="@+id/tv_longitude"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv_location"
        android:layout_centerHorizontal="true" />
 
    <TextView
        android:id="@+id/tv_latitude"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv_longitude"
        android:layout_centerHorizontal="true"/>
</RelativeLayout>
 
Update the file res/values/styles.xml
 
<resources>
    <style name="AppTheme" parent="android:Theme" />
</resources>
 
Update the file res/values-v11/styles.xml
 
<resources>
    <style name="AppTheme" parent="android:Theme.Holo" />
</resources>
 
Update the file res/values-v14/styles.xml
 
<resources>
    <style name="AppTheme" parent="android:Theme.Holo" />
</resources>
 
Update the class MainActivity in the file src/in/wptrafficanalyzer/locationfromgps/MainActivitiy.java
 
package in.wptrafficanalyzer.locationfromgps;
 
import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;
 
public class MainActivity extends Activity implements LocationListener{
 
    LocationManager locationManager ;
    String provider;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        // Getting LocationManager object
        locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
 
        // Creating an empty criteria object
        Criteria criteria = new Criteria();
 
        // Getting the name of the provider that meets the criteria
        provider = locationManager.getBestProvider(criteria, false);
 
        if(provider!=null && !provider.equals("")){
 
            // Get the location from the given provider
            Location location = locationManager.getLastKnownLocation(provider);
 
            locationManager.requestLocationUpdates(provider, 20000, 1, this);
 
            if(location!=null)
                onLocationChanged(location);
            else
                Toast.makeText(getBaseContext(), "Location can't be retrieved", Toast.LENGTH_SHORT).show();
 
        }else{
            Toast.makeText(getBaseContext(), "No Provider Found", Toast.LENGTH_SHORT).show();
        }
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
 
    @Override
    public void onLocationChanged(Location location) {
        // Getting reference to TextView tv_longitude
        TextView tvLongitude = (TextView)findViewById(R.id.tv_longitude);
 
        // Getting reference to TextView tv_latitude
        TextView tvLatitude = (TextView)findViewById(R.id.tv_latitude);
 
        // Setting Current Longitude
        tvLongitude.setText("Longitude:" + location.getLongitude());
 
        // Setting Current Latitude
        tvLatitude.setText("Latitude:" + location.getLatitude() );
    }
 
    @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
    }
}
 
Update the file AndroidManifest.xml
 
    package="in.wptrafficanalyzer.locationfromgps"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk
        android:minSdkVersion="4"
        android:targetSdkVersion="15" />
 
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />
 
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>
 
Enable GPS in the emulator or device from Settings

Enabling GPS in Android 1.6 (Emulator)
Figure 5 : Enabling GPS in Android 1.6 (Emulator)


Set Longitude and Latitude of the location in Eclipse -> DDMS ( Perspective ) to run  this application in the emulator
Setting Longitude and Latitude in Eclipse ->DDMS Perspective
Figure 6 : Setting Longitude and Latitude in Eclipse ->DDMS Perspective

 Screenshot of the application
Showing Longitude and Latitude of the current location
Figure 7 : Showing Longitude and Latitude of the current location

 Download Source Code


 Reference
http://developer.android.com/guide/index.html