Send GPS data while App is running background in Android - android

I developed app that getting GPS data and send to Server. So i want to get GPS data while my app is running background in Android device. I have search in many websites, but i could not answer.
I use 2 class. One of them is Main class and another is GPSTracker class. Now i give some part code of 2 class.
Main Class
public class Request extends Activity {
public static Float longitude;
public static Float latitude;
public static int ID;
public static String URL="http://xxx.xxx";
GPSTracker gps;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_request);
final Button button_send_info = (Button)findViewById(R.id.button_send_info);
final TextView show_infos = (TextView) findViewById (R.id.textView1);
gps = new GPSTracker(Request.this);
if(gps.canGetLocation()){
latitude = (float) gps.getLatitude();
longitude = (float) gps.getLongitude();
// \n is for new line
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
if( Build.VERSION.SDK_INT >= 8){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
button_send_info.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("latitude", latitude.toString()));
postParameters.add(new BasicNameValuePair("longitude", longitude.toString()));
String response = null;
try
{
response = CustomHttpClient.executeHttpPost(URL, postParameters);
String res=response.toString();
show_infos.setText(res);
}
catch (Exception e)
{
//hata alanı
}
}
});
GPSTracker Class;
public class GPSTracker extends Service implements LocationListener {
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
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 (isGPSEnabled) {
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;
}
How can i do it?

There is a component called Service in android. It provides background activity. You can perform background process in it. Service has no GUI. You can write a GPS fetching code there.
Have a look at simple tutorial of Service components from Vogella.

Related

Storing latitude and longitude in CSV file every 15 minutes

I want to access users location i.e latitude and longitude in every 15 minutes and store them in a CSV file. How can I do this?
I have a GPSTracker class:
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 15; // 15 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
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 (isGPSEnabled) {
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
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS() {
if (locationManager != null) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
and in MainActivity:
File root = Environment.getExternalStorageDirectory();
File gpxfile = new File(root, "mydata.csv");
try {
writer = new FileWriter(gpxfile);
writeCsvHeader("DateTime", "Latitude", "Longitude");
writeCsvData(""+strDate,latitude,longitude);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
private void writeCsvHeader(String h1, String h2, String h3) throws IOException {
String line = String.format("%s,%s,%s\n", h1,h2,h3);
writer.write(line);
}
private void writeCsvData(String date, double lat, double lon) throws IOException {
String line = String.format("%s,%f,%f\n", date, lat, lon);
writer.write(line);
}
for CSV I have referenced
http://antipastohw.pbworks.com/w/page/41913616/Write%20CSV%20files%20onto%20SD%20Card%20Storage
For doing an repetitive task you can use Handler like,
handler.postDelayed(new Runnable(){
#Override
public void run() {
// get Location or do whatever you want
}
}, (15 * 60 * 1000));
In this case getLocation() will call after every 15 min.
May this way possible
Timer timer = new Timer();
timerTask = new TimerTask() {
Handler mnhandler = new Handler();
#Override
public void run() {
mnhandler.post(new Runnable() {
#Override
public void run() {
//Use ur method which store CSV file
}
});
}
};
timer.schedule(timerTask, start, duration);

Get String from Location Android

I found a great function which gives me possibility to get Location quickly.
After that i want to display its (longitude and latitude) but it doest work still i get 0.0 / 0.0.
here's code
What should i do if i want display this latitude and longitude mostly I'm interested in function getLastKnownLocation because i want display this data without using GPS or Internet
public class MainActivity extends Activity implements OnClickListener
{
private static final long MIN_TIME_BW_UPDATES = 0;
private static final float MIN_DISTANCE_CHANGE_FOR_UPDATES = 0;
public EditText lokalizacja;
public Button pobierz;
private static Context context;
LocationManager locationManager;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude ; // latitude
double longitude; // longitude
public static Context getContext()
{
return context;
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lokalizacja = (EditText) findViewById(R.id.editText1);
pobierz = (Button) findViewById(R.id.button1);
pobierz.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, (LocationListener) this);
Log.d("Network", "Network Enabled");
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 (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, (LocationListener) this);
Log.d("GPS", "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();
}
String napis = String.valueOf(latitude+ "\n" + longitude);
lokalizacja.setText(napis);
return location;
}
}
As flow never enter the else part due the following condition
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
You need to have condition something like this
if (!isGPSEnabled || !isNetworkEnabled) {
// no network provider is enabled
} else {
or first check for GPS and then after network
For the first time, for getting your current location, you want to enable gps or network in your device. After getting lat and lng create a preference and save these values to preference. So make some changes in your getLocation() method.
If gps and network are disable try to return the saved value from preference.
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />

GPS location changing in Android application

I've followed this tutorial for GPS tracking in Android application with this class:
GPSTracker.java
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
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 (isGPSEnabled) {
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;
}
#Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
#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;
}
and this is the Activity using the previous class:
AndroidGPSTrackingActivity.java
package com.example.gpstracking;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class AndroidGPSTrackingActivity extends Activity {
Button btnShowLocation;
// GPSTracker class
GPSTracker gps;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
// show location button click event
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// create class object
gps = new GPSTracker(AndroidGPSTrackingActivity.this);
// check if GPS enabled
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
// \n is for new line
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
});
}
}
How can I receive new position updates from the AndroidGPSTrackingActivity.java ?
How can I get latitude and longitude in AndroidGPSTrackingActivity taken by onLocationChanged that is in GPSTracker class ?
many thanks
I can't write comments yet, so I try here:
I would create a Handler in your Activity and assign it to the the GPSTracker Class:
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
// new GPS Informations
// get it by gps.getLatitude() for example
};
};
gps = new GPSTracker(AndroidGPSTrackingActivity.this, handler);
In your GPSTracker Class you have to change the constructor of course:
Handler mHandler;
public GPSTracker(Context context, Handler handler){
...
this.mHandler = handler;
}
And then, just send the info, that the location has changed to your activity:
#Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
mHandler.sendEmptyMessage(0);
}

Android GPS using old locations

Im trying to learn more about location services in android and am attempting to build an app which can locate an Android device and send it's latitude and longitude to a server. I've had everything working as expected for a while, but am still being bothered by a small bug. When I send the command from the server to locate the device the first time, the device returns a recent, but old, location such as a road I drove on the same day.
On the second time the device receives a command from the server to locate the device, the device returns an accurate location.
Here is the relevant code:
LocationTracker.java
public class LocationTracker extends Service implements LocationListener {
//flag for GPS Status
boolean isGPSEnabled = false;
//flag for network status
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
double latitude;
double longitude;
//The minimum distance to change updates in metters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10*1000; //10,000 meters
//The minimum time beetwen updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 10000; // 10,000 minutes
//Declaring a Location Manager
protected LocationManager locationManager;
public void fetchLocation(Context context) {
getLocation(context);
if (canGetLocation())
{
String stringLatitude = String.valueOf(latitude);
String stringLongitude = String.valueOf(longitude);
Log.i("Location: ", stringLatitude + " " + stringLongitude);
new MyAsyncTask().execute(stringLatitude, stringLongitude);
}
else
{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
Log.i("Error: ", "Cannot get location");
}
}
public Location getLocation(Context context)
{
try
{
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
//getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
//getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled)
{
// no network provider is enabled
}
else
{
this.canGetLocation = true;
//if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled)
{
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);
updateGPSCoordinates();
}
}
}
//If no GPS, get location from Network Provider
if (isNetworkEnabled && !isGPSEnabled)
{
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);
updateGPSCoordinates();
}
}
}
}
catch (Exception e)
{
//e.printStackTrace();
Log.e("Error : Location", "Impossible to connect to LocationManager", e);
}
return location;
}
public void updateGPSCoordinates()
{
if (location != null)
{
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
*/
public void stopUsingGPS()
{
if (locationManager != null)
{
locationManager.removeUpdates(LocationTracker.this);
}
}
/**
* Function to get latitude
*/
public double getLatitude()
{
if (location != null)
{
latitude = location.getLatitude();
}
return latitude;
}
/**
* Function to get longitude
*/
public double getLongitude()
{
if (location != null)
{
longitude = location.getLongitude();
}
return longitude;
}
/**
* Function to check GPS/wifi enabled
*/
public boolean canGetLocation()
{
return this.canGetLocation;
}
#Override
public void onLocationChanged(Location location)
{
double newLat = location.getLatitude();
double newLong = location.getLongitude();
String stringNewLatitude = String.valueOf(newLat);
String stringNewLongitude = String.valueOf(newLong);
Log.i("New Location: ", stringNewLatitude + " " + stringNewLongitude);
new MyAsyncTask().execute(stringNewLatitude, stringNewLongitude);
}
#Override
public void onProviderDisabled(String provider)
{
}
#Override
public void onProviderEnabled(String provider)
{
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
public IBinder onBind(Intent intent)
{
return null;
}
Why is my location updating as an old location the first time it tries, and a correct location on the second time?
Also note that I would also like to remove requestLocationUpdates seen here:
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
because it causes a handler on dead thread warning, but when I removed it my device stopped acquiring my location. This may be part of the problem.
I would greatly appreciate any help!
It's because you're using getLastKnownLocation().
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
getLastKnownLocation(String Provider) :
Returns a Location indicating the data from the last known location fix obtained from the given provider.
This can be done without starting the provider. Note that this location could be out-of-date, for example if the device was turned off and moved to another location.

Fast and Frequent location Update in android..?

public void getUserLocation() {
Location location;
TextView lon = (TextView) findViewById(R.id.textView2);
TextView lat = (TextView) findViewById(R.id.textView3);
boolean GpsEnable = false, NetworkEnabled = false;
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// String locationProvider = LocationManager.GPS_PROVIDER;
GpsEnable = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
NetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// locationManager.requestLocationUpdates(locationProvider,0,0,locationListner);
if (!GpsEnable && !NetworkEnabled) {
Toast.makeText(getBaseContext(), "No Provider Availabe",
Toast.LENGTH_SHORT);
} else {
if (NetworkEnabled)
Toast.makeText(getBaseContext(), "Network Provider Available",
Toast.LENGTH_SHORT);
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
lon.setText("Latitude" + location.getLatitude());
lat.setText("Longitude " + location.getLongitude());
}
if (GpsEnable) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
lon.setText("Latitude" + location.getLatitude());
lat.setText("Longitude " + location.getLongitude());
}
}
}
}
}
I had done both with GPS and network provider.. I want to know how we get exact current location in Google maps? Is there any way or algorithm by which i can get longitude and latitude of my location using internally Google maps?
Thanks in Advance
I have Followed this Tutorial for Fast Update and Initial SetUp for GoogleMap v2
Initial Setup Here
Alternative for LocationUpdate
Hope this could help...:)
public void retriveLocation(){
try {
String locCtx = Context.LOCATION_SERVICE;
LocationManager locationmanager = (LocationManager) context.getSystemService(locCtx);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationmanager.getBestProvider(criteria, true);
locationmanager.requestLocationUpdates(provider, 0, 0, this);
} catch (Exception e) {
}
}
Hope this code can be useful for retrieving fast location updates.
Here is the code that I basically use to get a constant location signal using Google Play Services.
public class MyActivity
extends
Activity
implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener,
LocationListener
{
private LocationClient locClient;
private LocationRequest locRequest;
// Flag that indicates if a request is underway.
private boolean servicesAvailable = false;
#Override
protected void onCreate( Bundle savedInstanceState )
{
// Check that Google Play services is available
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
// If Google Play services is available
if (ConnectionResult.SUCCESS == resultCode) {
servicesAvailable = true;
} else {
servicesAvailable = false;
}
if(locClient == null) {
locClient = new LocationClient(this, this, this);
}
if(!locClient.isConnected() || !locClient.isConnecting())
{
locClient.connect();
}
// Create the LocationRequest object
locRequest = LocationRequest.create();
// Use high accuracy
locRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locRequest.setInterval(INTERVAL);
locRequest.setFastestInterval(INTERVAL);
}
#Override
public void onLocationChanged( Location location )
{
// DO SOMETHING WITH THE LOCATION
}
#Override
public void onConnectionFailed( ConnectionResult arg0 )
{
}
#Override
public void onConnected( Bundle arg0 )
{
// Request location updates using static settings
locClient.requestLocationUpdates(locRequest, this);
}
#Override
public void onDisconnected()
{
if(servicesAvailable && locClient != null) {
//
// It looks like after a time out of like 90 minutes the activity
// gets destroyed and in this case the locClient is disconnected and
// calling removeLocationUpdates() throws an exception in this case.
//
if (locClient.isConnected()) {
locClient.removeLocationUpdates(this);
}
locClient = null;
}
}
}
This is the crux of it anyway and I culled this from other sources so I can't really claim it but there it is.

Categories

Resources