Wednesday, May 30, 2018

Fetching Location using GPS, Network provider in Android

Overview


One of the unique features of mobile applications is location awareness. Mobile users take their devices with them everywhere, and adding location awareness to your app offers users a more contextual experience. The location APIs available in Google Play services facilitate adding location awareness to your app with automated location tracking, geofencing, and activity recognition.

Earlier getting the location with the couple of API is simple but getting the accurate location We will be using Fused Location API that combines signals from GPSWi-Fi, and cell networks, as well as accelerometergyroscopemagnetometer and other sensors to provide more accurate results.


GPS and network providers are two different ways to get Android device location (latitude and longitude). GPS and network location providers have got their own advantages and we may have to use both in sync. In in-door situations GPS may not provide the location quickly and network location provider is quick. Network location provider uses our mobile connectivity provider and will give the nearest tower location. GPS gives the exact location of where we are standing.


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.

Request this permission with the uses-permission element in your app manifest, as the following code snippet shows:
<manifest ... >
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
   <uses-permission android:name="android.permission. ACCESS_COARSE_LOCATION" />
   <uses-permission android:name="android.permission.INTERNET" />
</manifest>

We need to implement LocationListener and make it a service class by extending Android Service API. Then use the Android’s LocationManager API to get the latitude and longitude location. Nothing much to discuss, lets jump into the code.

public class GPSTracker extends Service implements LocationListener {
    private final Context mContext;
// flag for GPS status // flag for network status // flag for GPS status Location location; // location
// The minimum distance to change Updates in meters
// The minimum time between updates in milliseconds
// Declaring a Location Manager
OnCancel onCancel; public GPSTracker(Context context,OnCancel onCancel) {
this.mContext = context;
this.onCancel=onCancel;
getLocation();
}
public interface OnCancel{
public void onCancel(Context context);
} public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE); // getting GPS status
.isProviderEnabled(LocationManager.GPS_PROVIDER); // getting network status
.isProviderEnabled(LocationManager.NETWORK_PROVIDER); if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
this.canGetLocation = true;
// First get location from Network Provider
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
} } catch (Exception e) {
e.printStackTrace();
} return location;
} /** * Stop using GPS listener
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
} /** * Function to get latitude
if(location != null){
latitude = location.getLatitude();
} // return latitude
} /** * Function to get longitude
if(location != null){
longitude = location.getLongitude();
} // return longitude
} /** * Function to check GPS/wifi enabled *
return this.canGetLocation;
} /**
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext); // Setting Dialog Title // Setting Dialog Message
alertDialog.setCancelable(false);
// On pressing Settings button
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
}); // on pressing cancel button
public void onClick(DialogInterface dialog, int which) { dialog.cancel();
onCancel.onCancel(mContext);
}
}); // Showing Alert Message
} @Override
public void onLocationChanged(Location location) {
} @Override
public void onProviderDisabled(String provider) {
} @Override
public void onProviderEnabled(String provider) {
} @Override
public void onStatusChanged(String provider, int status, Bundle extras) {
} @Override
public IBinder onBind(Intent arg0) {
return null;
} }
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
 double latitude; 
// latitude    
double longitude; 
// longitude
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; 
// 10 meters
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; 
// 1 minute
protected LocationManager locationManager;
isGPSEnabled = locationManager
isNetworkEnabled = locationManager
} else {
if (isNetworkEnabled) {
if (isGPSEnabled) {
* Calling this function will stop using GPS in your app     
* */    public void stopUsingGPS(){
* */    
public double getLatitude(){
return latitude;
* */    
public double getLongitude(){
return longitude;
 @return boolean     
* */    
public boolean canGetLocation() {
* Function to show settings alert dialog     
* On pressing Settings button will lauch Settings Options    
 * */    
public void showSettingsAlert(){
alertDialog.setTitle("GPS is settings");
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
alertDialog.show();

Use this code to get the Location in any Activity;
boolean isGPSSetings = false;
void gpsTrackerCode(){
gps = new GPSTracker(YourActivity.this, new GPSTracker.OnCancel() {
@Override
public void onCancel(Context context) {

}
});
if(gps.canGetLocation()){
isGPSSetings = false;
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
if (latitude==0&&longitude==0){
showProgressDialog();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
gpsTrackerCode();
}
},200);
return;
}
hideProgressDialog();
Location loc=new Location("");
loc.setLatitude(latitude);
loc.setLongitude(longitude);
PrefHelper.getInstance(WheatherActivity.this).setWeatherLocation(loc);
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new WeatherFragment())
.commitAllowingStateLoss();
}else{
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
gps.showSettingsAlert();
isGPSSetings = true;
}
},500);
}
}





No comments:

Post a Comment

Webbooks introduction & Implementation

Webhook  Webhooks are also sometimes referred to as  “Reverse APIs” . In APIs,  the client-side application calls (consumes) the server-side...