Data not changed while inserting data from android to mysql database - java

I have a problem in inserting data (latitude and longitude) to mysql. when I first run the app, the lat and long are inserted but when I updated the location (lat and long) and insert the data again, only the longitude changes, and the latitude stays the same value as the previous data inserted. I'm totally confused why it doesnt work. I'd be very glad if anyone could help me with this.
This is my code
package com.android.tyegah;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class TyegahActivity extends Activity {
private LocationManager locationManager;
private Location latestLocation;
private double lat;
private double longi;
private Button updateButton;
private TextView locUpdate;
public String url = "http://servername/file.php";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
locationManager =(LocationManager)getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,onLocationChange);
locUpdate = (TextView)findViewById(R.id.locUpdate);
updateButton = (Button)findViewById(R.id.updateButton);
updateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,onLocationChange);
if (latestLocation.getLatitude() != lat && latestLocation.getLongitude() != longi ) {
lat = latestLocation.getLatitude();
longi = latestLocation.getLongitude();
}
String latitude = Double.toString(lat);
String longitude = Double.toString(longi);
url += "?latitude=" + latitude + "&longitude=" + longitude;
locUpdate.setText(latitude + "," + longitude);
getRequest(url);
Toast.makeText(getBaseContext(),
"Location updated : Lat: " + latestLocation.getLatitude() +
" Lng: " + latestLocation.getLongitude(),
Toast.LENGTH_LONG).show();
}
});
}
public void getRequest(String Url) {
// TODO Auto-generated method stub
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
try {
HttpResponse response = client.execute(request);
} catch (Exception ex) {
locUpdate.setText(ex.toString());
}
}
LocationListener onLocationChange = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
latestLocation = location;
if (latestLocation.getLatitude() != lat && latestLocation.getLongitude() != longi ) {
Toast.makeText(getBaseContext(),
"Location updated : Lat: " + latestLocation.getLatitude() +
" Lng: " + latestLocation.getLongitude(),
Toast.LENGTH_LONG).show();
}
}
};
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, onLocationChange);
}
}
This is the php file :
<?php
mysql_connect("localhost","root","");
mysql_select_db("php");
$longitude = $_GET['longitude'];
$latitude = $_GET['latitude'];
if($latitude && $longitude){
$string= "insert into table (latitude, longitude)values('".$latitude."','".$longitude."')";
mysql_query($string);
}
mysql_close();
?>

just change two lines and try it
in android
u have written
if (latestLocation.getLatitude() != lat && latestLocation.getLongitude() != longi )
instead that write
if (latestLocation.getLatitude() != lat || latestLocation.getLongitude() != longi )
AND in php
u have putten
$string= "insert into table (latitude, longitude)values('".$latitude."','".$longitude."')";
instead put
$string= "insert into table (latitude, longitude) values('".$latitude."','".$longitude."')";
try it, i think it'll work

You are updating url on onCreate() method and please check Activity life cycle onCreate() method will call first time when activity is created or activity is re created.
I will suggest you to make a call back mechanism to fetch location data whenever you are creating url for server request.

Related

Implement google map like Uber

I am completely new to android.I am trying to implement a draggable google map like uber app.I have found out a code from somewhere,But when I try running few issues were coming like
Error:(24, 37) error: cannot find symbol class GooglePlayServicesClient
Error:(26, 39) error: cannot find symbol class LocationClient
In my dependencies I have added
compile 'com.google.android.gms:play-services:8.4.0'
Following is the code I have used.
package com.rakyow.taxifinder.taxifinder;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.app.Dialog;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;
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.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnCameraChangeListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity extends Activity implements
ConnectionCallbacks, OnConnectionFailedListener {
// A request to connect to Location Services
private LocationRequest mLocationRequest;
GoogleMap mGoogleMap;
public static String ShopLat;
public static String ShopPlaceId;
public static String ShopLong;
// Stores the current instantiation of the location client in this object
private GoogleApiClient mLocationClient;
boolean mUpdatesRequested = false;
private TextView markerText;
private LatLng center;
private LinearLayout markerLayout;
private Geocoder geocoder;
private List<Address> addresses;
private TextView Address;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.homepage);
markerText = (TextView) findViewById(R.id.locationMarkertext);
Address = (TextView) findViewById(R.id.adressText);
markerLayout = (LinearLayout) findViewById(R.id.locationMarker);
// Getting Google Play availability status
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getBaseContext());
if (status != ConnectionResult.SUCCESS) { // Google Play Services are
// not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
requestCode);
dialog.show();
} else { // Google Play Services are available
// Getting reference to the SupportMapFragment
// Create a new global location parameters object
mLocationRequest = LocationRequest.create();
/*
* Set the update interval
*/
mLocationRequest.setInterval(GData.UPDATE_INTERVAL_IN_MILLISECONDS);
// Use high accuracy
mLocationRequest
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the interval ceiling to one minute
mLocationRequest
.setFastestInterval(GData.FAST_INTERVAL_CEILING_IN_MILLISECONDS);
// Note that location updates are off until the user turns them on
mUpdatesRequested = false;
/*
* Create a new location client, using the enclosing class to handle
* callbacks.
*/
mLocationClient = new GoogleApiClient(this, this, this);
mLocationClient.connect();
}
}
private void stupMap() {
try {
LatLng latLong;
// TODO Auto-generated method stub
mGoogleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// Enabling MyLocation in Google Map
mGoogleMap.setMyLocationEnabled(true);
if (mLocationClient.getLastLocation() != null) {
latLong = new LatLng(mLocationClient.getLastLocation()
.getLatitude(), mLocationClient.getLastLocation()
.getLongitude());
ShopLat = mLocationClient.getLastLocation().getLatitude() + "";
ShopLong = mLocationClient.getLastLocation().getLongitude()
+ "";
} else {
latLong = new LatLng(12.9667, 77.5667);
}
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLong).zoom(19f).tilt(70).build();
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
// Clears all the existing markers
mGoogleMap.clear();
mGoogleMap.setOnCameraChangeListener(new OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition arg0) {
// TODO Auto-generated method stub
center = mGoogleMap.getCameraPosition().target;
markerText.setText(" Set your Location ");
mGoogleMap.clear();
markerLayout.setVisibility(View.VISIBLE);
try {
new GetLocationAsync(center.latitude, center.longitude)
.execute();
} catch (Exception e) {
}
}
});
markerLayout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
LatLng latLng1 = new LatLng(center.latitude,
center.longitude);
Marker m = mGoogleMap.addMarker(new MarkerOptions()
.position(latLng1)
.title(" Set your Location ")
.snippet("")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.add_marker)));
m.setDraggable(true);
markerLayout.setVisibility(View.GONE);
} catch (Exception e) {
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
#Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
stupMap();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onDisconnected() {
// TODO Auto-generated method stub
}
private class GetLocationAsync extends AsyncTask<String, Void, String> {
// boolean duplicateResponse;
double x, y;
StringBuilder str;
public GetLocationAsync(double latitude, double longitude) {
// TODO Auto-generated constructor stub
x = latitude;
y = longitude;
}
#Override
protected void onPreExecute() {
Address.setText(" Getting location ");
}
#Override
protected String doInBackground(String... params) {
try {
geocoder = new Geocoder(MainActivity.this, Locale.ENGLISH);
addresses = geocoder.getFromLocation(x, y, 1);
str = new StringBuilder();
if (geocoder.isPresent()) {
Address returnAddress = addresses.get(0);
String localityString = returnAddress.getLocality();
String city = returnAddress.getCountryName();
String region_code = returnAddress.getCountryCode();
String zipcode = returnAddress.getPostalCode();
str.append(localityString + "");
str.append(city + "" + region_code + "");
str.append(zipcode + "");
} else {
}
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String result) {
try {
Address.setText(addresses.get(0).getAddressLine(0)
+ addresses.get(0).getAddressLine(1) + " ");
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
}
My requirement is something similar to this .
Please help me in solving this issue.Any help would be appreciated.
Thanks in advance
I recommend that you use GoogleApiClient because LocationClient is no longer supported in newer versions of play-services they removed it starting Google Play Services 6.5.87 if I am not mistaken. Here is the link for the example implementation. If you really want to use LocationClient, which I do not recommend, you can use an older version of the play-services
cannot find symbol class GooglePlayServicesClient Error:(
GooglePlayServicesClient was removed. The documentation explicitly says that you should be using GoogleApiClient
Note: If you have an existing app that connects to Google Play
services with a subclass of GooglePlayServicesClient, you should
migrate to GoogleApiClient as soon as possible.
here you can find more about it.
Use GoogleApiClient instead of Location Client.
LocationClient is deprecated. The replacement class is the
GoogleApiClient. It has similar functions so its easy to replace.
Source

How to track the distance when user running/ walking

Im currently doing an apps that can track running distance.
My idea is when i click start, i will record the position that i start running, then when i click stop, it will record the position that i end my running. Then calculate the distance between this 2 point.
I don't know why my distance result keep showing me 0km no matter how i run. Please help me see if gt any problems~
package com.example.ifitness;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.SupportMapFragment;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class calorieburn extends ActionBarActivity implements LocationListener{
private GoogleMap map;
private Location startLocation;
private Location endLocation;
private double latA;
private double longA;
private double latB;
private double longB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calorieburn);
SetupMap();
Button start = (Button) findViewById(R.id.start);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
latA = startLocation.getLatitude();
longA = startLocation.getLongitude();
TextView distance = (TextView) findViewById(R.id.distance);
distance.setText("0 km");
TextView calorie = (TextView) findViewById(R.id.calorie);
calorie.setText("0 cal");
}
});
Button stop = (Button) findViewById(R.id.stop);
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
latB = endLocation.getLatitude();
longB = endLocation.getLongitude();
TextView distance = (TextView) findViewById(R.id.distance);
distance.setText(String.valueOf(distance(latA,longA,latB,longB)+ "km"));
TextView calorie = (TextView) findViewById(R.id.calorie);
calorie.setText(String.valueOf(distance(latA,longA,latB,longB)+ "cal"));
}
});
}
public double calories(double distance){
double calories = 0;
calories = distance * 100;
return calories;
}
public static void distanceBetween(){
}
public double distance(double lat,double lng,double latitude,double longtitude){
Location locA = new Location("locA");
locA.setLatitude(lat);
locA.setLongitude(lng);
Location locB = new Location("locB");
locB.setLatitude(latitude);
locB.setLongitude(longtitude);
double distance = locA.distanceTo(locB);
return distance;
}
private void SetupMap() {
if (map == null){
// Getting reference to the SupportMapFragment of activity_main.xml
SupportMapFragment mf = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// get google map from the fragment
map = mf.getMap();
}
if (map !=null ){
// Enabling MyLocation Layer of Google Map
map.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
String bestprovider = lm.getBestProvider(criteria,false);
String provider = LocationManager.NETWORK_PROVIDER;
if (provider == null){
onProviderDisabled(provider);
}
// Getting Current Location
Location loc = lm.getLastKnownLocation(bestprovider);
if (loc != null){
onLocationChanged(loc);
}
map.setOnMapLongClickListener(onLongClickMapSettings());
}
}
private OnMapLongClickListener onLongClickMapSettings() {
// TODO Auto-generated method stub
return new OnMapLongClickListener(){
#Override
public void onMapLongClick(LatLng arg0) {
// TODO Auto-generated method stub
Log.i(arg0.toString(), "User Long CLicked");
}
};
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
// Getting latitude of the current location
double latitude = location.getLatitude();
// Getting longitude of the current location
double longitude = location.getLongitude();
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Showing the current location in Google Map
map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
map.animateCamera(CameraUpdateFactory.zoomTo(17));
}
private void makeUseOfNewLocation(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
}

Unable to send GPS coordinates to server

I am trying to send GPS coordinates to server got by my app,it is showing GPS coordinates correctly, but unable to send it to server, the problem is in my MainActivity.java
Here is my code
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.NameValuePair;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
int lat,lng;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_location);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
}
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
lat = (int) (location.getLatitude());
lng = (int) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
private class LoadServerASYNC extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return null;
}
void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://182.18.144.140:80"); //your php file path
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("lat", "1.0256"));
nameValuePairs.add(new BasicNameValuePair("lng", "1.0256"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
}
I am not getting what is the problem
You are not initializing and executing the LoadServerAsync anywhere.
If you want to send coordinates every time you update the text views, you should do this:
#Override
public void onLocationChanged(Location location) {
lat = (int) (location.getLatitude());
lng = (int) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
LoadServerASYNC task = new LoadServerASYNC();
task.execute();
}
And you should call postData method inside doInBackground();

Android collect and send data

I am working on application where I need to collect accelerometer and location data & send them over web-server. I have to collect the data on sensor changed event. Right now I am trying to collect it when I click on start button, but somehow I don't see that data getting stored in my file. Could anyone help me with this ?
I have to send this data to MySQL database for processing (on web-server). How will I send the data over to server?
Here is what I have tried right now :
package myapp;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import app.AccelLocData;
import com.google.android.gms.maps.*;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapViewActivity extends Activity implements LocationListener,
SensorEventListener, OnClickListener {
GoogleMap googleMap;
private boolean started = false;
private ArrayList<AccelLocData> sensorData;
private SensorManager sensorManager;
private Button btnStart, btnStop;
private String provider;
// private Button btnUpload;
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorData = new ArrayList<AccelLocData>();
btnStart = (Button) findViewById(R.id.btnStart);
btnStop = (Button) findViewById(R.id.btnStop);
btnStart.setOnClickListener(this);
btnStop.setOnClickListener(this);
btnStart.setEnabled(true);
btnStop.setEnabled(false);
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getBaseContext());
if (status != ConnectionResult.SUCCESS) { // Google Play Services are
// not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
requestCode);
dialog.show();
} else { // Google Play Services are available
googleMap.setOnMapClickListener(new OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Setting the position for the marker
markerOptions.position(latLng);
// Setting the title for the marker.
// This will be displayed on taping the marker
markerOptions.title(latLng.latitude + " : "
+ latLng.longitude);
// Clears the previously touched position
googleMap.clear();
// Animating to the touched position
googleMap.animateCamera(CameraUpdateFactory
.newLatLng(latLng));
// Placing a marker on the touched position
googleMap.addMarker(markerOptions);
}
});
// Enabling MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
}
}
public void onSensorChanged(SensorEvent event) {
if (started) {
double x = event.values[0];
double y = event.values[1];
double z = event.values[2];
long timestamp = System.currentTimeMillis();
LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setPowerRequirement(Criteria.POWER_MEDIUM);
criteria.setAccuracy(Criteria.ACCURACY_FINE);
provider = locManager.getBestProvider(criteria, true);
Location location = locManager.getLastKnownLocation(provider);
double latitude = 0;
double longitude = 0;
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
AccelLocData data = new AccelLocData(timestamp, x, y, z, latitude,
longitude);
// System.out.println("Accel Data:" + data.toString());
// System.out.println("Latitude:" + latitude);
// System.out.println("Longitude:" + longitude);
sensorData.add(data);
}
}
#Override
public void onLocationChanged(Location location) {
TextView tvLocation = (TextView) findViewById(R.id.tv_location);
// Getting latitude of the current location
double latitude = location.getLatitude();
// Getting longitude of the current location
double longitude = location.getLongitude();
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Showing the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
System.out.println("Latitude:" + latitude + ", Longitude:" + longitude);
// Setting latitude and longitude in the TextView tv_location
// tvLocation.setText("Latitude:" + latitude + ", Longitude:" +
// longitude);
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnStart:
btnStart.setEnabled(false);
btnStop.setEnabled(true);
// btnUpload.setEnabled(false);
// sensorData = new ArrayList<AccelLocData>();
// save prev data if available
started = true;
try {
File root = android.os.Environment
.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "/myapp");
dir.mkdirs();
File sensorFile = new File(dir, "acc.txt");
// sensorFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(sensorFile);
ObjectOutputStream myOutWriter = new ObjectOutputStream(fOut);
System.out.println("Sensor data size:"+sensorData.size());
for(int i=0;i<sensorData.size();i++){
System.out.println("Sensor Data:" + sensorData.get(i).getX());
}
myOutWriter.writeObject(sensorData);
myOutWriter.close();
fOut.close();
} catch (Exception e) {
}
Sensor accel = sensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(this, accel,
SensorManager.SENSOR_DELAY_FASTEST);
break;
case R.id.btnStop:
btnStart.setEnabled(true);
btnStop.setEnabled(false);
// btnUpload.setEnabled(true);
started = false;
sensorManager.unregisterListener(this);
// don't need chart
// openChart();
// show data in chart
break;
// case R.id.btnUpload:
// break;
default:
break;
}
}
}
In your activity put this into your OnClick of your Startbutton:
startService(new Intent(this, BackgroundService.class));
and this to your Stopbutton:
stopService(new Intent(this, BackgroundService.class));
Create a new Class for example like the following:
public class BackgroundService extends Service implements LocationListener,
SensorEventListener{
//Hint: there are some methods you need to implement which I forgot to mention but eclipse will add them for you
#Override
public void onCreate() {
//enable networking, look into this: http://www.vogella.com/blog/2012/02/22/android-strictmode-networkonmainthreadexception/
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
//do your data collecting-methods and connect to your webserver
}
#Override
public void onDestroy() {
//unregister your sensor listener
}
}
In this method I got this:
#Override
public void onSensorChanged(SensorEvent event) {
sendValuesToYourServer(Float.toString(event.values[0]) + "," + Float.toString(event.values[1]) +","+ Float.toString(event.values[2]));
}

How to Disable Android LocationListener when application is closed

I have a class which handle a location service called MyLocationManager.java
this is the code :
package com.syariati.childzone;
import java.util.List;
import java.util.Locale;
import android.content.Context;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;
public class MyLocationManager {
private Context context;
private double myLat = 0.0;
private double myLon = 0.0;
private LocationManager locationManager = null;
private Location location = null;
private Criteria criteria;
private String locationName = null;
public MyLocationManager(Context ctx) {
this.context = ctx;
}
private String setCriteria() {
this.criteria = new Criteria();
this.criteria.setAccuracy(Criteria.ACCURACY_FINE);
this.criteria.setAltitudeRequired(false);
this.criteria.setBearingRequired(false);
this.criteria.setCostAllowed(true);
this.criteria.setPowerRequirement(Criteria.POWER_LOW);
return locationManager.getBestProvider(criteria, true);
}
public double getMyLatitude() {
return this.myLat;
}
public double getMyLongitude() {
return this.myLon;
}
public String getLocation() {
return this.locationName;
}
public void onLocationUpdate() {
locationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
String provider = setCriteria();
location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
locationManager.requestLocationUpdates(provider, 1000, 0,
new MyLocationListener());
}
private void updateWithNewLocation(Location location) {
if (location != null) {
this.myLat = location.getLatitude();
this.myLon = location.getLongitude();
// Toast.makeText(this.context,
// "Lokasi Anda:\n" + this.myLat + "\n" + this.myLon,
// Toast.LENGTH_LONG).show();
getLocationName(this.myLat, this.myLon);
} else {
Toast.makeText(this.context, "Lokasi Anda Tidak Diketahui",
Toast.LENGTH_SHORT).show();
}
}
private void getLocationName(double lat, double lon) {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
try {
List<Address> adresses = geocoder.getFromLocation(lat, lon, 1);
StringBuilder sb = new StringBuilder();
if (adresses.size() > 0) {
Address address = adresses.get(0);
for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
sb.append(address.getAddressLine(i)).append("\n");
sb.append(address.getCountryName()).append("\n");
}
this.locationName = sb.toString();
// Toast.makeText(context, sb.toString(), Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location newLocation) {
// TODO Auto-generated method stub
myLat = newLocation.getLatitude();
myLon = newLocation.getLongitude();
getLocationName(myLat, myLon);
Toast.makeText(context,
"Lokasi terupdate\nLat: " + myLat + "\nLon: " + myLon,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
}
which has an Inner class that implements location listener on it. So far, it works. It listen the location with no problem. However, when I exit my apps, it doesn't completely stop the listen the location. As you see from this code :
#Override
public void onLocationChanged(Location newLocation) {
// TODO Auto-generated method stub
myLat = newLocation.getLatitude();
myLon = newLocation.getLongitude();
getLocationName(myLat, myLon);
Toast.makeText(context,
"Lokasi terupdate\nLat: " + myLat + "\nLon: " + myLon,
Toast.LENGTH_SHORT).show();
}
while the location is updated, the toast will be shown, and it still appear when the location is updated. Even when I've closed the application.
How to stop the location listener completely in my case.
This one helped me to stop the updat :
android how to stop gps
You may call removeUpdates on your LocationManager.
public void removeUpdates (PendingIntent intent)
Removes any current registration for location updates of the current
activity with the given PendingIntent. Following this call, updates
will no longer occur for this intent.
Parameters:
intent {#link PendingIntent} object that no longer needs location
updates
Throws:
IllegalArgumentException if intent is null
See here: http://developer.android.com/reference/android/location/LocationManager.html#removeUpdates(android.app.PendingIntent)
Updated:
In this case, you may change this line:
locationManager.requestLocationUpdates(provider, 1000, 0,
new MyLocationListener());
to:
MyLocationListener myLL = new MyLocationListener();
locationManager.requestLocationUpdates(provider, 1000, 0,
myLL);
When you want to remove your listener call as below:
locationManager.removeUpdates(myLL);

Categories

Resources