Location Services
There are two ways to get a users location in our application
1. android.location.LocationListener : using Android Location API
This is a part of the Android API.
2. com.google.android.gms.location.LocationListener :
This is present in the Google Play Services API.
Using the location services e provided in the android.location package.
(LocationManager and LocationProvider)
A LocationProvider provides location data using several metrics, and you can access providers
through a LocationManager
In order to use location services, our activity needs to implement the LocationManager Interface.
It is through this interface that an application can access the system’s location services. These
services basically allow the application to obtain periodic updates of the device’s geographical
location.
It also helps in firing an application specific intent when the device comes within the proximity of a
specified location.
The last-known Location is also available directly from the manager.
The Location class is a Java bean that represents all the location data available from a particular
snapshot in time.
The central class that you will use to interact with location-related data on Android is the
LocationManager.
LocationManager class provides the facility to get latitude and longitude coordinates of current
location.
The class in which you want to get location should implement LocationListener and override all its
abstract methods.
LocationListener
The LocationListener interface, which is part of the Android Locations API is used for receiving
notifications from the LocationManager when the location has changed. The LocationManager class
provides access to the systems location services.
The LocationListener class needs to implement the following methods.
onLocationChanged(Location location) : Called when the location has changed.
onProviderDisabled(String provider) : Called when the provider is disabled by the user.
onProviderEnabled(String provider) : Called when the provider is enabled by the user.
onStatusChanged(String provider, int status, Bundle extras) : Called when the provider status
changes.
Instance of LocationManager
You do not instantiate this class directly; instead, retrieve it through
Context.getSystemService(Context.LOCATION_SERVICE).
LocationManager locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
The android.location has two means of acquiring location data:
LocationManager.GPS_PROVIDER: Determines location using satellites. Depending on the
conditions, this provider may take a while to return a location fix
LocationManager.NETWORK_PROVIDER: Determines location based on the availability of nearby cell
towers and WiFi access points. This is faster than GPS_PROVIDER
USeful methods of location class
location.getLatitude()
location.getLongitude()
location.distanceBetween(location.getLatitude(),
location.getLongitude(),lastlatitide,lastlongitude,results)
geoLocation() - search for a particular location given as string parameter by converting to
appropriate latittue, longitude
Location class hosts the latitude and longitude.
To get the current location the following code snippet is used.
Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener)
method of the LocationManager class is used to register the current activity to be notified
periodically by the named
Example
provider.locationManager.requestLocationUpdates(provider, 500, 1, mylistener);
first param - location provider
secod param - time in ms
third param - distance in meters
fourth param - listener instance
Location Permissions
There are two permissions available to request location. The accuracy of the location is determined
by the kind of permission requested and priority level.
ACCESS_COARSE_LOCATION: Gives location approximately equivalent to a city block.
ACCESS_FINE_LOCATION: Gives precise location, sometimes in few meters or feet when combined
with High Priority accuracy.
To get Current Location in Android Using Location Manager
Add following permissions to AndroidManifest.xml file.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Following lines of code helps in getting current location.
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 5, this);
In requestLocationUpdates() method the 2nd argument is time in milliseconds and 3rd argument is
distance in meters. we have 5000 and 5 that means after every 5 seconds and 5 meter the current
location is fetched.
To get coordinates use getLatitude() and getLongitude() method on variable of Location class.
Whenever location is changed it can be fetched inside onLocationChanged() method.
Application that fetches current location on button click and displays it in textview.
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/locationText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/getLocationBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="88dp"
android:layout_marginTop="244dp"
android:text="Show latitde and longitude"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
"
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.locationapp">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity.java
package com.example.locationapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements LocationListener{
Button getLocationBtn;
TextView locationText;
LocationManager locationManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getLocationBtn = (Button)findViewById(R.id.getLocationBtn);
locationText = (TextView)findViewById(R.id.locationText);
getLocationBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getLocation();
}
});
}
void getLocation() {
try {
locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
this);
locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
// Toast.makeText(MainActivity.this,
Double.toString(location.getLatitude()), Toast.LENGTH_LONG).show();
}
catch(SecurityException e) {
e.printStackTrace();
}
}
@Override
public void onLocationChanged(Location location) {
locationText.setText("Current Location: " + location.getLatitude() + ", "
+ location.getLongitude());
Toast.makeText(MainActivity.this, Double.toString(location.getLatitude()),
Toast.LENGTH_LONG).show();
}
@Override
public void onProviderDisabled(String provider) {
Toast.makeText(MainActivity.this, "Please Enable GPS and Internet",
Toast.LENGTH_LONG).show();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
}
IF no display when button is clicked - >on android device go to Settings, Location Services, App-Level
Permission and enable permission for the app
0
You can add this document to your study collection(s)
Sign in Available only to authorized usersYou can add this document to your saved list
Sign in Available only to authorized users(For complaints, use another form )