blog

Home / DeveloperSection / Blogs / Get Current Location in Android

Get Current Location in Android

Manoj Pandey2447 14-Apr-2016

In this blog I explaining to get current location as well as find update location. In android have two types to get location


1.   GPS Location Provider

2.   Network Location Provider


Network Provider is fast is compare than GPS. GPS is very slow and its drain more battery. Network Provider depend on cell tower and it does not return accurate address but GPS provider give us accurate address.

Here I am creating a sample which give us accurate current address as well as whenever location updates it also provide updates location accurately.

1.   First of all we have need to allow permission in manifest file to access GPS. Add following permission in manifest.xml file

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET" />  <uses-permission android:name="android.permission.ACCESS_GPS"/>

2.   Add Textview Control in activity.xml file 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
    <TextView
        android:id="@+id/tvFullLocation"
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

3. Add below code in MainActivity.class 


packag com.example.msclient009.androidlocation; 

import android.app.Activity;

import android.content.Context;

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.media.audiofx.BassBoost;

import android.media.audiofx.EnvironmentalReverb;

import android.net.Uri;

import android.os.AsyncTask;

import android.provider.Settings;

import android.support.v4.app.FragmentActivity;

import android.support.v7.app.ActionBarActivity;

import android.os.Bundle;

import android.util.Log;

import android.view.Menu;

import android.view.MenuItem;

import android.view.View;

import android.widget.Button;

import android.widget.TextView;

import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;

import com.google.android.gms.common.api.GoogleApiClient;

import com.google.android.gms.location.FusedLocationProviderApi;

import com.google.android.gms.location.LocationRequest;

import com.google.android.gms.location.LocationServices;

import java.util.List;

import java.util.Locale;

public class MainActivity extends Activity implements LocationListener {

    LocationManager locationManager;

    //Geocoding is the process of transforming a street address or other description of a location into a // (latitude, longitude) coordinate.

    Geocoder geocoder;

    TextView textView;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        textView = (TextView) findViewById(R.id.tvFullLocation);

        //  GeoCoder and Location Manager

        geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());

        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        // check GPS is enable or not

        boolean statusOfGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

        if (statusOfGPS) {

            try {

                // apply for get current address

                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);

             // We can get address according to  minimum requirement such as on update distance 50 meters

                // or after duration 10 minute 

            // locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100000, 50, this);

            } catch (Exception ex) {

                ex.printStackTrace();

            }

        }

    }

 

    public void updateCurrentLocation(final String text) {

        runOnUiThread(new Runnable() {

            @Override

            public void run() {

                textView.setText("Location -: " + text);

            }

        });

    }

    @Override

    public void onLocationChanged(final Location location) {

        try {

            // When location change return Location reference and we can get latitude and longitude                                // of  current address

            // GeoCoder return all address of location

   List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 10);

            if (addresses != null) {

                if (addresses.size() > 0) {

                    Address address = addresses.get(0);

                    String addressText = String.format(

                            "%s, %s, %s",

                            // If there's a street address, add it

                            address.getMaxAddressLineIndex() > 0 ? address

                                    .getAddressLine(0) : "",

                            // Locality is usually a city

                            address.getLocality(),

                            // The country of the address

                            address.getCountryName());

                    updateCurrentLocation(addressText); 

                }

            } 

        } catch (Exception ex) {

        }

    }

 

    @Override

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

    } 

    @Override

    public void onProviderEnabled(String provider) {

    }

    @Override

    public void onProviderDisabled(String provider) {

    }

}



4.   Now run your application. See Output of your current address

 Get Current Location in Android


Updated 14-Mar-2018

Leave Comment

Comments

Liked By