Thursday, May 26, 2011

Get Current Location (GPS Position) in Android Native Java Code

Get Current Location (GPS Position) in Android Native Java Code

Generally till now while developing Android Apps or I should say PhoneGap Supported Apps, to get the current GPS location, I always referred to the following function:

navigator.geolocation.getCurrentPosition(onSuccess, onError);

which instantly gives all the required location details like latitude, longitude, accuracy etc.

But then, how do I get these details which I'm not using a web app or I should say not a PhoneGap Application but a pure native Android Application or an Android Service, So for the same I tried researching  on the various articles and documents and finally arrived at the solution as follows:

package com.mayuri.location;
import java.sql.Timestamp;
import java.util.Date;
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.util.Log; 
import android.widget.TextView;
import android.widget.Toast;


public class LocationSample extends Activity {   
TextView tv;
    @Override 
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);         
    tv = (TextView)this.findViewById(R.id.txtLocation);
    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    LocationListener ll = new mylocationlistener();
    lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, ll);    
    }  
    private class mylocationlistener implements LocationListener {
    @Override 
    public void onLocationChanged(Location location) {    
     Date today = new Date();  
Timestamp currentTimeStamp = new Timestamp(today.getTime());
        if (location != null) {
        Log.d("LOCATION CHANGED", location.getLatitude() + "");
        Log.d("LOCATION CHANGED", location.getLongitude() + "");
        Strig str = "\n CurrentLocation: "+
        "\n Latitude: "+ location.getLatitude() + 
        "\n Longitude: " + location.getLongitude() + 
        "\n Accuracy: " + location.getAccuracy() + 
        "\n CurrentTimeStamp "+ currentTimeStamp;         
          Toast.makeText(LocationSample.this,str,Toast.LENGTH_LONG).show();
          tv.append(str);               
        } 
    } 
    @Override
    public void onProviderDisabled(String provider) {
    Toast.makeText(LocationSample.this,"Error onProviderDisabled",Toast.LENGTH_LONG).show();
    }    
    @Override
    public void onProviderEnabled(String provider) {
    Toast.makeText(LocationSample.this,"onProviderEnabled",Toast.LENGTH_LONG).show();
    }
    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    Toast.makeText(LocationSample.this,"onStatusChanged",Toast.LENGTH_LONG).show();
    }
    }
}

The heart of the Logic lies in the 'LocationManager' class, which provides an access to the System location services.  

'requestLocationUpdates' gives the periodic location updates as per the arguments specified.


The method, 'onLocationChanged' of the Interface 'LocationListener' gives the entire location details like Latitude, Longitude, Accuracy etc which can be used as per our requirements, currently In the example I'm periodically updating the text view as well as showing the Toast Popup of the location details along with the Current Timestamp.

Most Important thing to be remembered while using the LocationService in Android Application is to modify the Application manifest file with the following,

        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
        <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />      
        <uses-permission android:name="android.permission.INTERNET" />    
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />


Thats all on this from my end!!

Happy Coding :-))

~ Mayuri

12 comments:

Ashwini said...

Thanks a lot...:)

Phil said...

Really great... thanks for sharing your code. It helped to get me started...

Just 2 things..

1) Strig str => should be String str

2) You can switch the
LocationManager.NETWORK_PROVIDER for LocationManager.GPS_PROVIDER if you want to get finer position updates outside.

europhia core said...

Does this get the location using Native GPS, not Assisted GPS. WHat it means is that will you be able to get coordinates WITHOUT cell coverage ?

europhia core said...
This comment has been removed by the author.
Rekha said...

hi mam,
when i execute this code in the emulator it couldn't not run. showing"unfortunately Location(name of the project) has stopped".pls can u tel me wht's wrong or anytoher setting to made while running this code

Nezam,The Soldier Of Allah said...

@Rekha

Please turn ON the gps on the simulator and try to add the permission to android manifest file

anish said...

I want to get the current location of my place when i am executing this code there is some error in the location so please can anyone help me to resolve it

anish said...

i want to develop a application called HELP which has the features like send the messages to five persons in the from the selected contacts in emergency by pressing help button and the message should also include the current location of the peson

Barkat said...
This comment has been removed by the author.
sachin thawari said...

Hey Hi ,I want to display the current location of my friend,is it possible in android ,if yes tell me the how i can get the his location by using his number.

If possible plz mail me info according ==>> sthawari@yahoo.com

sachin thawari said...

Hey Hi ,I want to display the current location of my friend,is it possible in android ,if yes tell me the how i can get the his location by using his number.

If possible plz mail me info according ==>> sthawari@yahoo.com

Ahsan Ahmed said...

i am having the error for the line : tv = (TextView)this.findViewById(R.id.txtLocation);
(txtLocation can not be resolved or is not a field)

and for line: Toast.makeText(LocationSample.this,str,Toast.LENGTH_LONG).show();
(Locationsample can not be resolved to a type.)
kindly help