Time synchronization between Mobile devices - android

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;
}
}
}

Related

how to get real time geolocation with movings(like google maps) on android with movings

I'm new to android and I'm creating an application based on GPS . So i have implement Google maps and location point identifier on my application but it takes only my first attempt geo location , when I'm moving it is not get updated . please help me to solve this . Thank you.
package com.android.locationtracker;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.android.app.AppConst;
import com.android.app.AppController;
import com.android.common.GPSTracker;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.Request.Method;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
public class NearByActivity extends Activity {
private static final String TAG = "error";
private GoogleMap googleMap;
private static String URL = AppConst.GEOMETRY;
private static String URL_UPDATE = AppConst.GEOMETRY_UPDATE;
private String jsonResponse;
private ProgressDialog pDialog;
GPSTracker gps;
double latitude;
double longtitude;
String id;
String type;
List<Marker> markerList = new ArrayList<Marker>();
Marker marker;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nearby_activity);
try {
// Loading map
initilizeMap();
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.getUiSettings().setRotateGesturesEnabled(true);
} catch (Exception e) {
e.printStackTrace();
}
gps = new GPSTracker(this);
if (gps.canGetLocation()) {
latitude = gps.getLatitude();
longtitude = gps.getLongtitude();
} else {
gps.showSettingAllerts();
}
new LoadGeo().execute();
}
private void initilizeMap() {
try {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager()
.findFragmentById(R.id.map)).getMap();
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onResume() {
super.onResume();
initilizeMap();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
private class LoadGeo extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NearByActivity.this);
pDialog.setMessage("Loading...");
pDialog.show();
//
}
#Override
protected Void doInBackground(Void... arg0) {
SharedPreferences prefs = getSharedPreferences("conetext",
Context.MODE_PRIVATE);
id = prefs.getString("userid", null);
type = prefs.getString("persontype", null);
Map<String, String> params = new HashMap<String, String>();
params.put("userid", id);
params.put("usertype", type);
params.put("lat", String.valueOf(latitude));
params.put("lng", String.valueOf(longtitude));
JsonObjectRequest req = new JsonObjectRequest(URL_UPDATE,
new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.d("map", "msg");
VolleyLog.v("Response:%n %s",
response.toString(4));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
// add the request object to the queue to be executed
AppController.getInstance().addToRequestQueue(req);
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Thread thread = new Thread() {
#Override
public void run() {
try {
while (true) {
sleep(1000);
JsonArrayRequest req = new JsonArrayRequest(URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(
JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
try {
markerList.clear();
googleMap.clear();
for (int i = 0; i < response
.length(); i++) {
JSONObject geo = (JSONObject) response
.get(i);
String usertype = geo
.getString("UserType");
MarkerOptions markerblue = new MarkerOptions();
markerblue.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_CYAN));
markerblue.position(new LatLng(latitude, longtitude));
googleMap.addMarker(markerblue);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(
latitude, longtitude), 17));
if (usertype
.equals("driver")) {
double lat = geo
.getDouble("Lat");
double lng = geo
.getDouble("Lng");
MarkerOptions markerop = new MarkerOptions();
markerop.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
markerop.position(
new LatLng(lat,
lng))
.draggable(true)
.visible(true);
marker= googleMap
.addMarker(markerop);
markerList.add(marker);
}
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(
getApplicationContext(),
"Error: "
+ e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(
VolleyError error) {
VolleyLog.d(
TAG,
"Error: "
+ error.getMessage());
Toast.makeText(
getApplicationContext(),
error.getMessage(),
Toast.LENGTH_SHORT).show();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
}
}
}
You need to register LocationListener and implement method
#Override
public void onLocationChanged(Location location) {
//smth like this
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongtitude()), 17));
}
detailed info is here https://developer.android.com/training/location/receive-location-updates.html
You need to execute this code in specific interval
if (gps.canGetLocation()) {
latitude = gps.getLatitude();
longtitude = gps.getLongtitude();
} else {
gps.showSettingAllerts();
}
new LoadGeo().execute();
i would suggest use Handler.postDelayed(Runnable,Interval) method to work this out.
You can use Location service. Here is the code for that:
Call this function by giving a desired frequency (in mins):
private void requestLocation(Context context, int frequency) //frequency in mins
{
LocationMgr loc_mgr = new LocationMgr(context);
loc_mgr.requestLocationUpdates(frequency);
}
Here is the LocationMgr class:
public class LocationMgr implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener
{
private final Context context;
private GoogleApiClient googleApiClient;
private boolean inProgress;
public enum REQUEST_TYPE {START, STOP, LAST_KNOWN}
private REQUEST_TYPE requestType;
private Intent intent;
LocationRequest mLocationRequest;
LocationListener ll;
public LocationMgr(Context context)
{
this.context = context;
this.googleApiClient = new GoogleApiClient.Builder(context)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
intent = new Intent(context, LocationService.class);
inProgress = false;
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
inProgress = false;
}
#Override
public void onConnectionSuspended(int arg0) {
googleApiClient.connect();
}
#Override
public void onConnected(Bundle connectionHint) {
PendingIntent pendingIntent = PendingIntent.getService(context, 123, intent, PendingIntent.FLAG_UPDATE_CURRENT);
switch (requestType)
{
case START :
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, mLocationRequest, pendingIntent);
break;
case STOP :
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, pendingIntent);
break;
case LAST_KNOWN :
Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
ll.onNewLocationUpdate(location);
break;
default :
log.e("Unknown request type in onConnected().");
break;
}
inProgress = false;
googleApiClient.disconnect();
}
/**
*
* #param frequency (minutes) minimum time interval between location updates
*/
public void requestLocationUpdates(int frequency)
{
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(frequency * 60 * 1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setFastestInterval(1000);
if (inProgress)
{
log.e("A request is already underway");
return;
}
inProgress = true;
requestType = REQUEST_TYPE.START;
googleApiClient.connect();
}
public void removeContinuousUpdates()
{
if (inProgress)
{
log.e("A request is already underway");
return;
}
inProgress = true;
requestType = REQUEST_TYPE.STOP;
googleApiClient.connect();
}
public void getLastKnownLocation(LocationListener ll)
{
this.ll = ll;
if (inProgress)
{
log.e("A request is already underway");
return;
}
inProgress = true;
requestType = REQUEST_TYPE.LAST_KNOWN;
googleApiClient.connect();
}
}
Here is the LocationService class:
public class LocationService extends IntentService
{
public LocationService()
{
super("NOTIFICATION_SERVICE");
}
/**
* Called when a new location update is available.
*/
#Override
protected void onHandleIntent(Intent intent)
{
LocationListener ll = new LocationListener()
{
#Override
public void onNewLocationUpdate(Location location)
{
// here you will get the latest location
}
};
LocationMgr lm = new LocationMgr(getApplicationContext());
lm.getLastKnownLocation(ll);
}
}

Difference in android code execution

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.

Android Gps Time

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());
}
}

Android creating/stopping TimerTask

I have an android application that makes submissions to a database every 3 minutes using a timer task. The timer is suppose to persist even if the user minimizes the application. If I change the focus to another app and then change back everything works correctly but if I press the home button and then press app Icon another timer task is started. Can anyone explain why?
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;
#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);
// if(this.timerUpdate == null && authenticate() == true) {
// this.timerUpdate = new TimerUpdate(this, addressOps);
// timerUpdate.startTimer();
// }
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.com"));
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");
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");
}
}
Heres my timertask 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){
initializeTimerTask();
this.mainContext = context;
this.addressOps = ops;
userLocalStore = new UserLocalStore(context);
}
private void 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(){
timer = new Timer();
timer.schedule(timertask, 1000 * 30, 1000 * 60 * 3);
timerScheduled = true;
Log.e(TAG, "Start Schedule created");
}
public void stopTimerTask(){
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();
}
}
So, as #Robert suggested in comments, this happens because your TimerTask instance is tied to the Activity instance. When you start another Activity instance (by starting your app by tapping the launcher icon), a new instance of TimerTask is created. If you need your TimerTask to be independent of Activities, then you'll need a Service.
When you restart your app, MainActivity goes through onCreate and onStart, and in onStart you start the timer.

Waking Device When Destination Reached

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.

Categories

Resources