avoid same locations while checking location updates in android - android

I want to send location data to server after a certain time from my android app. I used service and AlarmManager to check location updates continuously in background.
But my problem is that the app sends too many data to server; so that, while I see those location data on map it shows so many data on same location. How can I solve this issue?
Here is the portion of the code where I checked minimum time and distance to check location updates.
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30000, 15, listener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 15, listener);
Is that safe to use minTimeto 30000 milliseconds and minDistance to 15 meters?
If it is ok then how should I filter only one data of a same
location?
If it is not safe then how should I avoid same location data?
I added my LocationListener code below. Here I am checking the best location and sending data to server.
public class MyLocationListener implements LocationListener
{
public void onLocationChanged(final Location loc)
{
Log.i("**************************************", "Location changed");
if(isBetterLocation(loc, previousBestLocation)) {
loc.getLatitude();
loc.getLongitude();
intent.putExtra("Latitude", loc.getLatitude());
intent.putExtra("Longitude", loc.getLongitude());
intent.putExtra("Provider", loc.getProvider());
sendBroadcast(intent);
mySpeed = loc.getSpeed() * 1.94384449;
myKmph = loc.getSpeed() * 3.6;
myBearing = loc.getBearing();
double flat = loc.getLatitude(); //-32.827141
double flon = loc.getLongitude(); //139.667476
int inlat = (int) flat; //-32
int inlon = (int) flon; //139
float minlat = (float) (flat % 1) * 60; //10.371540000000152
float minlon = (float) (flon % 1) * 60; //
minlat = (minlat < 0) ? -minlat : minlat;
minlon = (minlon < 0) ? -minlon : minlon;
String norther = "N";
String souther = "S";
String easter = "E";
String wester = "W";
String northsouther = "";
String eastwester = "";
if(flat>=0.0) {
northsouther = norther;
}
else {
northsouther = souther;
}
if(flon>=0.0) {
eastwester = easter;
}
else {
eastwester = wester;
}
String text = "...my formate to send data...";
try {
String ip = "XX.XXX.XXX.XXX";
int port = XXXX;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Socket clientSocket = new Socket(ip, port);
DataOutputStream outToServer = new DataOutputStream(
clientSocket.getOutputStream());
outToServer.writeBytes(text);
clientSocket.close();
Log.d("LocationService", "Data sent successfully");
} catch (Exception e) {
Log.e("LocationService", "[Error] Either in Sending Data or the callback" + e.toString());
}
}
}
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show();
}
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
Please suggest me possible ways to overcome this situation?
Thanks in advance.

You can provide a validation of some kind in this code.Lets say we provide a validation that if the distance moved is more than 15 meters we send the latitude and longitude to the server.You can write your code like this:
public class MyLocationListener implements LocationListener
{
public void onLocationChanged(final Location loc)
{
Log.i("**************************************", "Location changed");
if(isBetterLocation(loc, previousBestLocation)) {
loc1_lat =loc.getLatitude();
loc1_long = loc.getLongitude();
// define double loc2_lat==0 and loc2_long=0 so we initially enter this condition;
if ((loc2_lat == null || loc2_lat == 0.0)
&& (loc2_long == null || loc2_long == 0.0))
{
double loc2_lat = loc1_lat;
double loc2_long = loc1_long;
}
//new piece of code goes here.
Location locationA = new Location("point A");
locationA.setLatitude(loc1_lat);
locationA.setLongitude(loc1_long);
Location locationB = new Location("point B");
locationB.setLatitude(loc2_lat);
locationB.setLongitude(loc2_lat);
//calculate distance between current lat long and future lat long
float calculated_distance = locationA.distanceTo(locationB);
//calculated_distance in meter.
calculated_distance = distance_U_driver / 1000;
//put this validation by yourself in meters.If you want your device to move 15 meter and then send the next coordinate
if(calculated_distance > 15){
intent.putExtra("Latitude", loc.getLatitude());
intent.putExtra("Longitude", loc.getLongitude());
intent.putExtra("Provider", loc.getProvider());
sendBroadcast(intent);
}
mySpeed = loc.getSpeed() * 1.94384449;
myKmph = loc.getSpeed() * 3.6;
myBearing = loc.getBearing();
double flat = loc.getLatitude(); //-32.827141
double flon = loc.getLongitude(); //139.667476
int inlat = (int) flat; //-32
int inlon = (int) flon; //139
float minlat = (float) (flat % 1) * 60; //10.371540000000152
float minlon = (float) (flon % 1) * 60; //
minlat = (minlat < 0) ? -minlat : minlat;
minlon = (minlon < 0) ? -minlon : minlon;
String norther = "N";
String souther = "S";
String easter = "E";
String wester = "W";
String northsouther = "";
String eastwester = "";
if(flat>=0.0) {
northsouther = norther;
}
else {
northsouther = souther;
}
if(flon>=0.0) {
eastwester = easter;
}
else {
eastwester = wester;
}
String text = "...my formate to send data...";
try {
String ip = "XX.XXX.XXX.XXX";
int port = XXXX;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Socket clientSocket = new Socket(ip, port);
DataOutputStream outToServer = new DataOutputStream(
clientSocket.getOutputStream());
outToServer.writeBytes(text);
clientSocket.close();
Log.d("LocationService", "Data sent successfully");
} catch (Exception e) {
Log.e("LocationService", "[Error] Either in Sending Data or the callback" + e.toString());
}
}
}
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show();
}
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}

Related

Log Location Coordinates using a Service

Guys I am trying to create an app that logs your locations' coordinates using the location class and the service class, but it doesn't work !
I don't know how to start!!!
here is my sevice file:
public class LocationService extends Service {
private static final long ONE_MIN = 1000 * 60;
private static final long TWO_MIN = ONE_MIN * 2;
private static final long FIVE_MIN = ONE_MIN * 5;
private static final long MEASURE_TIME = 1000 * 30;
private static final long POLLING_FREQ = 1000 * 10;
private static final float MIN_ACCURACY = 25.0f;
private static final float MIN_LAST_READ_ACCURACY = 500.0f;
private static final float MIN_DISTANCE = 10.0f;
private static final int NOTIFICATION_ID = 1;
// Current best location estimate
private Location mBestReading;
WIWDb db;
// Reference to the LocationManager and LocationListener
private LocationManager mLocationManager;
private LocationListener mLocationListener;
private final String TAG = "LocationGetLocationActivity";
private boolean mFirstUpdate = true;
#SuppressLint("NewApi") #Override
public void onCreate() {
super.onCreate();
Log.i(TAG,"here");
db=new WIWDb(this);
// Acquire reference to the LocationManager
if (null == (mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE)))
Toast.makeText(getBaseContext(), "Error", Toast.LENGTH_LONG).show();
// Get best last location measurement
mBestReading = bestLastKnownLocation(MIN_LAST_READ_ACCURACY, FIVE_MIN);
// Display last reading information
if (null != mBestReading) {
updateDisplay(mBestReading);
} else {
Toast.makeText(getBaseContext(),"No Initial Reading Available",Toast.LENGTH_LONG).show();
//mAccuracyView.setText("No Initial Reading Available");
}
mLocationListener = new LocationListener() {
// Called back when location changes
public void onLocationChanged(Location location) {
// Determine whether new location is better than current best
// estimate
if (null == mBestReading
|| location.getAccuracy() < mBestReading.getAccuracy()) {
// Update best estimate
mBestReading = location;
// Update display
updateDisplay(location);
if (mBestReading.getAccuracy() < MIN_ACCURACY)
mLocationManager.removeUpdates(mLocationListener);
}
}
public void onStatusChanged(String provider, int status,
Bundle extras) {
// NA
}
public void onProviderEnabled(String provider) {
// NA
}
public void onProviderDisabled(String provider) {
// NA
}
};
// Create a notification area notification so the user
// can get back to the MusicServiceClient
final Intent notificationIntent = new Intent(getApplicationContext(),
MainActivity.class);
final PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
final Notification notification = new Notification.Builder(
getApplicationContext())
.setSmallIcon(android.R.drawable.ic_menu_compass)
.setOngoing(true).setContentTitle("Location tracking...")
.setContentText("Back to WIW")
.setContentIntent(pendingIntent).build();
// Put this Service in a foreground state, so it won't
// readily be killed by the system
startForeground(NOTIFICATION_ID, notification);
}
private Location bestLastKnownLocation(float minAccuracy, long maxAge) {
Location bestResult = null;
float bestAccuracy = Float.MAX_VALUE;
long bestAge = Long.MIN_VALUE;
List<String> matchingProviders = mLocationManager.getAllProviders();
for (String provider : matchingProviders) {
Location location = mLocationManager.getLastKnownLocation(provider);
if (location != null) {
float accuracy = location.getAccuracy();
long time = location.getTime();
if (accuracy < bestAccuracy) {
bestResult = location;
bestAccuracy = accuracy;
bestAge = time;
}
}
}
// Return best reading or null
if (bestAccuracy > minAccuracy
|| (System.currentTimeMillis() - bestAge) > maxAge) {
return null;
} else {
return bestResult;
}
}
#SuppressWarnings("deprecation")
private void updateDisplay(Location location) {
StringBuilder sb=new StringBuilder();
sb.append("Accuracy:" + location.getAccuracy());
//mAccuracyView.setText("Accuracy:" + location.getAccuracy());
sb.append("Time:"+ new SimpleDateFormat("MM/dd/yyyy HH:mm:ss", Locale.getDefault()).format(new Date(location.getTime())));
//mTimeView.setText("Time:"+ new SimpleDateFormat("MM/dd/yyyy HH:mm:ss", Locale.getDefault()).format(new Date(location.getTime())));
sb.append("Longitude:" + location.getLongitude());
//mLatView.setText("Longitude:" + location.getLongitude());
sb.append("Latitude:" + location.getLatitude());
//mLngView.setText("Latitude:" + location.getLatitude());
//db.insertCordsToDb(String.valueOf(location.getLongitude())+","+String.valueOf( location.getLatitude()),String.valueOf(new Date().getDate()) ,String.valueOf(location.getTime()));
db.insertCordsToDb(String.valueOf(location.getLongitude())+","+String.valueOf(lo cation.getLatitude()),new SimpleDateFormat("MM/dd/yyyy", Locale.getDefault()).format(new Date(location.getTime())) ,new SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(new Date(location.getTime())));
}
protected void onResume() {
// Determine whether initial reading is
// "good enough". If not, register for
// further location updates
if (null == mBestReading
|| mBestReading.getAccuracy() > MIN_LAST_READ_ACCURACY
|| mBestReading.getTime() < System.currentTimeMillis()
- TWO_MIN) {
// Register for network location updates
if (null != mLocationManager
.getProvider(LocationManager.NETWORK_PROVIDER)) {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, POLLING_FREQ,
MIN_DISTANCE, mLocationListener);
}
// Register for GPS location updates
if (null != mLocationManager
.getProvider(LocationManager.GPS_PROVIDER)) {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, POLLING_FREQ,
MIN_DISTANCE, mLocationListener);
}
// Schedule a runnable to unregister location listeners
Executors.newScheduledThreadPool(1).schedule(new Runnable() {
#Override
public void run() {
Log.i(TAG, "location updates cancelled");
mLocationManager.removeUpdates(mLocationListener);
}
}, MEASURE_TIME, TimeUnit.MILLISECONDS);
}
}
// Unregister location listeners
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
please guide to finish this application

Android geocoding api can't return addressess

I'm having some trouble geocoding locations, i guess i've implemented everything. I've registered a google api, i've recieved a working google Api key, i also turned on google maps and geocoding services, but i can't get any locations associated with some hardcoded longitudes and latitudes.
Here's the code:
My AppLocationService
public class AppLocationService extends Service implements LocationListener {
protected LocationManager locationManager;
Location location;
private static final long MIN_DISTANCE_FOR_UPDATE = 10;
private static final long MIN_TIME_FOR_UPDATE = 1000 * 60 * 2;
public AppLocationService(Context context) {
locationManager = (LocationManager) context
.getSystemService(LOCATION_SERVICE);
}
public Location getLocation(String provider) {
if (locationManager.isProviderEnabled(provider)) {
locationManager.requestLocationUpdates(provider,
MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider);
return location;
}
}
return null;
}
#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;
}
}
My LocationAddress class
public class LocationAddress {
private static final String TAG = "LocationAddress";
public static void getAddressFromLocation(final double latitude, final double longitude,
final Context context, final Handler handler) {
Thread thread = new Thread() {
#Override
public void run() {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
String result = null;
try {
List<Address> addressList = geocoder.getFromLocation(
latitude, longitude, 1);
if (addressList != null && addressList.size() > 0) {
Address address = addressList.get(0);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
sb.append(address.getAddressLine(i)).append("\n");
}
sb.append(address.getLocality()).append("\n");
sb.append(address.getPostalCode()).append("\n");
sb.append(address.getCountryName());
result = sb.toString();
}
} catch (IOException e) {
Log.e(TAG, "Unable connect to Geocoder", e);
} finally {
Message message = Message.obtain();
message.setTarget(handler);
if (result != null) {
message.what = 1;
Bundle bundle = new Bundle();
result = "Latitude: " + latitude + " Longitude: " + longitude +
"\n\nAddress:\n" + result;
bundle.putString("address", result);
message.setData(bundle);
} else {
message.what = 1;
Bundle bundle = new Bundle();
result = "Latitude: " + latitude + " Longitude: " + longitude +
"\n Unable to get address for this lat-long.";
bundle.putString("address", result);
message.setData(bundle);
}
message.sendToTarget();
}
}
};
thread.start();
}
}
Somewhere deep in my mainActivity:
appLocationService = new AppLocationService(
ServerInterface.this);
Location location = appLocationService
.getLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
double latitude = 47.162494;
double longitude = 19.503304;
LocationAddress locationAddress = new LocationAddress();
LocationAddress.getAddressFromLocation(latitude, longitude,
getApplicationContext(), new GeocoderHandler());
}
Thanks,
I think you can take look at this. I tried and it worked.
Hope it hopes.

How to get the most accurate speed from Location [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I have a service class to get speed, address, location, latitude and longitude from GPS. My existing app gets a good result with a little tolerance. But i want to get the most accurate speed from location.getSpeed() method. For example when i have constant 80km/h speed, it shows me 76 or 77km/h. How can i increase accuracy? I want to do it without any error margin.
My GPSLocation Service:
public class GPSLocationService extends Service {
private static final String TAG = "GPSLocationService";
private LocationManager locationManager;
private LocationListener gpsLocationListener;
private long lastGPStime;
private double lastLatitude;
private double lastLongitude;
private float lastSpeed;
private Address lastAddress;
private Location mLastLocation;
private float maxSpeed;
private final float metersSec_in_KMPH = 3.6f;
#SuppressLint("SimpleDateFormat")
private SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss.SSS");
// other modules will call these public methonds
public String getTime() {
return timeFormat.format(new Date(lastGPStime));
}
public String getLocation(){
if(mLastLocation != null)
return mLastLocation.toString();
else
return "0";
}
public String getAddress(){
if(lastAddress != null)
return lastAddress.getAddressLine(0) + " " + lastAddress.getAddressLine(1) + " " + lastAddress.getAddressLine(2) + " " + lastAddress.getAddressLine(3);
else
return "0";
}
public float getSpeedFloat(){
if (lastSpeed < 1.0f) { return 0; }
float mph = lastSpeed * metersSec_in_KMPH;
return mph;
}
public Float getGpsStatus(){
if(mLastLocation != null)
return mLastLocation.getAccuracy();
else
return 0.0f;
}
// latitude ranges from 0.0 to 90.0
// In the US, latitude is always double-digits: 44.xxyyzz
// We'll keep six digits after the decimal point
public String getLat() {
String lValue = Double.toString(lastLatitude);
if (lValue.length() < 9)
return lValue;
return lValue.substring(0, 9);
} // latitude has max 2 digits before
// in the US, Longitude is always three digits: 123.xxyyzz
// We'll keep six digits after the decimal point (ITIS)
public String getLong() {
String lValue = Double.toString(lastLongitude);
if (lValue.length() < 10)
return lValue;
return lValue.substring(0, 10);
} // longitude has up to 3 digits
// speed is reported in meters/second
// speed needs three digits, and maybe three more past the decimal point:
// 145.608
public String getSpeed() {
if (lastSpeed < 1.0f) { return "000"; }
float mph = lastSpeed * metersSec_in_KMPH;
String lValue = Integer.toString((int) mph);
return lValue;
}
public String getMaxSpeed() {
if (maxSpeed < 1.0f) { return "0.0"; }
String lValue = Float.toString(maxSpeed * metersSec_in_KMPH);
if (lValue.length() < 7) {
return lValue;
} else
return lValue.substring(0, 7);
}
// setup this service to allow binding for access to public methods above.
// http://developer.android.com/guide/components/bound-services.html
private final IBinder mBinder = new GPSBinder();
public class GPSBinder extends Binder {
GPSLocationService getService() {
return GPSLocationService.this;
}
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
// the usual 'Service' methods below
#Override
public void onCreate() {
super.onCreate();
// instantiate the inner class
gpsLocationListener = new GPSLocationListener();
// get the system manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// and demand Speed values
Criteria criteria = new Criteria();
criteria.setSpeedRequired(true);
locationManager.requestLocationUpdates(
locationManager.getBestProvider(criteria, false), 250,
5, gpsLocationListener);
Toast toast = Toast.makeText(GPSLocationService.this, "GPS updates requested.", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
#Override
public void onDestroy() {
super.onDestroy();
locationManager.removeUpdates(gpsLocationListener);
}
private class GPSLocationListener implements LocationListener,
GpsStatus.Listener {
boolean isGPSFix;
public void onGpsStatusChanged(int event) {
switch (event) {
case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
if (mLastLocation != null)
isGPSFix = (SystemClock.elapsedRealtime() - lastGPStime) < 3000;
if (isGPSFix) { // A fix has been acquired.
Toast toast = Toast.makeText(GPSLocationService.this, "GPS has a fix.", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
} else { // The fix has been lost.
Toast toast = Toast.makeText(GPSLocationService.this, "GPS DOES NOT have a fix.", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
break;
case GpsStatus.GPS_EVENT_FIRST_FIX:
Toast toast = Toast.makeText(GPSLocationService.this, "GPS got first fix.", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
isGPSFix = true;
break;
}
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
try {
lastAddress = getAddressForLocation(Main.context, location);
} catch (IOException e) {
Log.i("EXCEPTION", "Exception on Address");
e.printStackTrace();
}
lastGPStime = location.getTime();
lastLatitude = location.getLatitude();
lastLongitude = location.getLongitude();
lastSpeed = location.getSpeed();
if (lastSpeed > maxSpeed) {
maxSpeed = lastSpeed;
}
Log.i(TAG, "GPS update received.");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
String statusDescription = "unknown";
switch (status) {
case LocationProvider.OUT_OF_SERVICE:
statusDescription = "OUT_OF_SERVICE";
break;
case LocationProvider.AVAILABLE:
statusDescription = "AVAILABLE";
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
statusDescription = "TEMPORARILY_UNAVAILABLE";
break;
}
Toast toast = Toast.makeText(GPSLocationService.this, TAG + " GPS provider status changed to "
+ statusDescription + "and the last speed was: " + getSpeed() , Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
#Override
public void onProviderEnabled(String provider) {
Toast toast = Toast.makeText(GPSLocationService.this, "GPS provider enabled.", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
#Override
public void onProviderDisabled(String provider) {
Toast toast = Toast.makeText(GPSLocationService.this, "GPS provider disabled?", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}
public void zeroMaxSpeed() {
maxSpeed = 0.0f;
}
public Address getAddressForLocation(Context context, Location location) throws IOException {
if (location == null) {
return null;
}
double latitude = location.getLatitude();
double longitude = location.getLongitude();
int maxResults = 1;
Geocoder gc = new Geocoder(context, Locale.getDefault());
List<Address> addresses = gc.getFromLocation(latitude, longitude, maxResults);
return addresses.get(0);
}
}
I use this service's methods from my Main class:
public class Main extends Activity {
private GPSLocationService gpsService;
private ServiceConnection gpsSvcConn;
private boolean isGPSserviceBound;
private static final String TAG = "FullScreenSpeed";
private Thread updateThread;
private Handler handler = new Handler();
private TextView address;
private TextView lat;
private TextView longi;
private TextView velocity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
address = (TextView) findViewById(R.id.address);
lat = (TextView) findViewById(R.id.latitude);
longi = (TextView) findViewById(R.id.longitude);
velocity = (TextView) findViewById(R.id.velocity);
updateThread = new Thread() {
public void run() {
if (isGPSserviceBound) {
speed = gpsService.getSpeed();
latitude = gpsService.getLat();
longitude = gpsService.getLong();
address.setText("Address: " + gpsService.getAddress());
lat.setText("Latitude: " + latitude);
longi.setText("Longitude: " + longitude);
velocity.setText("Velocity: " + speed + " Km/h");
if(i == 10){
i=0;
}
else{
arrayVelocity[i] = speed;
arrayLatitude[i] = latitude;
arrayLongitude[i] = longitude;
Log.i("HIZ","arrayVelocity[" + i + "] = " + speed);
Log.i("HIZ","arrayLatitude[" + i + "] = " + latitude);
Log.i("HIZ","arrayLongitude[" + i + "] = " + longitude);
i++;
}
} // GPS service isn't bound, can't do anything
handler.postDelayed(this, 14000); // wait a while
}
};
}
private void startGPSService() {
startService(new Intent(this, GPSLocationService.class));
gpsSvcConn = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder binder) {
GPSBinder gpsBinder = (GPSBinder) binder;
gpsService = gpsBinder.getService();
isGPSserviceBound = true;
Toast toast = Toast.makeText(Main.this, "GPS service bound", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
#Override
public void onServiceDisconnected(ComponentName name) {
isGPSserviceBound = false;
Toast toast = Toast.makeText(Main.this, "GPS service came unbound?", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
};
Intent intent = new Intent(this, GPSLocationService.class);
bindService(intent, gpsSvcConn, Context.BIND_AUTO_CREATE);
Log.i(TAG, "started gps service");
Toast toast = Toast.makeText(Main.this, "Started to bind to GPS service", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
#Override
protected void onResume() {
super.onResume();
handler.postDelayed(updateThread, 0);
Toast toast = Toast.makeText(Main.this, "MainActivity resumed", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
#Override
protected void onStop() {
super.onStop();
Toast toast = Toast.makeText(Main.this, "MainActivity stopped", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}
After checking these links Link1 and Link2, i realize that my speed is correct and the speedometer of the cars where i tested my app on do not show correct value. They always show much then real speed of the car. So, the value from my app is better than the cars' speedometers.

How to run a background process in service method completely?

Hi can any body show me how to run this code in service without activity, i have done this code in an activity but i dont want it to be an application i need it to be in a service only just to display it on service thank you i have tried but my activity displaying for once in 30 mins.
this is my code:
public class gps extends Activity implements LocationListener {
LocationManager manager;
String closestStation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
{
Calendar cur_cal = Calendar.getInstance();
cur_cal.setTimeInMillis(System.currentTimeMillis());
cur_cal.add(Calendar.MINUTE, 15);
Log.d("Testing", "Calender Set time:" + cur_cal.getTime());
Intent intent = new Intent(gps.this, gps_back_process.class);
PendingIntent pintent = PendingIntent.getService(gps.this, 0,
intent, 0);
AlarmManager alarm_manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm_manager.setRepeating(AlarmManager.RTC_WAKEUP,
cur_cal.getTimeInMillis(), 1000 * 60 * 15, pintent);
alarm_manager.set(AlarmManager.RTC, cur_cal.getTimeInMillis(),
pintent);
Log.d("Testing", "alarm manager set");
Toast.makeText(this, "gps_back_process.onCreate()",
Toast.LENGTH_LONG).show();
}
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
this.sendBroadcast(intent);
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(!provider.contains("gps")){ //if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
this.sendBroadcast(poke);
}
{
//initialize location manager
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//check if GPS is enabled
//if not, notify user with a toast
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)); else {
//get a location provider from location manager
//empty criteria searches through all providers and returns the best one
String providerName = manager.getBestProvider(new Criteria(), true);
Location location = manager.getLastKnownLocation(providerName);
TextView tv = (TextView)findViewById(R.id.locationResults);
if (location != null) {
tv.setText(location.getLatitude() + " latitude, " + location.getLongitude() + " longitude");
} else
{
tv.setText("Last known location not found. Waiting for updated location...");
}
manager.requestLocationUpdates(providerName, 1000*60*30 , 1 , this);
}
}
}
#Override
public void onLocationChanged(Location location) {
TextView tv = (TextView)findViewById(R.id.locationResults);
if (location != null) {
tv.setText(location.getLatitude() + " latitude, " + location.getLongitude() + " longitude");
// I have added this line
appendData ( location.getLatitude() + " latitude, " + location.getLongitude() + " longitude" );
} else {
tv.setText("Problem getting gps NETWORK ID : " + "");
}
}
#Override
public void onProviderDisabled(String arg0) {}
#Override
public void onProviderEnabled(String arg0) {}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}
// Find the closest Bart Station
public String findClosestBart(Location loc) {
double lat = loc.getLatitude();
double lon = loc.getLongitude();
double curStatLat = 0;
double curStatLon = 0;
double shortestDistSoFar = Double.POSITIVE_INFINITY;
double curDist;
String curStat = null;
String closestStat = null;
//sort through all the stations
// write some sort of for loop using the API.
curDist = Math.sqrt( ((lat - curStatLat) * (lat - curStatLat)) +
((lon - curStatLon) * (lon - curStatLon)) );
if (curDist < shortestDistSoFar) {
closestStat = curStat;
}
return closestStat;
}
// method to write in file
public void appendData(String text)
{
File dataFile = new File(Environment.getExternalStorageDirectory() + "/GpsData.txt");
if (!dataFile.exists())
{
try
{
dataFile.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try
{
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(dataFile, true));
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm, dd/MM/yyyy");
String currentDateandTime = sdf.format(new Date());
// text+=","+currentDateandTime;
buf.append(text + "," + currentDateandTime);
buf.newLine();
buf.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
1.extends service class instead of Activity class and
2. put your code into oncreate()
3.add your service into manefest.
4.call service from activity once like
Intent service = new Intent(context, localService.class);
context.startService(service);
follow this tutorial.

How to store a value from a textbox android?

i am developing an gps program in that i am getting gps values for every 5 minutes,
and it is working great, but i have to store the values which i get. it has been refreshed for every 5 minutes and i have only one text view so that it deletes the old values when the new one is refreshed.
this is my code.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
this.sendBroadcast(intent);
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(!provider.contains("gps")){ //if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
this.sendBroadcast(poke);
}
{
//initialize location manager
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//check if GPS is enabled
//if not, notify user with a toast
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)); else {
//get a location provider from location manager
//empty criteria searches through all providers and returns the best one
String providerName = manager.getBestProvider(new Criteria(), true);
Location location = manager.getLastKnownLocation(providerName);
TextView tv = (TextView)findViewById(R.id.locationResults);
if (location != null) {
tv.setText(location.getLatitude() + " latitude, " + location.getLongitude() + " longitude");
} else {
tv.setText("Last known location not found. Waiting for updated location...");
}
//sign up to be notified of location updates every 15 seconds - for production code this should be at least a minute
manager.requestLocationUpdates(providerName, 60000, 1, this);
}
}
}
#Override
public void onLocationChanged(Location location) {
TextView tv = (TextView)findViewById(R.id.locationResults);
if (location != null) {
tv.setText(location.getLatitude() + " latitude, " + location.getLongitude() + " longitude");
} else {
tv.setText("Problem getting location");
}
}
#Override
public void onProviderDisabled(String arg0) {}
#Override
public void onProviderEnabled(String arg0) {}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}
// Find the closest Bart Station
public String findClosestBart(Location loc) {
double lat = loc.getLatitude();
double lon = loc.getLongitude();
double curStatLat = 0;
double curStatLon = 0;
double shortestDistSoFar = Double.POSITIVE_INFINITY;
double curDist;
String curStat = null;
String closestStat = null;
//sort through all the stations
// write some sort of for loop using the API.
curDist = Math.sqrt( ((lat - curStatLat) * (lat - curStatLat)) +
((lon - curStatLon) * (lon - curStatLon)) );
if (curDist < shortestDistSoFar) {
closestStat = curStat;
}
return closestStat;
}
Thank you.
You can store your Textview's value into a file for persistance storage. Study my answer properly, I am adding a file store method in your existing code,
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
this.sendBroadcast(intent);
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(!provider.contains("gps")){ //if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
this.sendBroadcast(poke);
}
{
//initialize location manager
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//check if GPS is enabled
//if not, notify user with a toast
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)); else {
//get a location provider from location manager
//empty criteria searches through all providers and returns the best one
String providerName = manager.getBestProvider(new Criteria(), true);
Location location = manager.getLastKnownLocation(providerName);
TextView tv = (TextView)findViewById(R.id.locationResults);
if (location != null) {
tv.setText(location.getLatitude() + " latitude, " + location.getLongitude() + " longitude");
} else {
tv.setText("Last known location not found. Waiting for updated location...");
}
//sign up to be notified of location updates every 15 seconds - for production code this should be at least a minute
manager.requestLocationUpdates(providerName, 60000, 1, this);
}
}
}
#Override
public void onLocationChanged(Location location) {
TextView tv = (TextView)findViewById(R.id.locationResults);
if (location != null) {
tv.setText(location.getLatitude() + " latitude, " + location.getLongitude() + " longitude");
// I have added this line
appendData ( location.getLatitude() + " latitude, " + location.getLongitude() + " longitude" );
} else {
tv.setText("Problem getting location");
}
}
#Override
public void onProviderDisabled(String arg0) {}
#Override
public void onProviderEnabled(String arg0) {}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}
// Find the closest Bart Station
public String findClosestBart(Location loc) {
double lat = loc.getLatitude();
double lon = loc.getLongitude();
double curStatLat = 0;
double curStatLon = 0;
double shortestDistSoFar = Double.POSITIVE_INFINITY;
double curDist;
String curStat = null;
String closestStat = null;
//sort through all the stations
// write some sort of for loop using the API.
curDist = Math.sqrt( ((lat - curStatLat) * (lat - curStatLat)) +
((lon - curStatLon) * (lon - curStatLon)) );
if (curDist < shortestDistSoFar) {
closestStat = curStat;
}
return closestStat;
}
// method to write in file
public void appendData(String text)
{
File dataFile = new File("sdcard/gpsData.txt");
if (!dataFile.exists())
{
try
{
dataFile.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try
{
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(dataFile, true));
buf.append(text);
buf.newLine();
buf.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
You need to write following permission in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Well you have plenty of persistence options, but in this case the best is using SharedPreferences
No one can say for sure without knowing exactly what you need to do with the saved data. ArrayList is a good option if you need to store it temporarily. You can create a new ArrayList then put the value in there at the same time that you use it in setText(). If you want something permanent then you will probably want to store it in a DB or a file. Check out Storage Options
Also, in this case, a good idea may be to store it in an ArrayList temporarily then use that list to transfer them to a file or DB for permanent storage if that's what you want
Another way to store it temporarily, and possibly save somewhere later would be a HashMap. Maybe something in the form of HashMap<String, HashMap<String, String>>. Since we don't know your exact intentions with the data, examples could be endless but maybe this will give you a good starting point so you can decide what will work best for you then you can find many examples all over SO and the Google for your choice

Categories

Resources