Friday, February 15, 2013

Get user last know location

There are two location provider in Android, NETWORK_PROVIDER and GPS_PROVIDER. In case you want to get last known user location, which one you should use?

It's a example to get last know location from both NETWORK_PROVIDER and GPS_PROVIDER, and choice the provider base on its accuracy.

Get user last know location


Please note that:
- More accuracy not means most recent in time.
- If no accuracy, 0.0 will be return from getLastKnownLocation() method. The code haven't concern this case.
- The code get last known location one time only, if you have to monitor continuously, and estimate the best location, refer Android documenet here.

Main code:
package com.example.androidmylocation;

import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.app.Activity;
import android.content.Context;

public class MainActivity extends Activity {
 
 TextView textView_GpsLocation, textView_NetworkLocation, textView_MyLocation;
 
 final String gpsLocationProvider = LocationManager.GPS_PROVIDER;
 final String networkLocationProvider = LocationManager.NETWORK_PROVIDER;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView_GpsLocation = (TextView)findViewById(R.id.textgpslocation);
        textView_NetworkLocation = (TextView)findViewById(R.id.textnetworklocation);
        textView_MyLocation = (TextView)findViewById(R.id.textmylocation);

        
        LocationManager locationManager = 
          (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
        
        Location lastKnownLocation_byGps = 
          locationManager.getLastKnownLocation(gpsLocationProvider);
        Location lastKnownLocation_byNetwork = 
          locationManager.getLastKnownLocation(networkLocationProvider);
        
        if(lastKnownLocation_byGps==null){
         textView_GpsLocation.setText("GPS Last Location not available");
         
         if(lastKnownLocation_byNetwork==null){
          textView_NetworkLocation.setText("Network Last Location not available");
          textView_MyLocation.setText("No Last Known Location!");
         }else{
          textView_NetworkLocation.setText("Network Location:\n" + lastKnownLocation_byNetwork.toString());
          
          textView_MyLocation.setText(
            "My Location is " + lastKnownLocation_byNetwork.getLatitude() +
            " : " + lastKnownLocation_byNetwork.getLongitude());
         }
         
         
        }else{
         textView_GpsLocation.setText("GPS Location:\n" + lastKnownLocation_byGps.toString());
         
         if(lastKnownLocation_byNetwork==null){
          textView_NetworkLocation.setText("Network Last Location not available");
          textView_MyLocation.setText(
            "My Location is " + lastKnownLocation_byGps.getLatitude() +
            " : " + lastKnownLocation_byGps.getLongitude());
         }else{
          textView_NetworkLocation.setText("Network Location:\n" + lastKnownLocation_byNetwork.toString());
          
          //Both Location provider have last location
          //decide location base on accuracy
          if(lastKnownLocation_byGps.getAccuracy() <= lastKnownLocation_byNetwork.getAccuracy()){
           textView_MyLocation.setText(
                "My Location from GPS\n" + lastKnownLocation_byGps.getLatitude() +
                " : " + lastKnownLocation_byGps.getLongitude());
          }else{
           textView_MyLocation.setText(
                "My Location from Network\n" + lastKnownLocation_byNetwork.getLatitude() +
                " : " + lastKnownLocation_byNetwork.getLongitude());
          }
          
         }
        }

    }

}


Layout:
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
    <TextView
        android:id="@+id/textgpslocation"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/textnetworklocation"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/textmylocation"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textStyle="bold" />

</LinearLayout>


In order to use both NETWORK_PROVIDER and GPS_PROVIDER, only the ACCESS_FINE_LOCATION permission is need, because it includes permission for both providers. (Permission for ACCESS_COARSE_LOCATION includes permission only for NETWORK_PROVIDER.)

download filesDownload the files.

10 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Sorry I had s small bug in previous code. so just giving you updated.
    Thanks for this post.

    private Location getBestLastKnownLocation() {

    Location lastKnownLocation_byGps = locationMgr
    .getLastKnownLocation(gpsLocationProvider);

    Location lastKnownLocation_byNetwork = locationMgr
    .getLastKnownLocation(networkLocationProvider);

    // Network Last Location not available
    if (lastKnownLocation_byGps == null
    && lastKnownLocation_byNetwork != null) {

    return lastKnownLocation_byNetwork;

    }// GPS Last Location not available
    else if (lastKnownLocation_byGps != null
    && lastKnownLocation_byNetwork == null) {

    return lastKnownLocation_byGps;

    } // Both Location provider have last location
    // decide location base on accuracy
    else if (lastKnownLocation_byGps != null
    && lastKnownLocation_byNetwork != null) {

    if (lastKnownLocation_byGps.getAccuracy() <= lastKnownLocation_byNetwork
    .getAccuracy()) {

    return lastKnownLocation_byGps;

    } else {

    return lastKnownLocation_byNetwork;
    }

    } else {

    return null;
    }

    }

    ReplyDelete
  3. I lost my phone pls tell me how to get the location...it is switched off ......

    ReplyDelete
  4. Hello Sonal Tiwari,

    Hope it can help:
    https://www.google.com/android/devicemanager
    https://maps.google.com/locationhistory/

    but...

    ReplyDelete
  5. how do you implement that code? my phone fell out of my bag at the beach and I just wanted to recover what is left of it

    ReplyDelete
  6. Hello Eric,

    I tried that but there was no data available so it did not work. I also tried lookout and google location history and neither of those worked either. I was hoping this code could help me find it's last known location but I have no clue how to use it.

    Thanks for the quick response!

    ReplyDelete
  7. Hello Eric,

    I tried all those methods along with lookout and Google location tracker and none of them worked because my phone did not have data at the time. It is now off and on on the beach somewhere so I am trying to see if there is any way of finding its last location. There is a very slim chance that anyone picked it up and it is most likely where I dropped it. If you or anyone else could help me implement that code then I would be able to get a general location to look.

    Thank you for all your help,
    Sepehr

    ReplyDelete
  8. hello Sepehr,

    if you have enable location history before, you can try https://maps.google.com/locationhistory.

    ReplyDelete