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.
Related
I had create a Location Listener by FusedLocation. Each time when my logged auth user start to track their location, the location were write under the currentuser user-id but it keep added a different unique ID for each location that were written in the database. I need that 'location' in the same tree with my current login user description ('name' & 'type') and each time my current user have a location changed data, it will overwrite the data in the 'latitude' and 'longitude'. How I can reconstruct my code?
Here my screenshot of my database
my firebase database
Here my location.class
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
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.GoogleApiAvailability;
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 com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.text.DateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
/**
* Created by AKMAL NIZAR ROSLE on 12/6/2017.
*/
public class DriverActivity extends AppCompatActivity implements
LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "DriverActivity";
private static final long INTERVAL = 1000 * 10;
private static final long FASTEST_INTERVAL = 1000 * 5;
private FirebaseAuth auth;
private DatabaseReference databaseReference;
Button btnFusedLocation;
TextView tvLocation, textViewUser;
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);
auth = FirebaseAuth.getInstance();
//get current user
if (auth.getCurrentUser() == null) {
startActivity(new Intent(DriverActivity.this, LoginActivity.class));
finish();
}
databaseReference = FirebaseDatabase.getInstance().getReference();
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_driver);
FirebaseUser user = auth.getCurrentUser();
textViewUser = (TextView) findViewById(R.id.textViewUser);
textViewUser.setText("Welcome"+" "+user.getEmail());
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() {
final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (apiAvailability.isUserResolvableError(resultCode)) {
apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST)
.show();
} else {
Log.d(TAG, "This device is not supported.");
}
return false;
}
return true;
}
#Override
public void onConnected(Bundle bundle) {
Log.d(TAG, "onConnected - isConnected ...............: " + mGoogleApiClient.isConnected());
startLocationUpdates();
}
protected void startLocationUpdates() {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
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());
saveToFirebase();
updateUI();
}
private void saveToFirebase() {
FirebaseUser user = auth.getCurrentUser();
Map mLocations = new HashMap();
Map mCoordinate = new HashMap();
mCoordinate.put("latitude", mCurrentLocation.getLatitude());
mCoordinate.put("longitude", mCurrentLocation.getLongitude());
mLocations.put("location", mCoordinate);
databaseReference.child(user.getUid()).push().setValue(mLocations);
}
private void updateUI() {
Log.d(TAG, "UI update initiated .............");
if (null != mCurrentLocation) {
String lat = String.valueOf(mCurrentLocation.getLatitude());
String lng = String.valueOf(mCurrentLocation.getLongitude());
tvLocation.setText("At Time: " + mLastUpdateTime + "\n" +
"Latitude: " + lat + "\n" +
"Longitude: " + lng + "\n" +
"Accuracy: " + mCurrentLocation.getAccuracy() + "\n" +
"Provider: " + mCurrentLocation.getProvider());
} 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 .....................");
}
}
}
private void saveToFirebase() {
FirebaseUser user = auth.getCurrentUser();
Map mLocations = new HashMap();
Map mCoordinate = new HashMap();
mCoordinate.put("latitude", mCurrentLocation.getLatitude());
mCoordinate.put("longitude", mCurrentLocation.getLongitude());
mLocations.put("location", mCoordinate);
databaseReference.child(user.getUid()).push().setValue(mLocations);
}
Just remove the push() method in your setValue database operation:
private void saveToFirebase() {
FirebaseUser user = auth.getCurrentUser();
Map mCoordinate = new HashMap();
mCoordinate.put("latitude", mCurrentLocation.getLatitude());
mCoordinate.put("longitude", mCurrentLocation.getLongitude());
databaseReference.child(user.getUid() + "/location").setValue(mCoordinate);
}
The push() method generates a new node with an unique key to your database reference.
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;
}
}
}
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());
}
}
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.