I am researching receiving gps time with an android device in order to make an application. I am getting the time from multiple devices and comparing the results. The application will need to get time accurate to within around 5 milliseconds (the comparisons will depend heavily on time). I've been looking around and found some articles such as https://groups.google.com/forum/#!topic/android-developers/VwbqlB9ugLg
and
How do I get the most accurate time with Android?
These articles make it seem like it is not possible but as they are a little older I was wondering if there was any change in technology making it possible or possibly a fancy way around this to have all the devices share the same time?
Code I put together to test out my idea. It is suppose to request a location change every 1 second and update the locations. Two problems occur, first it only updates every ~5 seconds (after reading documentation it seems 5 seconds is the fastest the FusedApi will update) and two it seems the location.getTime is using the device time not gps.
package temp;
import android.app.Activity;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
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.common.api.PendingResult;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import java.text.DateFormat;
import java.util.Date;
public class MainActivity extends Activity implements LocationListener,
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
private String mLastUpdateTime;
private Location currentLocation;
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private static final String TAG = "MainActivity";
private static final long INTERVAL = 1000 * 1;
private static final long FATEST_INTERVAL = 1000 * 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.e(TAG, "On Create . . . . .");
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
createLocationRequest();
Thread myThread = null;
Runnable myRunnableThread = new CountDownRunner();
myThread = new Thread(myRunnableThread);
myThread.start();
}
public void doWork() {
runOnUiThread(new Runnable() {
public void run() {
try {
//Log.e("Main", "Inside doWork");
TextView txtCurrentDeviceTime = (TextView) findViewById(R.id.DeviceTime);
TextView txtCurrentGPSTime = (TextView) findViewById(R.id.GpsTime);
Date dt = new Date();
String time = dt.toString();
txtCurrentDeviceTime.setText(time);
Date d = new Date(currentLocation.getTime());
txtCurrentGPSTime.setText(d.toString());
} catch (Exception e) {
}
}
});
}
class CountDownRunner implements Runnable {
// #Override
public void run() {
Log.e("Main", "Inside Run");
while (!Thread.currentThread().isInterrupted()) {
try {
doWork();
//Log.e("Main", "After doWork");
Thread.sleep(1000); // Pause of 1 Second
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (Exception e) {
}
}
}
}
protected void createLocationRequest(){
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FATEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
public void onConnected(Bundle bundle) {
Log.e(TAG, "onConnected: Connected - " + mGoogleApiClient.isConnected());
startLocationUpdates();
}
protected void startLocationUpdates() {
PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
Log.e(TAG, "Location update started ");
}
#Override
public void onConnectionSuspended(int i) {
stopLocationUpdates();
Log.e(TAG, "On Connection Suspended " + mGoogleApiClient.isConnected());
Toast.makeText(getApplicationContext(), "No Network Connection", Toast.LENGTH_LONG).show();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.e(TAG, "Connection failed " + connectionResult.toString());
stopLocationUpdates();
Log.e(TAG, "onConnectionFailed " + mGoogleApiClient.isConnected());
Toast.makeText(getApplicationContext(), "No Network Connection", Toast.LENGTH_LONG).show();
}
#Override
public void onLocationChanged(Location location) {
Log.e(TAG, "Firing onLocationChanged.........");
currentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
Log.e(TAG, "Location update stopped");
}
#Override
public void onStart() {
super.onStart();
mGoogleApiClient.connect();
Log.e(TAG, "MainActivity Started, GoogleApi Connection: " + mGoogleApiClient.isConnected());
}
}
Related
I have two different devices running the same code but executing them in different ways. Whenever I minimize the application and then pull it back up on the tablet it works the way I wanted it to, by not creating another timer. When I run it on the phone though and minimize/maximize it another timer is started, thus having 2 run at the same time. Why does this work differently on the two devices or is there something else happening I am not seeing. (I know I need to create a background service and that the way I am doing it currently is incorrect)
Tablet Specs
Android Version: 4.4.2
Kernal Version: 3.4.67
Model Number: DL701Q
Phone Specs
Android Version: 4.4.2
Kernal Version: 3.4.0+
Software/Model: VS450PP1
Code
Main Class
package temp;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import android.location.Geocoder;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
public class MainActivity extends Activity implements LocationListener,
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
private Button bLogout, bWebsite;
private ImageButton bLogData;
private TextView etLabel;
private UserLocalStore userLocalStore;
private String mLastUpdateTime;
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private static final String TAG = "MainActivity";
private static final long INTERVAL = 1000 * 15;
private static final long FATEST_INTERVAL = 1000 * 30;
private Geocoder geocoder;
AddressOps addressOps;
TimerUpdate timerUpdate;
int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.e(TAG, "On Create . . . . .");
if(!isGooglePlayServicesAvailable()){
startActivity(new Intent(MainActivity.this, login.class));
finish();
Toast.makeText(getApplicationContext(), "Please update GooglePlay Servies to use this Application", Toast.LENGTH_LONG).show();
}else {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
createLocationRequest();
userLocalStore = new UserLocalStore(this);
this.geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
addressOps = new AddressOps(this.geocoder);
etLabel = (TextView) findViewById(R.id.etEmailLabel);
bLogout = (Button) findViewById(R.id.bLogout);
bLogData = (ImageButton) findViewById(R.id.DataLog);
bWebsite = (Button) findViewById(R.id.website);
bLogData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String pressStatus = "3";
timerUpdate.update(pressStatus);
}
});
bLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
userLocalStore.clearuserData();
userLocalStore.setUserLoggedIn(false);
timerUpdate.stopTimerTask();
startActivity(new Intent(MainActivity.this, login.class));
finish();
}
});
bWebsite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://temp"));
startActivity(browserIntent);
}
});
}
}
private void displayUserDetails(){
User user = userLocalStore.getLoggedInUser();
String userdisplay = "Logged in as: " + user.username;
etLabel.setText(userdisplay);
}
private boolean authenticate(){
return userLocalStore.getUserLoggedIn();
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
Log.e(TAG, "Network Check");
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
return false;
}
}
protected void createLocationRequest(){
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FATEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
public void onConnected(Bundle bundle) {
Log.e(TAG, "onConnected: Connected - " + mGoogleApiClient.isConnected());
startLocationUpdates();
}
protected void startLocationUpdates() {
PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
Log.e(TAG, "Location update started ");
}
#Override
public void onConnectionSuspended(int i) {
stopLocationUpdates();
Log.e(TAG, "On Connection Suspended " + mGoogleApiClient.isConnected());
Toast.makeText(getApplicationContext(), "No Network Connection", Toast.LENGTH_LONG).show();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.e(TAG, "Connection failed " + connectionResult.toString());
stopLocationUpdates();
Log.e(TAG, "onConnectionFailed " + mGoogleApiClient.isConnected());
Toast.makeText(getApplicationContext(), "No Network Connection", Toast.LENGTH_LONG).show();
}
#Override
public void onLocationChanged(Location location) {
Log.e(TAG, "Firing onLocationChanged.........");
if(this.timerUpdate != null) {
timerUpdate.location = location;
}else{
Log.e(TAG, "Timer is null");
}
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
Log.e(TAG, "Location update stopped");
}
#Override
protected void onPause() {
super.onPause();
Log.e(TAG, "MainActivity Paused");
}
#Override
public void onResume() {
super.onResume();
Log.e(TAG, "MainActivity Resumed");
if (mGoogleApiClient.isConnected()) {
if(!isGooglePlayServicesAvailable()){
startActivity(new Intent(MainActivity.this, login.class));
Toast.makeText(getApplicationContext(), "Please update GooglePlay Servies to use this Application", Toast.LENGTH_LONG).show();
finish();
}
}
}
#Override
public void onStart() {
super.onStart();
if(authenticate() == true){
displayUserDetails();
if(this.timerUpdate == null) {
this.timerUpdate = new TimerUpdate(this, addressOps);
Log.e(TAG, "Timer created: " + count);
timerUpdate.startTimer();
}
}else{
startActivity(new Intent(MainActivity.this, login.class));
finish();
}
mGoogleApiClient.connect();
Log.e(TAG, "MainActivity Started, GoogleApi Connection: " + mGoogleApiClient.isConnected());
}
#Override
public void onStop() {
super.onStop();
Log.e(TAG, "MainActivity Stopped");
}
}
Timer class
package temp;
import android.content.Context;
import android.location.Location;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;
import java.util.Timer;
import java.util.TimerTask;
public class TimerUpdate {
private Timer timer;
private TimerTask timertask;
public boolean timerScheduled = false;
private final Handler handler = new Handler();
private static final String TAG = "UpdateTimer";
AddressOps addressOps;
private Context mainContext;
private UserLocalStore userLocalStore;
public Location location;
public TimerUpdate(Context context, AddressOps ops){
Log.e(TAG, "Constructor");
initializeTimerTask();
this.mainContext = context;
this.addressOps = ops;
userLocalStore = new UserLocalStore(context);
}
private void initializeTimerTask(){
Log.e(TAG, "InitializeTimerTask");
timertask = new TimerTask() {
public void run(){
handler.post(new Runnable(){
public void run(){
Log.e(TAG, "TimerTask Ran");
String status = "5";
update(status);
}
});
}
};
}
public void startTimer(){
Log.e(TAG, "startTimer");
timer = new Timer();
timer.schedule(timertask, 1000 * 30, 1000 * 60 * 2);
timerScheduled = true;
Log.e(TAG, "Start Schedule created");
}
public void stopTimerTask(){
Log.e(TAG, "StopTimer");
if (timer != null){
timer.cancel();
timer = null;
Log.e(TAG, "Timer Stopped");
}
}
public void update(String status) {
Log.e(TAG, "Update initiated .............");
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
if(isNetworkAvailable()){
String address = addressOps.getAddressString(lng, lat);
if(address != null) {
User user = userLocalStore.getLoggedInUser();
ServerRequest request = new ServerRequest(this.mainContext);
request.storeLocationInBackground(lat, lng, user.username, address, status);
Toast.makeText(this.mainContext, "Longitude: " + lng + "\nLatitude: "
+ lat + "\nAddress: " + address, Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this.mainContext, "Unable to retrieve Address", Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(this.mainContext, "No Network Connection" + "\nLatitude: " + lat
+ "\nLongitude: " + lng, Toast.LENGTH_LONG).show();
}
} else {
Log.e(TAG, "There is no current Location Data in Update");
Toast.makeText(this.mainContext, "There is no current Location Data ....", Toast.LENGTH_SHORT).show();
}
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager)mainContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
Log.e(TAG, "Network Check");
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
onStart() is called even when "minimizing/maximize" (see the details of Activity lifecycle.) If the authenticate() method returns false, the timer class is re-created blindly. The old instance of the timer may stick around, depending on what it is doing / registering with other components.
Trying to write an application that will synchronize time between multiple devices. I have researched using gps, device, and NTP time. From what I understand the time I am getting from gps is the time the device received the location information thus dependent on device time. System time won't work for obvious reasons and thus I experimented with NTP time. I have all 3 being displayed on 2 devices and I am not sure why NTP doesn't work. Can anyone explain to me why or what I am doing wrong? (I apologize for some of the bad coding practices, just threw this together for testing purposes)
package temp.gpstime;
import android.app.Activity;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
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.common.api.PendingResult;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import org.apache.commons.net.ntp.NTPUDPClient;
import org.apache.commons.net.ntp.TimeInfo;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class MainActivity extends Activity implements LocationListener,
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
private long mLastUpdateTime;
private Location currentLocation;
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private static final String TAG = "MainActivity";
private static final long INTERVAL = 1000 * 5;
private static final long FATEST_INTERVAL = 1000 * 5;
private boolean hasFirst = false;
private int count = 0;
private Location first;
long NTPReturnedTime;
boolean setTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.e(TAG, "On Create . . . . .");
final TextView txtTimeDiff = (TextView) findViewById(R.id.timedifference);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
createLocationRequest();
final Button updateDifference = (Button) findViewById(R.id.Update);
updateDifference.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
long timer = System.currentTimeMillis() - mLastUpdateTime;
long difference = System.currentTimeMillis() - currentLocation.getTime() - timer;
txtTimeDiff.setText(difference + "");
}
});
new getTimeNTP().execute();
Thread myThread = null;
Runnable myRunnableThread = new CountDownRunner();
myThread = new Thread(myRunnableThread);
myThread.start();
}
public void doWork() {
runOnUiThread(new Runnable() {
public void run() {
try {
TextView txtCurrentGPSTime = (TextView) findViewById(R.id.GpsTime);
TextView txtCurrentDeviceTime = (TextView) findViewById(R.id.DeviceTime);
TextView txtFirstFix = (TextView) findViewById(R.id.gpsfixtime);
TextView txtFirstSysFix = (TextView) findViewById(R.id.systemFixTime);
TextView txtTimeDiff = (TextView) findViewById(R.id.timedifference);
TextView txtNTPtime = (TextView) findViewById(R.id.NTPTime);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
sdf.setTimeZone(TimeZone.getTimeZone("gmt"));
String gpsTime = sdf.format(new Date(currentLocation.getTime()));
txtCurrentGPSTime.setText(gpsTime);
String deviceTime = sdf.format(System.currentTimeMillis());
txtCurrentDeviceTime.setText(deviceTime);
if(setTime) {
String NTPTimeFormat = sdf.format(new Date(NTPReturnedTime));
txtNTPtime.setText(NTPTimeFormat);
NTPReturnedTime += 50;
}
if (!hasFirst && first != null) {
txtFirstFix.setText(sdf.format(new Date(first.getTime())));
txtFirstSysFix.setText(sdf.format(new Date(System.currentTimeMillis())));
txtTimeDiff.setText((System.currentTimeMillis() - first.getTime()) + "");
hasFirst = true;
}
} catch (Exception e) {
}
}
});
}
class CountDownRunner implements Runnable {
// #Override
public void run() {
Log.e("Main", "Inside Run");
while (!Thread.currentThread().isInterrupted()) {
try {
doWork();
Thread.sleep(50);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (Exception e) {
}
}
}
}
protected void createLocationRequest(){
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FATEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
public void onConnected(Bundle bundle) {
Log.e(TAG, "onConnected: Connected - " + mGoogleApiClient.isConnected());
startLocationUpdates();
}
protected void startLocationUpdates() {
PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
Log.e(TAG, "Location update started ");
}
#Override
public void onConnectionSuspended(int i) {
stopLocationUpdates();
Log.e(TAG, "On Connection Suspended " + mGoogleApiClient.isConnected());
Toast.makeText(getApplicationContext(), "No Network Connection", Toast.LENGTH_LONG).show();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.e(TAG, "Connection failed " + connectionResult.toString());
stopLocationUpdates();
Log.e(TAG, "onConnectionFailed " + mGoogleApiClient.isConnected());
Toast.makeText(getApplicationContext(), "No Network Connection", Toast.LENGTH_LONG).show();
}
#Override
public void onLocationChanged(Location location) {
// Log.e(TAG, "Firing onLocationChanged.........");
mLastUpdateTime = System.currentTimeMillis();
if(count == 0){
first = location;
count++;
}
currentLocation = location;
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
Log.e(TAG, "Location update stopped");
}
#Override
public void onStart() {
super.onStart();
mGoogleApiClient.connect();
Log.e(TAG, "MainActivity Started, GoogleApi Connection: " + mGoogleApiClient.isConnected());
}
public class getTimeNTP extends AsyncTask<Void, Void, Void> {
InetAddress inetAddress;
private String TIME_SERVER = "time-a.nist.gov";
TimeInfo timeInfoServer;
NTPUDPClient timeClient;
long returnTime;
SimpleDateFormat sdf;
#Override
protected Void doInBackground(Void... params) {
timeClient = new NTPUDPClient();
try {
inetAddress = InetAddress.getByName(TIME_SERVER);
} catch (UnknownHostException e) {
e.printStackTrace();
}
try {
timeInfoServer = timeClient.getTime(inetAddress);
returnTime = timeInfoServer.getReturnTime();
Log.e("Main", returnTime + "");
} catch (IOException e) {
e.printStackTrace();
}
NTPReturnedTime = returnTime;
setTime = true;
return null;
}
}
}
The program below is used for vibrating the phone when some destination is reached.This works perfectly when the screen is on but doesnt when the device is idle(SCREEN OFF) any suggestion so that it works while screen is off is very much appreciated.I am a novice in Android Development sorry if the question is stupid.`
package com.sset.jibin.wakemethere;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.os.Bundle;
import android.os.SystemClock;
import android.os.Vibrator;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import java.text.DateFormat;
import java.util.Date;
public class LocationActivity extends Activity implements
LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "LocationActivity";
private static final long INTERVAL = 1000 * 10;
private static final long FASTEST_INTERVAL = 1000 * 5;
Button btnFusedLocation;
TextView tvLocation;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mCurrentLocation;
String mLastUpdateTime;
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate ...............................");
//show error dialog if GoolglePlayServices not available
if (!isGooglePlayServicesAvailable()) {
finish();
}
createLocationRequest();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
setContentView(R.layout.activity_location);
tvLocation = (TextView) findViewById(R.id.tvLocation);
btnFusedLocation = (Button) findViewById(R.id.btnShowLocation);
btnFusedLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
updateUI();
}
});
}
#Override
public void onStart() {
super.onStart();
Log.d(TAG, "onStart fired ..............");
mGoogleApiClient.connect();
}
#Override
public void onStop() {
super.onStop();
Log.d(TAG, "onStop fired ..............");
mGoogleApiClient.disconnect();
Log.d(TAG, "isConnected ...............: " + mGoogleApiClient.isConnected());
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
return false;
}
}
#Override
public void onConnected(Bundle bundle) {
Log.d(TAG, "onConnected - isConnected ...............: " + mGoogleApiClient.isConnected());
startLocationUpdates();
}
protected void startLocationUpdates() {
PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
Log.d(TAG, "Location update started ..............: ");
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(TAG, "Connection failed: " + connectionResult.toString());
}
#Override
public void onLocationChanged(Location location) {
Log.d(TAG, "Firing onLocationChanged..............................................");
mCurrentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
updateUI();
}
private void updateUI() {
Log.d(TAG, "UI update initiated .............");
if (null != mCurrentLocation) {
double l = mCurrentLocation.getLatitude();
double le = mCurrentLocation.getLongitude();
String lat = String.valueOf(l);
String lng = String.valueOf(le);
tvLocation.setText("At Time: " + mLastUpdateTime + "\n" +
"Latitude: " + lat + "\n" +
"Longitude: " + lng + "\n" +
"Accuracy: " + mCurrentLocation.getAccuracy() + "\n" +
"Provider: " + mCurrentLocation.getProvider());
MapsActivity MA = new MapsActivity();
Location loc1 = new Location("");
loc1.setLatitude(l);
loc1.setLongitude(le);
Log.d("=====>", "t5");
SharedPreferences preff = getSharedPreferences("ll", 0);
String lal = preff.getString("la", null);
String lnl = preff.getString("ln", null);
Log.d("=====>", "t5.1");
Log.d("=====>", lal);
Log.d("=====>", lnl);
double la = Double.parseDouble(lal);
double ln = Double.parseDouble(lnl);
Location loc2 = new Location("");
loc2.setLatitude(la);
loc2.setLongitude(ln);
Log.d("=====>", "t6");
float distanceInMeters = loc1.distanceTo(loc2);
Log.d("=====>", "t7");
if (distanceInMeters < 20) {
Log.d("=====>", "FOUND");
Vibrator v = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
v.vibrate(500);
}
} else {
Log.d(TAG, "location is null ...............");
}
}
#Override
protected void onPause() {
super.onPause();
stopLocationUpdates();
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
Log.d(TAG, "Location update stopped .......................");
}
#Override
public void onResume() {
super.onResume();
if (mGoogleApiClient.isConnected()) {
startLocationUpdates();
Log.d(TAG, "Location update resumed .....................");
}
}
}
`
You have to move your location logic to a service. so it will run even if the application is leave by the user or screen is off.
Recently I am learning about using gps and marker to pinpoint my current location. And now I try to modify so that the code will be able to keep track my current location and calculate my total distance travelled when there is updated in my location. At the beginning, it works find. But after 2-3 minutes, my app start hang and prompt me force close as no response from my application.
Below is my code:
public class WhereAmINowActivity extends Activity {
//declaration of variables
public void getPrevActivityValue(){
Intent intent = getIntent();
// get the value from prev activity
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start_distance);
getPrevActivityValue();
btnStart = (Button)findViewById(R.id.btnStart);
btnStop = (Button)findViewById(R.id.btnStop);
distance = (TextView)findViewById(R.id.distance);
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
provider = locationManager.getBestProvider(criteria, true);
location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
locationManager.requestLocationUpdates(provider, TWO_MIN, HUNDRED_METERS ,locationListener);
addListenerOnBtnStart();
addListenerOnBtnStop();
}
public void addListenerOnBtnStart(){
btnStart.setOnClickListener(new View.OnClickListener(){
public void onClick(View paramAnonymousView){
if(!startPressed){
// Initialize the variables of current and old location coordinates
}
catch (Exception e){
e.printStackTrace();
}
}
else{
// Do nothing
}
}
});
}
public void addListenerOnBtnStop(){
btnStop.setOnClickListener(new View.OnClickListener(){
public void onClick(View paramAnonymousView){
try{
if(connected to internet is true)
// Do something here
}
else{
// prompt message to notify user connectivity is not available
}
}
catch (Exception e){
e.printStackTrace();
}
}
});
}
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider){
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider){ }
public void onStatusChanged(String provider, int status,
Bundle extras){ }
};
private void updateWithNewLocation(Location location) {
// Update the current location, old coordinates and get the address
}
}
Some of the value is passed from previous activity by using getIntent().
can anyone help me figure out which part I done it wrongly?
Addition:
I removed the overlay and tested on merely the location listener.
I found that when it run about 2-3minutes, the interface of my app will not response on what I pressed (as I declare two button- start and stop). When I pressed the stop button, there is nothing happened, then a force close message is prompt to me. Is this the part I did wrong? How should I correct it so that it can work as like a normal distance calculation when I walk by using GPS?
I have solved this exact problem in my open source Gps Tracker. The full working android project is here:
https://github.com/nickfox/GpsTracker/tree/master/phoneClients/android
and the class that does the tracking is below. You want to take a look at the variable called totalDistanceInMeters.
package com.websmithing.gpstracker;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class LocationService extends Service implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener,
LocationListener {
private static final String TAG = "LocationService";
// use the websmithing defaultUploadWebsite for testing and then check your
// location with your browser here: https://www.websmithing.com/gpstracker/displaymap.php
private String defaultUploadWebsite;
private boolean currentlyProcessingLocation = false;
private LocationRequest locationRequest;
private LocationClient locationClient;
#Override
public void onCreate() {
super.onCreate();
defaultUploadWebsite = getString(R.string.default_upload_website);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// if we are currently trying to get a location and the alarm manager has called this again,
// no need to start processing a new location.
if (!currentlyProcessingLocation) {
currentlyProcessingLocation = true;
startTracking();
}
return START_NOT_STICKY;
}
private void startTracking() {
Log.d(TAG, "startTracking");
if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(this) == ConnectionResult.SUCCESS) {
locationClient = new LocationClient(this,this,this);
if (!locationClient.isConnected() || !locationClient.isConnecting()) {
locationClient.connect();
}
} else {
Log.e(TAG, "unable to connect to google play services.");
}
}
protected void sendLocationDataToWebsite(Location location) {
// formatted for mysql datetime format
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getDefault());
Date date = new Date(location.getTime());
SharedPreferences sharedPreferences = this.getSharedPreferences("com.websmithing.gpstracker.prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
float totalDistanceInMeters = sharedPreferences.getFloat("totalDistanceInMeters", 0f);
boolean firstTimeGettingPosition = sharedPreferences.getBoolean("firstTimeGettingPosition", true);
if (firstTimeGettingPosition) {
editor.putBoolean("firstTimeGettingPosition", false);
} else {
Location previousLocation = new Location("");
previousLocation.setLatitude(sharedPreferences.getFloat("previousLatitude", 0f));
previousLocation.setLongitude(sharedPreferences.getFloat("previousLongitude", 0f));
float distance = location.distanceTo(previousLocation);
totalDistanceInMeters += distance;
editor.putFloat("totalDistanceInMeters", totalDistanceInMeters);
}
editor.putFloat("previousLatitude", (float)location.getLatitude());
editor.putFloat("previousLongitude", (float)location.getLongitude());
editor.apply();
final RequestParams requestParams = new RequestParams();
requestParams.put("latitude", Double.toString(location.getLatitude()));
requestParams.put("longitude", Double.toString(location.getLongitude()));
Double speedInMilesPerHour = location.getSpeed()* 2.2369;
requestParams.put("speed", Integer.toString(speedInMilesPerHour.intValue()));
try {
requestParams.put("date", URLEncoder.encode(dateFormat.format(date), "UTF-8"));
} catch (UnsupportedEncodingException e) {}
requestParams.put("locationmethod", location.getProvider());
if (totalDistanceInMeters > 0) {
requestParams.put("distance", String.format("%.1f", totalDistanceInMeters / 1609)); // in miles,
} else {
requestParams.put("distance", "0.0"); // in miles
}
requestParams.put("username", sharedPreferences.getString("userName", ""));
requestParams.put("phonenumber", sharedPreferences.getString("appID", "")); // uuid
requestParams.put("sessionid", sharedPreferences.getString("sessionID", "")); // uuid
Double accuracyInFeet = location.getAccuracy()* 3.28;
requestParams.put("accuracy", Integer.toString(accuracyInFeet.intValue()));
Double altitudeInFeet = location.getAltitude() * 3.28;
requestParams.put("extrainfo", Integer.toString(altitudeInFeet.intValue()));
requestParams.put("eventtype", "android");
Float direction = location.getBearing();
requestParams.put("direction", Integer.toString(direction.intValue()));
final String uploadWebsite = sharedPreferences.getString("defaultUploadWebsite", defaultUploadWebsite);
LoopjHttpClient.get(uploadWebsite, requestParams, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, org.apache.http.Header[] headers, byte[] responseBody) {
LoopjHttpClient.debugLoopJ(TAG, "sendLocationDataToWebsite - success", uploadWebsite, requestParams, responseBody, headers, statusCode, null);
stopSelf();
}
#Override
public void onFailure(int statusCode, org.apache.http.Header[] headers, byte[] errorResponse, Throwable e) {
LoopjHttpClient.debugLoopJ(TAG, "sendLocationDataToWebsite - failure", uploadWebsite, requestParams, errorResponse, headers, statusCode, e);
stopSelf();
}
});
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
Log.e(TAG, "position: " + location.getLatitude() + ", " + location.getLongitude() + " accuracy: " + location.getAccuracy());
// we have our desired accuracy of 500 meters so lets quit this service,
// onDestroy will be called and stop our location uodates
if (location.getAccuracy() < 500.0f) {
stopLocationUpdates();
sendLocationDataToWebsite(location);
}
}
}
private void stopLocationUpdates() {
if (locationClient != null && locationClient.isConnected()) {
locationClient.removeLocationUpdates(this);
locationClient.disconnect();
}
}
/**
* Called by Location Services when the request to connect the
* client finishes successfully. At this point, you can
* request the current location or start periodic updates
*/
#Override
public void onConnected(Bundle bundle) {
Log.d(TAG, "onConnected");
locationRequest = LocationRequest.create();
locationRequest.setInterval(1000); // milliseconds
locationRequest.setFastestInterval(1000); // the fastest rate in milliseconds at which your app can handle location updates
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationClient.requestLocationUpdates(locationRequest, this);
}
/**
* Called by Location Services if the connection to the
* location client drops because of an error.
*/
#Override
public void onDisconnected() {
Log.e(TAG, "onDisconnected");
stopLocationUpdates();
stopSelf();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.e(TAG, "onConnectionFailed");
stopLocationUpdates();
stopSelf();
}
}
Hi Can anybody tell me how can i calculate Total Miles Travel from the Curent location to another location? e.g. like i start walking from point A and reached at point B. how can i find the total distance travel from point A to B. Please help me!!!
Criteria c=new Criteria()
c.setAccuracy(Criteria.ACCURACY_FINE);
String providerName=locMgr.getBestProvider(c,true);
Location startLocation = new Location(providerName);
startLocation.setLatitude(PrevLatitude);
startLocation.setLongitude(PrevLongitude);
startLocation.set(startLocation);
Location _myLoc = new Location(providerName);
_myLoc.setLatitude(Double.valueOf(nf.format(location.getLatitude())));
_myLoc.setLongitude(Double.valueOf(nf.format(location.getLongitude())));
_myLoc.set(_myLoc);
double meters = _myLoc.distanceTo(startLocation);
double miles = (meters*0.000621371192237334);
Assume, you have Location start_location and finish_location.
So you can use start_location.distanceTo(finish_location)
Please See , Location in Android
I have solved this exact problem in my open source Gps Tracker. The full working android project is here:
https://github.com/nickfox/GpsTracker/tree/master/phoneClients/android
and the class that does the tracking is below. You want to take a look at the variable called totalDistanceInMeters.
package com.websmithing.gpstracker;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class LocationService extends Service implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener,
LocationListener {
private static final String TAG = "LocationService";
// use the websmithing defaultUploadWebsite for testing and then check your
// location with your browser here: https://www.websmithing.com/gpstracker/displaymap.php
private String defaultUploadWebsite;
private boolean currentlyProcessingLocation = false;
private LocationRequest locationRequest;
private LocationClient locationClient;
#Override
public void onCreate() {
super.onCreate();
defaultUploadWebsite = getString(R.string.default_upload_website);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// if we are currently trying to get a location and the alarm manager has called this again,
// no need to start processing a new location.
if (!currentlyProcessingLocation) {
currentlyProcessingLocation = true;
startTracking();
}
return START_NOT_STICKY;
}
private void startTracking() {
Log.d(TAG, "startTracking");
if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(this) == ConnectionResult.SUCCESS) {
locationClient = new LocationClient(this,this,this);
if (!locationClient.isConnected() || !locationClient.isConnecting()) {
locationClient.connect();
}
} else {
Log.e(TAG, "unable to connect to google play services.");
}
}
protected void sendLocationDataToWebsite(Location location) {
// formatted for mysql datetime format
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getDefault());
Date date = new Date(location.getTime());
SharedPreferences sharedPreferences = this.getSharedPreferences("com.websmithing.gpstracker.prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
float totalDistanceInMeters = sharedPreferences.getFloat("totalDistanceInMeters", 0f);
boolean firstTimeGettingPosition = sharedPreferences.getBoolean("firstTimeGettingPosition", true);
if (firstTimeGettingPosition) {
editor.putBoolean("firstTimeGettingPosition", false);
} else {
Location previousLocation = new Location("");
previousLocation.setLatitude(sharedPreferences.getFloat("previousLatitude", 0f));
previousLocation.setLongitude(sharedPreferences.getFloat("previousLongitude", 0f));
float distance = location.distanceTo(previousLocation);
totalDistanceInMeters += distance;
editor.putFloat("totalDistanceInMeters", totalDistanceInMeters);
}
editor.putFloat("previousLatitude", (float)location.getLatitude());
editor.putFloat("previousLongitude", (float)location.getLongitude());
editor.apply();
final RequestParams requestParams = new RequestParams();
requestParams.put("latitude", Double.toString(location.getLatitude()));
requestParams.put("longitude", Double.toString(location.getLongitude()));
Double speedInMilesPerHour = location.getSpeed()* 2.2369;
requestParams.put("speed", Integer.toString(speedInMilesPerHour.intValue()));
try {
requestParams.put("date", URLEncoder.encode(dateFormat.format(date), "UTF-8"));
} catch (UnsupportedEncodingException e) {}
requestParams.put("locationmethod", location.getProvider());
if (totalDistanceInMeters > 0) {
requestParams.put("distance", String.format("%.1f", totalDistanceInMeters / 1609)); // in miles,
} else {
requestParams.put("distance", "0.0"); // in miles
}
requestParams.put("username", sharedPreferences.getString("userName", ""));
requestParams.put("phonenumber", sharedPreferences.getString("appID", "")); // uuid
requestParams.put("sessionid", sharedPreferences.getString("sessionID", "")); // uuid
Double accuracyInFeet = location.getAccuracy()* 3.28;
requestParams.put("accuracy", Integer.toString(accuracyInFeet.intValue()));
Double altitudeInFeet = location.getAltitude() * 3.28;
requestParams.put("extrainfo", Integer.toString(altitudeInFeet.intValue()));
requestParams.put("eventtype", "android");
Float direction = location.getBearing();
requestParams.put("direction", Integer.toString(direction.intValue()));
final String uploadWebsite = sharedPreferences.getString("defaultUploadWebsite", defaultUploadWebsite);
LoopjHttpClient.get(uploadWebsite, requestParams, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, org.apache.http.Header[] headers, byte[] responseBody) {
LoopjHttpClient.debugLoopJ(TAG, "sendLocationDataToWebsite - success", uploadWebsite, requestParams, responseBody, headers, statusCode, null);
stopSelf();
}
#Override
public void onFailure(int statusCode, org.apache.http.Header[] headers, byte[] errorResponse, Throwable e) {
LoopjHttpClient.debugLoopJ(TAG, "sendLocationDataToWebsite - failure", uploadWebsite, requestParams, errorResponse, headers, statusCode, e);
stopSelf();
}
});
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
Log.e(TAG, "position: " + location.getLatitude() + ", " + location.getLongitude() + " accuracy: " + location.getAccuracy());
// we have our desired accuracy of 500 meters so lets quit this service,
// onDestroy will be called and stop our location uodates
if (location.getAccuracy() < 500.0f) {
stopLocationUpdates();
sendLocationDataToWebsite(location);
}
}
}
private void stopLocationUpdates() {
if (locationClient != null && locationClient.isConnected()) {
locationClient.removeLocationUpdates(this);
locationClient.disconnect();
}
}
/**
* Called by Location Services when the request to connect the
* client finishes successfully. At this point, you can
* request the current location or start periodic updates
*/
#Override
public void onConnected(Bundle bundle) {
Log.d(TAG, "onConnected");
locationRequest = LocationRequest.create();
locationRequest.setInterval(1000); // milliseconds
locationRequest.setFastestInterval(1000); // the fastest rate in milliseconds at which your app can handle location updates
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationClient.requestLocationUpdates(locationRequest, this);
}
/**
* Called by Location Services if the connection to the
* location client drops because of an error.
*/
#Override
public void onDisconnected() {
Log.e(TAG, "onDisconnected");
stopLocationUpdates();
stopSelf();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.e(TAG, "onConnectionFailed");
stopLocationUpdates();
stopSelf();
}
}