Wednesday, 19 February 2014

Android Location using GPS, Network Provider

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.
Having said all the above, I just noticed that I have written an Android GPS tutorial already. Though I feel like a buffoon, somehow I have to manage now. Its okay, it will do no harm if we have two different examples for the same purpose.
There is not much we need to do, Android API takes care of everything. We need to implement LocationListener and make it a service class by extending Android Service API. Then use the Android’sLocationManager API to get the latitude and longitude location. Nothing much to discuss, lets jump into the code.

AppLocationService.java

We can use the onLocationChanged() method to continuously monitor/get the device location. 
package com.javapapers.android.androidgps;
 
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
 
public class AppLocationService extends Service implements LocationListener {
 
  protected LocationManager locationManager;
  Location location;
 
  private static final long MIN_DISTANCE_FOR_UPDATE = 10;
  private static final long MIN_TIME_FOR_UPDATE = 1000 * 60 * 2;
 
  public AppLocationService(Context context) {
    locationManager = (LocationManager) context
        .getSystemService(LOCATION_SERVICE);
  }
 
  public Location getLocation(String provider) {
    if (locationManager.isProviderEnabled(provider)) {
      locationManager.requestLocationUpdates(provider,
          MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
      if (locationManager != null) {
        location = locationManager.getLastKnownLocation(provider);
        return location;
      }
    }
    return null;
  }
 
  @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;
  }
 
}

AndroidLocationActivity.java

This is the main activity having two buttons, each for GPS and Network provider. Used a toast to show the message and if the GPS or Network or not enabled in the device then we show an alert with a shortcut to the settings.
package com.javapapers.android.androidgps;
 
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
 
public class AndroidLocationActivity extends Activity {
 
  Button btnGPSShowLocation;
  Button btnNWShowLocation;
 
  AppLocationService appLocationService;
 
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    appLocationService = new AppLocationService(
        AndroidLocationActivity.this);
 
    btnGPSShowLocation = (Button) findViewById(R.id.btnGPSShowLocation);
    btnGPSShowLocation.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View arg0) {
 
        Location gpsLocation = appLocationService
            .getLocation(LocationManager.GPS_PROVIDER);
 
        if (gpsLocation != null) {
          double latitude = gpsLocation.getLatitude();
          double longitude = gpsLocation.getLongitude();
          Toast.makeText(
              getApplicationContext(),
              "Mobile Location (GPS): \nLatitude: " + latitude
                  + "\nLongitude: " + longitude,
              Toast.LENGTH_LONG).show();
        } else {
          showSettingsAlert("GPS");
        }
 
      }
    });
 
    btnNWShowLocation = (Button) findViewById(R.id.btnNWShowLocation);
    btnNWShowLocation.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View arg0) {
 
        Location nwLocation = appLocationService
            .getLocation(LocationManager.NETWORK_PROVIDER);
 
        if (nwLocation != null) {
          double latitude = nwLocation.getLatitude();
          double longitude = nwLocation.getLongitude();
          Toast.makeText(
              getApplicationContext(),
              "Mobile Location (NW): \nLatitude: " + latitude
                  + "\nLongitude: " + longitude,
              Toast.LENGTH_LONG).show();
        } else {
          showSettingsAlert("NETWORK");
        }
 
      }
    });
 
  }
 
  public void showSettingsAlert(String provider) {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(
        AndroidLocationActivity.this);
 
    alertDialog.setTitle(provider + " SETTINGS");
 
    alertDialog
        .setMessage(provider + " is not enabled! Want to go to settings menu?");
 
    alertDialog.setPositiveButton("Settings",
        new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int which) {
            Intent intent = new Intent(
                Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            AndroidLocationActivity.this.startActivity(intent);
          }
        });
 
    alertDialog.setNegativeButton("Cancel",
        new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
          }
        });
 
    alertDialog.show();
  }
 
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
  }
 
}

Android-Location-GPS-Network-Activity

AndroidManifest.xml

Android manifest file is important here. Just note the “uses-permission” tag below. We need to those tags for accessing GPS and network provider.
<?xml version='1.0' encoding='utf-8'?>
<manifest package="com.javapapers.android.androidgps" xmlns:android="http://schemas.android.com/apk/res/android" android:versioncode="1" android:versionname="1.0">
 
    <uses-sdk android:minsdkversion="8" android:targetsdkversion="18" />
 
    <!-- to get location using GPS -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
     
  <!-- to get location using NetworkProvider -->
    <uses-permission android:name="android.permission.INTERNET" />
 
    <application android:theme="@style/AppTheme" android:label="@string/app_name" android:icon="@drawable/ic_launcher" android:allowbackup="true">
        <activity android:name="com.javapapers.android.androidgps.AndroidLocationActivity" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
 
</manifest>

Android GPS Network Provider Output

Android-GPS-Location
If GPS or Network setting are not enabled:
Enable-GPS-Network-Settings-in-Android
Android-Enable-Location-Access

No comments:

Post a Comment