Unable to get proper speed between locations due to wrong GPS location - android

I am trying to find speed between two locations but found that GPS location is inaccurate. I am at the same location and it keeps on providing different location For e.g It provides me location that's far about 200KM from me.
public class LocationTracker extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener, SensorEventListener {
// LogCat tag
private static final String TAG = "LocationTracker";
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
private static int UPDATE_INTERVAL = 5000; // 5 sec
private static int FATEST_INTERVAL = 2000; // 2 sec
private static int DISPLACEMENT = 2; // 2 meters
private Context context;
private SharedPreferences sp;
// Location updates intervals in sec
private Location mLastLocation;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private double latitude, longitude;
private boolean firstLocation = false;
private float speed;
public LocationTracker(Context ctx, boolean firstLocation) {
context = ctx;
sp = context.getSharedPreferences(Utility.SHARED_PREFS, MODE_PRIVATE);
this.firstLocation = firstLocation;
// First we need to check availability of play services
if (checkPlayServices()) {
createLocationRequest();
buildGoogleApiClient();
if (mGoogleApiClient != null)
mGoogleApiClient.connect();
}
}
#Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
/**
* Creating google api client object
*/
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(context)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
}
/**
* Method to verify google play services on the device
*/
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(context);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode))
Utility.showLog(TAG, "Something went wrong with error code :" + resultCode);
else
Utility.showLog(TAG,
"This device is not supported.");
// stopLocationUpdates();
return false;
}
return true;
}
/**
* Creating location request object
*/
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FATEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(DISPLACEMENT); // 10 meters
}
/**
* Starting the location updates
*/
public void startLocationUpdates() {
Utility.showLog(TAG, "Starting Location Updates");
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
/**
* Stopping location updates
*/
public void stopLocationUpdates() {
Utility.showLog(TAG, "Stopping Location Updates");
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
if (mGoogleApiClient.isConnected())
mGoogleApiClient.disconnect();
}
stopSelf();
}
/**
* Function to get latitude
*/
public double getLatitude() {
// return latitude
return latitude;
}
/**
* Function to get longitude
*/
public double getLongitude() {
// return longitude
return longitude;
}
#Override
public void onConnected(Bundle bundle) {
Utility.showLog(TAG, "Google API Connected");
// Once connected with google api, get the location
updateLocation();
startLocationUpdates();
}
#Override
public void onLocationChanged(Location location) {
// Assign the new location
mLastLocation = location;
updateLocation();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
/**
* Method to display the location on UI
*/
private void updateLocation() {
mLastLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
if (firstLocation) {
sp.edit().putString("last_latitude", String.valueOf(mLastLocation.getLatitude())).commit();
sp.edit().putString("last_longitude", String.valueOf(mLastLocation.getLongitude())).commit();
sp.edit().putLong("last_location_time", System.currentTimeMillis()).commit();
firstLocation = false;
Utility.showLog(TAG, "Last Latitude : " + mLastLocation.getLatitude());
Utility.showLog(TAG, "Last Longitude : " + mLastLocation.getLongitude());
}
latitude = mLastLocation.getLatitude();
longitude = mLastLocation.getLongitude();
heading = mLastLocation.getBearing();
altitude = mLastLocation.getAltitude();
Utility.showLog(TAG, " Latitude : " + latitude);
Utility.showLog(TAG, " Longitude : " + longitude);
Utility.showLog(TAG, "Heading :" + heading);
Utility.showLog(TAG, "Altitude :" + altitude);
} else
Utility.showLog(TAG, "Couldn't get the location. Make sure location is enabled on the device");
}
#Override
public void onDestroy() {
super.onDestroy();
Utility.showLog(TAG, "Location Tracker Stopped");
}
/**
* Function to get Speed
*/
public double getSpeed() {
double previousLatitude = Double.parseDouble(sp.getString("last_latitude", "0.0"));
double previousLongitude = Double.parseDouble(sp.getString("last_longitude", "0.0"));
Utility.showLog(TAG, "Old Latitude :" + previousLatitude);
Utility.showLog(TAG, "Old Longitude :" + previousLongitude);
Utility.showLog(TAG, "New Latitude :" + latitude);
Utility.showLog(TAG, "New Longitude :" + longitude);
Location sourceLocation = new Location("A");
sourceLocation.setLatitude(previousLatitude);
sourceLocation.setLongitude(previousLongitude);
Location destinationLocation = new Location("B");
destinationLocation.setLatitude(latitude);
destinationLocation.setLongitude(longitude);
double distance = sourceLocation.distanceTo(destinationLocation);
Utility.showLog(TAG, "Distance =" + distance);
float differenceInTime = (float) ((System.currentTimeMillis() - sp.getLong("last_location_time", 0)) / 1000);
Utility.showLog(TAG, "Current Time :" + System.currentTimeMillis());
Utility.showLog(TAG, "Last Time :" + sp.getLong("last_location_time", 0));
Utility.showLog(TAG, "Difference in Time " + differenceInTime);
double mps = distance / differenceInTime;
double kph = (mps * 3600) / 1000;
return kph;
}
}

Please check the accuracy of the location obtained. And if the accuracy value is high(high depends on your decision), then ignore it.
You can get Accuracy using
location.getAccuracy();
At times when you are inside a building, there are chances that your location accuracy will be around 2km sometimes. You can ignore in this case. This accuracy depends on the number of satellites that are providing the result.

Related

The Geo-Cordinates getting is Very Far from previous one

In my application there is provision to track how much distance a person is travelled.There is a Service class for getting the current lat and long perodically.Some times the points getting is fine.Othertimes it is not.I started from a point and walked around 500m and came back to the samepoint ,but the distance calculated was 3.5 k.m.
For finding the distance travelled ,I take the difference in between Current and previous location.The values are added with new value and goes on until last.The problem occurs ,Some times the gps point getting is very far from previous one(Some times getting point would be more than 700 meters from previous).
Here is my class.Please enlighten me if i do anything wrong.
public class LocationUpdateService extends Service implements
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
protected static final String TAG = "LocationUpdateService";
public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000;
public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = UPDATE_INTERVAL_IN_MILLISECONDS / 2;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 3; // 10 meters
public static Boolean mRequestingLocationUpdates;
protected String mLastUpdateTime;
protected GoogleApiClient mGoogleApiClient;
protected LocationRequest mLocationRequest;
protected Location mCurrentLocation;
protected Location mLastLocation;
Location currentLocation, previousLocation;
public static boolean isEnded = false;
private Context mContext;
ServiceListener listener;
SharedPreferences sharedPreferences;
double latitude; // latitude
double longitude; // longitude
private String locationProvider; // source of fetched location
LocationManager locationManager;
private IBinder mBinder = new MyBinder();
public LocationUpdateService() {
super();
}
public void setListener(ServiceListener listener) {
this.listener = listener;
}
#Override
public void onCreate() {
super.onCreate();
// Kick off the process of building a GoogleApiClient and requesting the LocationServices
mContext = getApplicationContext();
//locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
sharedPreferences = mContext.getSharedPreferences(WebServiceHelper.PREFS_NAME, 0);
System.out.println("GPS TRACKER STARTED");
deletefile("asap_distance.csv");
}
// #Override
// public IBinder onBind(Intent intent) {
// return null;
// }
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Within {#code onPause()}, we pause location updates, but leave the
// connection to GoogleApiClient intact. Here, we resume receiving
// location updates if the user has requested them.
System.out.println(TAG + "onStartCommand");
Log.d("LOC", "Service init...");
isEnded = false;
mRequestingLocationUpdates = false;
mLastUpdateTime = "";
buildGoogleApiClient();
if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) {
startLocationUpdates();
}
return Service.START_REDELIVER_INTENT;
}
#Override
public void onConnected(Bundle bundle) {
System.out.println(TAG + "onConnected");
startLocationUpdates();
}
#Override
public void onConnectionSuspended(int i) {
// The connection to Google Play services was lost for some reason. We call connect() to
// attempt to re-establish the connection.
Log.i(TAG, "Connection suspended==");
mGoogleApiClient.connect();
}
#Override
public void onLocationChanged(Location location) {
System.out.println(TAG + "onLocationChanged");
if (location == null) {
getLastKnownLocation();
} else {
mCurrentLocation = location;
if (mCurrentLocation.hasAccuracy() && mCurrentLocation.getAccuracy() > MIN_DISTANCE_CHANGE_FOR_UPDATES)
setLocationData(mCurrentLocation);
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
}
//
// updateUI();
// Toast.makeText(this, "Location changed",
// Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
// Refer to the javadoc for ConnectionResult to see what error codes might be returned in
// onConnectionFailed.
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + connectionResult.getErrorCode());
}
/**
* Builds a GoogleApiClient. Uses the {#code #addApi} method to request the
* LocationServices API.
*/
protected synchronized void buildGoogleApiClient() {
Log.i(TAG, "Building GoogleApiClient===");
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
createLocationRequest();
}
public void setLocationData(Location location) {
if (location != null) {
currentLocation = location;
double previous_latitude, previous_longitude, current_lat, current_long;
latitude = location.getLatitude();
longitude = location.getLongitude();
// Toast.makeText(mContext, "Current lattitude:" + latitude + "Current Longitude:" + longitude, Toast.LENGTH_LONG).show();
previous_latitude = previousLocation.getLatitude();
previous_longitude = previousLocation.getLongitude();
current_lat = currentLocation.getLatitude();
current_long = currentLocation.getLongitude();
Log.d(TAG, "Previous lattitude:" + previous_latitude + "Previous Longitude:" + previous_longitude);
Log.d(TAG, "Current lattitude:" + current_lat + "Current Longitude:" + current_long);
sharedPreferences.edit().putFloat("lastSavedLat", (float) current_lat).apply();
sharedPreferences.edit().putFloat("lastSavedLon", (float) current_long).apply();
if (previousLocation != null && sharedPreferences.contains("sdeMarkedStartLocLat")) {
if (current_lat == previous_latitude && current_long == previous_longitude) {
Log.d(TAG, "No Displacement");
} else {
Log.d(TAG, "Device Displaced");
// double d = getDistance(previous_latitude, previous_longitude, current_lat, current_long);
double d = ((int) (previousLocation.distanceTo(currentLocation) * 1000)) / 1000;
Log.d(TAG, "Distance calculated in between previousLocation and currentLocation is" + d);
if (d < 5000) {
d = d + sharedPreferences.getFloat("sum_dist", 0);
sharedPreferences.edit().putFloat("sum_dist", (float) d).apply();
// Toast.makeText(mContext, "Total Distance travelled is " + d + "km", Toast.LENGTH_LONG).show();
// Log.d("Distance Calculator ON", "distance" + d);
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
writeToFile(sdf.format(new Date()) + "," + currentLocation.getLatitude() + "," + currentLocation.getLongitude() + ", " + d + " meters" + "\n", "asap.csv");
writeToFile(currentLocation.getLatitude() + "," + currentLocation.getLongitude() + "\n", "asap_distance.csv");
}
}
}
if (listener != null)
listener.onLocationReceived(location);
System.out.println("GPS TRACKER " + latitude + " " + longitude);
previousLocation = currentLocation;
} else {
Log.d(TAG, "Location is null");
return;
}
}
public double getDistance(double start_lat, double start_long, double dest_lat, double dest_long) {
double dist = 0;
Location locationA = new Location("point A");
locationA.setLatitude(start_lat);
locationA.setLongitude(start_long);
Location locationB = new Location("point B");
locationB.setLatitude(dest_lat);
locationB.setLongitude(dest_long);
dist = locationA.distanceTo(locationB);
if (dist != 0) {
dist = dist / 1000;
}
return dist;
}
/**
* Updates the latitude, the longitude, and the last location time in the UI.
*/
private void updateUI() {
Toast.makeText(this, "Latitude: =" + mCurrentLocation.getLatitude() + " Longitude:=" + mCurrentLocation
.getLongitude(), Toast.LENGTH_SHORT).show();
System.out.println("updateUI");
Log.d(TAG, "Latitude:==" + mCurrentLocation.getLatitude() + "\n Longitude:==" + mCurrentLocation.getLongitude
());
}
/**
* Sets up the location request. Android has two location request settings:
* {#code ACCESS_COARSE_LOCATION} and {#code ACCESS_FINE_LOCATION}. These settings control
* the accuracy of the current location. This sample uses ACCESS_FINE_LOCATION, as defined in
* the AndroidManifest.xml.
* <p/>
* When the ACCESS_FINE_LOCATION setting is specified, combined with a fast update
* interval (5 seconds), the Fused Location Provider API returns location updates that are
* accurate to within a few feet.
* <p/>
* These settings are appropriate for mapping applications that show real-time location
* updates.
*/
protected void createLocationRequest() {
mGoogleApiClient.connect();
mLocationRequest = new LocationRequest();
// Sets the desired interval for active location updates. This interval is
// inexact. You may not receive updates at all if no location sources are available, or
// you may receive them slower than requested. You may also receive updates faster than
// requested if other applications are requesting location at a faster interval.
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
// Sets the fastest rate for active location updates. This interval is exact, and your
// application will never receive updates faster than this value.
mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(MIN_DISTANCE_CHANGE_FOR_UPDATES);
}
/**
* Requests location updates from the FusedLocationApi.
*/
protected void startLocationUpdates() {
if (!mRequestingLocationUpdates) {
mRequestingLocationUpdates = true;
// The final argument to {#code requestLocationUpdates()} is a LocationListener
// (http://developer.android.com/reference/com/google/android/gms/location/LocationListener.html).
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
Log.i(TAG, " startLocationUpdates===");
isEnded = true;
}
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
previousLocation = mLastLocation;
if (mLastLocation != null) {
onLocationChanged(mLastLocation);
}
}
/**
* Function to get latitude
*/
public double getLatitude() {
if (mCurrentLocation != null) {
latitude = mCurrentLocation.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
*/
public double getLongitude() {
if (mCurrentLocation != null) {
longitude = mCurrentLocation.getLongitude();
}
// return longitude
return longitude;
}
/**
* Removes location updates from the FusedLocationApi.
*/
protected void stopLocationUpdates() {
if (mRequestingLocationUpdates) {
mRequestingLocationUpdates = false;
// It is a good practice to remove location requests when the activity is in a paused or
// stopped state. Doing so helps battery performance and is especially
// recommended in applications that request frequent location updates.
Log.d(TAG, "stopLocationUpdates();==");
// The final argument to {#code requestLocationUpdates()} is a LocationListener
// (http://developer.android.com/reference/com/google/android/gms/location/LocationListener.html).
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
#Override
public void onDestroy() {
super.onDestroy();
stopLocationUpdates();
System.out.println("GPS TRACKER STOPPED");
}
public Location getLastKnownLocation() {
// locationProvider = LocationManager.GPS_PROVIDER;
Location lastKnownLocation = null;
// Or use LocationManager.GPS_PROVIDER
if (Build.VERSION.SDK_INT >= 23 &&
ContextCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return lastKnownLocation;
}
try {
//lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
lastKnownLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
return lastKnownLocation;
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
return lastKnownLocation;
}
#Override
public IBinder onBind(Intent intent) {
Log.v("GPS", "in onBind");
return mBinder;
}
#Override
public void onRebind(Intent intent) {
Log.v("GPS", "in onRebind");
super.onRebind(intent);
}
#Override
public boolean onUnbind(Intent intent) {
Log.v("GPS", "in onUnbind");
return true;
}
public void deletefile(String filename) {
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File(sdCard.getAbsolutePath() + "/ASAPLog");
//Now delete the file in the above directory and write the contents into it
try {
File file = new File(directory.getAbsolutePath() + "/" + filename);
if (file.exists()) {
boolean deleted = file.delete();
System.out.println("deleted" + deleted);
} else {
System.out.println("File Doesnot Exists");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void writeToFile(String text, String filename) {
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File(sdCard.getAbsolutePath() + "/ASAPLog");
if (!directory.exists())
directory.mkdirs();
// String savedText = readFromFile(filename).toString();
//Now create the file in the above directory and write the contents into it
try {
File file = new File(directory.getAbsolutePath() + "/" + filename);
FileOutputStream fOut = new FileOutputStream(file, true);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.append(text);
osw.flush();
osw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public class MyBinder extends Binder {
LocationUpdateService getService() {
return LocationUpdateService.this;
}
}
}

Can anyone tell me how do i send longitude and lattitude co-ordinate via message in android app?

Hi all this is my code to get the longitude and lattitude now i want to know how do i call this class and how can i send that coordinated via url in a string sms , one more thing i want to tell that this code have no error but when i use this in my app it does not give me the toast, can anyone please help me out.
here is my location class:
public class Location_Getter extends AppCompatActivity implements
ConnectionCallbacks,
OnConnectionFailedListener,
LocationListener {
//Define a request code to send to Google Play services
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private double currentLatitude;
private double currentLongitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGoogleApiClient = new GoogleApiClient.Builder(this)
// The next two lines tell the new client that “this” current class will handle connection stuff
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
//fourth line adds the LocationServices API endpoint from GooglePlayServices
.addApi(LocationServices.API)
.build();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
}
#Override
protected void onResume() {
super.onResume();
//Now lets connect to the API
mGoogleApiClient.connect();
}
#Override
protected void onPause() {
super.onPause();
Log.v(this.getClass().getSimpleName(), "onPause()");
//Disconnect from API onPause()
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
/**
* If connected get lat and long
*
*/
#Override
public void onConnected(Bundle bundle) {
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
} else {
//If everything went fine lets get latitude and longitude
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
Log.e("check it", "lattitude "+currentLatitude+" longitude "+ currentLongitude);
Toast.makeText(this, currentLatitude + " WORKS " + currentLongitude + "", Toast.LENGTH_LONG).show();
}
}
#Override
public void onConnectionSuspended(int i) {}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
/*
* Google Play services can resolve some errors it detects.
* If the error has a resolution, try sending an Intent to
* start a Google Play services activity that can resolve
* error.
*/
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
/*
* If no resolution is available, display a dialog to the
* user with the error.
*/
Log.e("Error", "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
/**
* If locationChanges change lat and long
*
*
* #param location
*/
#Override
public void onLocationChanged(Location location) {
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
Log.e("check it m nmln l nk ", "lattitude "+currentLatitude+" longitude "+currentLongitude);
Toast.makeText(this, currentLatitude + " WORKS " + currentLongitude + "", Toast.LENGTH_LONG).show();
}
}
here is my string sms:
String message= " https://www.google.com/maps?q=000000,000000";
here is method to send:
private void sendSMS(String ph, String message) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(ph, null, message, null, null);
Toast.makeText(getApplicationContext(), "SMS SENT",
Toast.LENGTH_LONG).show();
}
MyService:
public class MyService extends Service implements SensorEventListener {
public MyService() {
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
int count = 1;
private boolean init;
private Sensor mySensor;
private SensorManager SM;
private float x1, x2, x3;
private static final float ERROR = (float) 7.0;
private static final float SHAKE_THRESHOLD = 15.00f; // m/S**2
private static final int MIN_TIME_BETWEEN_SHAKES_MILLISECS = 1000;
private long mLastShakeTime;
#Override
public void onCreate() {
}
#Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
long curTime = System.currentTimeMillis();
if ((curTime - mLastShakeTime) > MIN_TIME_BETWEEN_SHAKES_MILLISECS) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
double acceleration = Math.sqrt(Math.pow(x, 2) +
Math.pow(y, 2) +
Math.pow(z, 2)) - SensorManager.GRAVITY_EARTH;
Log.d("mySensor", "Acceleration is " + acceleration + "m/s^2");
if (acceleration > SHAKE_THRESHOLD) {
mLastShakeTime = curTime;
Toast.makeText(getApplicationContext(), "FALL DETECTED",
Toast.LENGTH_LONG).show();
SharedPreferences sharedPref = getSharedPreferences("nameInfo", Context.MODE_PRIVATE);
String ph = sharedPref.getString ("phone","");
// String message= "help me";
String message= " https://www.google.com/maps?q=39283,87353";
sendSMS(ph, message);
}
}
}
}
private void sendSMS(String ph, String message) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(ph, null, message, null, null);
Toast.makeText(getApplicationContext(), "SMS SENT",
Toast.LENGTH_LONG).show();
}
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Start Detecting", Toast.LENGTH_LONG).show();
SM = (SensorManager) getSystemService(SENSOR_SERVICE);
mySensor = SM.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
SM.registerListener(this, mySensor, SensorManager.SENSOR_DELAY_NORMAL);
//here u should make your service foreground so it will keep working even if app closed
return Service.START_STICKY;
}
#Override
public void onDestroy() {
Toast.makeText(this, "Stop Detecting", Toast.LENGTH_LONG).show();
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
//Noting to do!!
}
make java class like track then make a object of track class and then call it from your Main class after that copy the google map url and then call getlattitude and getlongitude .
Change you class Like this:
public class Location_Getter extends AppCompatActivity implements
ConnectionCallbacks,
OnConnectionFailedListener,
LocationListener {
//Define a request code to send to Google Play services
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private double currentLatitude;
private double currentLongitude;
private static int UPDATE_INTERVAL = 2 * 1000;
private static int FASTEST_INTERVAL = 1 * 1000;
private static int DISPLACEMENT = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGoogleApiClient = new GoogleApiClient.Builder(this)
// The next two lines tell the new client that “this” current class will handle connection stuff
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
//fourth line adds the LocationServices API endpoint from GooglePlayServices
.addApi(LocationServices.API)
.build();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
}
#Override
protected void onResume() {
super.onResume();
//Now lets connect to the API
mGoogleApiClient.connect();
}
#Override
protected void onPause() {
super.onPause();
Log.v(this.getClass().getSimpleName(), "onPause()");
//Disconnect from API onPause()
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
/**
* If connected get lat and long
*
*/
#Override
public void onConnected(Bundle bundle) {
createLocationRequest();
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
} else {
//If everything went fine lets get latitude and longitude
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
Log.e("check it", "lattitude "+currentLatitude+" longitude "+ currentLongitude);
Toast.makeText(this, currentLatitude + " WORKS " + currentLongitude + "", Toast.LENGTH_LONG).show();
}
}
#Override
public void onConnectionSuspended(int i) {}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
/*
* Google Play services can resolve some errors it detects.
* If the error has a resolution, try sending an Intent to
* start a Google Play services activity that can resolve
* error.
*/
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
/*
* If no resolution is available, display a dialog to the
* user with the error.
*/
Log.e("Error", "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
/**
* If locationChanges change lat and long
*
*
* #param location
*/
#Override
public void onLocationChanged(Location location) {
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
Log.e("check it m nmln l nk ", "lattitude "+currentLatitude+" longitude "+currentLongitude);
Toast.makeText(this, currentLatitude + " WORKS " + currentLongitude + "", Toast.LENGTH_LONG).show();
}
protected void createLocationRequest() {
try {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
} catch (Exception e) {
}
}
}
Change your sendMessage method like this :
private void sendSMS(String ph, String message,Location location) {
SmsManager smsManager = SmsManager.getDefault();
String message = "Latitude :" +location.getLatitude() + " Longitude : "+location.getLongitude();
smsManager.sendTextMessage(ph, null, message, null, null);
Toast.makeText(getApplicationContext(), "SMS SENT",
Toast.LENGTH_LONG).show();
}

GPS active on after my application destroy form my mobile stack

i want to on my GPS after my application destroy form stack so below is my code
Main.java
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.content_main);
//tvLocation = (TextView) findViewById(R.id.tvLocation);
btnFusedLocation = (Button) findViewById(R.id.btn_go);
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) {
String lat = String.valueOf(mCurrentLocation.getLatitude());
String lng = String.valueOf(mCurrentLocation.getLongitude());
String ss="At Time: " + mLastUpdateTime + "\n" +
"Latitude: " + lat + "\n" +
"Longitude: " + lng + "\n" +
"Accuracy: " + mCurrentLocation.getAccuracy() + "\n" +
"Provider: " + mCurrentLocation.getProvider();
Toast.makeText(LocationActivity.this,ss,Toast.LENGTH_LONG).show();
/*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();
startLocationUpdates();
//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 .....................");
}
}
}
From above code it working fine when i colse my application with mobile back button at that time it still give me GPS location but when i perform below task see in image
In above image when i close my GPS application from my mobile stack my GPS is not active so i want to make it active after application close so any one have idea how can i make it possible? your all suggestion are appreciable
Hello Friends i solve my issue with Broadcast refer my code
public class BrodActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
initialize();
}
private void initialize() {
AlarmManager alarmManager=(AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(BrodActivity.this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(BrodActivity.this, 0, intent, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(),1000*60*1,
pendingIntent);
}
}
AlarmReceiver.java
public class AlarmReceiver extends BroadcastReceiver
{
Location mCurrentLocation;
GPSTracker gps;
#Override
public void onReceive(Context context, Intent intent)
{
gps = new GPSTracker(context);
// check if GPS enabled
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
// \n is for new line
Toast.makeText(context, "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
}
GPSTracker.java
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
AndroidManifest.xml
register receiver in manifest file.
<receiver
android:name=".AlarmReceiver"
android:exported="false">
</receiver>
Happy Coding !!!
It might not be possible because
Android Guidelines have changed above version 4.0. You cannot change GPS off on programmatically for versions above 4.0. However, you can change wifi off on programmatically
Apps cannot enable or disable GPS programmatically, except perhaps on rooted devices. Please allow the user to do that.
But Below 4.0 there might be a possibilty check this post
How can I enable or disable the GPS programmatically on Android?

how to update latitude and longitude through a background service at regular intervals?

I have written a background service to insert latitude , longitude and some other details into my sqlite database based on the time limit set in my AlarmManager.
I am using GoogleApiClient to calculate latitude and longitude , but i am facing some problems.
Problem
When i am travelling outside without net , the latitude and longitude is not getting updated at regular intervals. The data is getting inserted in my sqlite at regular intervals but latitude and longitude remains same even after half an hour though i am travelling some about 10 kms.
I want the latitude and longitude to change while i am travelling like auto update.
I wanted to know if the FusedLocationApi calculates latitude longitude properly even if i am not connected to the internet , if yes then i need some suggestions to improve the code that i have tried.
Code i have tried.
AlarmManagerService.java
public class AlarmManagerService extends Service implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
private static final String TAG = "AlarmManagerService";
AlarmReceiver alarmReceiver;
DriverDbHelper driverDbHelper;
Handler handler;
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
private Location mLastLocation;
// Google client to interact with Google API
private GoogleApiClient mGoogleApiClient;
// boolean flag to toggle periodic location updates
private boolean mRequestingLocationUpdates = false;
private LocationRequest mLocationRequest;
// Location updates intervals in sec
private static int UPDATE_INTERVAL = 120000; // 2 mins
private static int FATEST_INTERVAL = 60000; // 1 min
private static int DISPLACEMENT = 10; // 10 meters
public Activity activity;
protected String mLastUpdateTime;
String areaName0, areaName1, areaName2, areaName3, fullAreaName,
sessionMobileNo, sessionDriverName, sessionDID, sessiondriverUserId,
date, time, dateTime, doc, trac_transId;
double latitude, longitude;
PowerManager.WakeLock mWakeLock;
SessionManager session;
ConnectionDetector cd;
Boolean isInternet = false;
String sync_no = "No";
String sync_yes = "Yes";
public AlarmManagerService() {
alarmReceiver = new AlarmReceiver();
driverDbHelper = new DriverDbHelper(this);
cd = new ConnectionDetector(this);
}
public void setActivity(Activity activity) {
this.activity = activity;
}
#Override
public void onCreate() {
super.onCreate();
try {
driverDbHelper.open(AlarmManagerService.this);
} catch (Exception e) {
e.printStackTrace();
}
Log.d("Service created", "Alarm Service Created");
// First we need to check availability of play services
if (checkPlayServices()) {
// Building the GoogleApi client
buildGoogleApiClient();
createLocationRequest();
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
PowerManager mgr = (PowerManager)
getSystemService(Context.POWER_SERVICE);
if (this.mWakeLock == null) {
this.mWakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"MyWakeLock");
}
if (!this.mWakeLock.isHeld()) {
this.mWakeLock.acquire();
}
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
Log.d("Service started", "Alarm Service Started");
handler = new Handler(Looper.myLooper());
handler.post(new Runnable() {
#Override
public void run() {
postDatabaseDetails();
}
});
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d("Service started", "Alarm Service Destroyed");
if (mGoogleApiClient.isConnected()) {
stopLocationUpdates();
mGoogleApiClient.disconnect();
}
if (this.mWakeLock != null) {
this.mWakeLock.release();
this.mWakeLock = null;
}
}
private void displayLocation() {
if (mLastLocation != null) {
latitude = mLastLocation.getLatitude();
longitude = mLastLocation.getLongitude();
List<Address> addressList = null;
try {
Geocoder gcd = new Geocoder(getBaseContext(),
Locale.getDefault());
addressList = gcd.getFromLocation(mLastLocation.getLatitude(),
mLastLocation.getLongitude(), 1);
if (addressList != null && addressList.size() > 0) {
Address address = addressList.get(0);
areaName0 = address.getLocality(); // city name
areaName1 = address.getSubLocality();
areaName2 = address.getAdminArea();// statename
//areaName3 = address.getFeatureName(); plot no
//areaName3 = address.getCountryCode();// IN
areaName3 = address.getThoroughfare();
fullAreaName = areaName3 + "\n" + areaName1 + "\n" +
areaName0 + "," + areaName2;
} else {
Log.i("Location ", "Location null");
}
} catch (IOException e1) {
Log.e("HomePage", "IO Exception in getFromLocation()");
e1.printStackTrace();
} catch (IllegalArgumentException e2) {
// Error message to post in the log
String errorString = "Illegal arguments " +
Double.toString(mLastLocation.getLatitude()) + " , " +
Double.toString(mLastLocation.getLongitude()) +
" passed to address service";
Log.e("HomePage", errorString);
e2.printStackTrace();
}
}
}
/**
* Creating google api client object
*/
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
}
/**
* Creating location request object
*/
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL);
//mLocationRequest.setFastestInterval(FATEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
}
/**
* Method to verify google play services on the device
*/
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, activity,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Log.i("Google play services", "Device not supported");
activity.finish();
}
return false;
}
return true;
}
/**
* Starting the location updates
*/
protected void startLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
/**
* Stopping location updates
*/
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
}
#Override
public void onConnected(Bundle bundle) {
// Once connected with google api, get the location
//displayLocation();
if (mRequestingLocationUpdates) {
startLocationUpdates();
}
if (mLastLocation == null) {
mLastLocation =
LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
displayLocation();
}
}
#Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
#Override
public void onLocationChanged(Location location) {
// Assign the new location
mLastLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
Log.d("Location changed ", "Location changed " + mLastLocation);
Log.d("Last updated time", "Last updated location " + mLastUpdateTime);
// Displaying the new location on UI
displayLocation();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
+ connectionResult.getErrorCode());
}
public void postDatabaseDetails() {
session = new SessionManager(getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
sessionMobileNo = user.get(SessionManager.KEY_MOBILENO);
sessionDriverName = user.get(SessionManager.KEY_NAME);
sessionDID = user.get(SessionManager.KEY_DEVICEID);
sessiondriverUserId = user.get(SessionManager.KEY_DRIVERUSERID);
Calendar in = Calendar.getInstance();
Date dt = new Date();
in.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat stf = new SimpleDateFormat("HH:mm:ss");
date = sdf.format(dt);
time = stf.format(dt);
String timeval = time.toString();
String dateval = date.toString();
dateTime = date.toString() + " " + time.toString();
doc = sessionDID + "" + dateTime;
isInternet = cd.isConnectingToInternet();
if (isInternet) {
long id = driverDbHelper.insertDriverDetails(doc, sessionDID,
sessiondriverUserId, latitude, longitude,
fullAreaName, dateTime, "DEMO", sync_no, dateval, timeval);
postDriverDetails();
Log.d("GPS", "Service started after 2 mins with internet");
} else {
Log.d("Internet status", "No internet available for service");
long id = driverDbHelper.insertDriverDetails(doc, sessionDID,
sessiondriverUserId, latitude, longitude,
"NA", dateTime, "DEMO", sync_no, dateval, timeval);
Log.d("GPS", "Service started after 2 mins without internet");
}
}
I am calling this service from the activity HomePage.java , but from where do i have to call the below code , from onStart() or after setContentView(R.layout.home)?
try {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MINUTE, 2);
AlarmManager am = (AlarmManager)
getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(Home_Page.this, AlarmManagerService.class);
PendingIntent pi = PendingIntent.getService(Home_Page.this, 0, i,0);
am.setInexactRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), EXEC_INTERVAL, pi);
} catch (Exception e) {
e.printStackTrace();
}
I hope i can get some suggestions to improve the above service code as i want it to run smoothly in background updating the latitude and longitude at regular intervals.

Making the helper class with FusedLocation api

I am trying to retrieve location via fused location api.I have tried to build a helper class so that I can use it throughout my app.
Code:
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.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class GPSTracker2 implements ConnectionCallbacks,
OnConnectionFailedListener,LocationListener {
// LogCat tag
private static final String TAG = GPSTracker2.class.getSimpleName();
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
private Location mLastLocation;
// Google client to interact with Google API
private GoogleApiClient mGoogleApiClient;
// boolean flag to toggle periodic location updates
private boolean mRequestingLocationUpdates = false;
private LocationRequest mLocationRequest;
// Location updates intervals in sec
private static int UPDATE_INTERVAL = 1000; // 10 sec
private static int FATEST_INTERVAL = 500; // 5 sec
private static int DISPLACEMENT = 10; // 10 meters
Context context;
// flag for GPS status
boolean canGetLocation = true;
double latitude,longitude;
public GPSTracker2(Context context) {
// TODO Auto-generated constructor stub
// First we need to check availability of play services
this.context=context;
createLocationRequest();
if (checkPlayServices()) {
// Building the GoogleApi client
buildGoogleApiClient();
}
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
// Show location button click listener
}
/**
* Method to display the location on UI
* */
/*private void displayLocation() {
mLastLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
} else {
}
}*/
/**
* Method to display the location on UI
* */
private void displayLocation() {
mLastLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
Toast.makeText(context,latitude+" "+longitude,Toast.LENGTH_LONG).show();
} else {
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
mLastLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
this.canGetLocation = true;
double latitude = mLastLocation.getLatitude();
System.out.println("In GetLat==>"+latitude);
return latitude;
}else{
System.out.println("last known null");
return 0.0;
}
}
/**
* Function to get longitude
* */
public double getLongitude(){
mLastLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
this.canGetLocation = true;
longitude = mLastLocation.getLongitude();
System.out.println("In Getlong==>"+longitude);
}
return longitude;
}
/**
* Creating google api client object
* */
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(context)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
}
/**
* Method to verify google play services on the device
* */
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(context);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, (Activity) context,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Toast.makeText(context,
"context device is not supported.", Toast.LENGTH_LONG)
.show();
//finish();
}
return false;
}
return true;
}
/**
* Creating location request object
* */
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FATEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
}
/**
* Starting the location updates
* */
protected void startLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
/**
* Stopping location updates
*/
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
}
/**
* Google api callback methods
*/
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
+ result.getErrorCode());
}
#Override
public void onConnected(Bundle arg0) {
// Once connected with google api, get the location
// displayLocation();
//getLatitude();
//getLongitude();
displayLocation();
System.out.println("On Connected");
if (mRequestingLocationUpdates) {
startLocationUpdates();
}
}
#Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
}
#Override
public void onLocationChanged(Location location) {
// Assign the new location
mLastLocation = location;
Toast.makeText(context, "Location changed!",
Toast.LENGTH_SHORT).show();
displayLocation();
// Displaying the new location on UI
// displayLocation();
// getLatitude();
// getLongitude();
}
/**
* Function to check GPS/wifi enabled
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
}
I am trying to use this as:
The CallingClass.java
GPSTracker2 gps=new GPSTracker2(SettingsActivity.this);
if(gps.canGetLocation())
{
System.out.println("lat-->"+gps.getLatitude()+" long===>"+gps.getLongitude());
}else{
showSettingsAlert(true);
}
The Problem:
Methods gps.getLatitude() and gps.getLongitude() is returning 0.0.But in the toast message (within the displayLocation(); method) the latitude and longitude is coming perfectly.
Hence I debugged my application and found that after calling the constructor of GpsTracker2 class,control is going back to the calling class and after finishing the onCreate of the calling class,the GoogleApiclient is getting connected.Hence it cannot fetch the latitude and longitude within the onCreate() of the calling class and hence the result.
How can I overcome this problem??
You are querying your gps helper before it has a location. For example in your getLatitude method.
public double getLatitude(){
mLastLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
// At first mLastKnownLocation will be null
if (mLastLocation != null) {
this.canGetLocation = true;
double latitude = mLastLocation.getLatitude();
System.out.println("In GetLat==>"+latitude);
return latitude;
} else {
System.out.println("last known null");
return 0.0; // This here is what is being returned.
}
}
It isn't until your apiclient has called public void onLocationChanged(Location location) that a location will become available.
Method 1
Return a Location object instead of primitives. This way you can return null if it is being queried too early and the caller can handle it.
Method 2
The users of your GPS helper register a callback with it. Now they will be notified when a location is available.
In the GPSTracker class
List<LocationListener> listeners = new ArrayList<>();
public void registerListener(LocationListener listener) {
listeners.add(listener);
}
public void removeListener(LocationListener listener) {
listeners.remove(listener);
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
for (LocationListener listener : listeners) {
listener.onLocationChanged(location);
}
}
User of GPSTracker
GPSTracker gps = new GPSTracker();
LocationListener myCallback = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// This code runs every time your gps gets a new location
System.out.println("lat-->"+location.getLatitude()+" long===>"+location.getLongitude());
doStuffWithLocation(location);
}
};
gps.registerListener(myCallback);
// Then when you are finished
gps.removeListener(myCallback);
I find class GooglePlayServicesHelper
after use code below in Activity
geoGPS = new GooglePlayServicesHelper(mContext, true);
mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
Logger.debug("lat: " + latitude);
Logger.debug("long: " + longitude);
}
};

Categories

Resources