onLocationChanged() is not getting executed in my service - android

i'm trying to automatically update my location and have some other part of cloud related code working when location is changed. here is the code of my service:
package com.salesforce.samples.templateapp;
import java.util.HashMap;
import org.json.JSONArray;
import com.salesforce.androidsdk.app.ForceApp;
import com.salesforce.androidsdk.rest.RestClient;
import com.salesforce.androidsdk.rest.RestRequest;
import com.salesforce.androidsdk.rest.RestResponse;
import com.salesforce.androidsdk.rest.RestClient.AsyncRequestCallback;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Criteria;
import android.location.GpsStatus.Listener;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class MyServices extends Service {
RestClient client;
double plat;
double plong;
int Two_Min=2*60*1000;
// TextView infoText;
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Location Updation has started", Toast.LENGTH_LONG)
.show();
Log.v("X","Response:in onStartCommand()");
//Intent in = new Intent().setClass(MyServices.this, GPSUpdate.class);
//in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//startActivity(in);
detectLocation();
return START_STICKY;
}
private void detectLocation() {
// TODO Auto-generated method stub
Toast.makeText(this, "Inside detectlocation()", Toast.LENGTH_SHORT)
.show();
LocationManager lm1 = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener ll1 = new MyLocationListetner();
Criteria crit = new Criteria();
crit.setAccuracy(Criteria.ACCURACY_FINE);
String best = lm1.getBestProvider(crit, false);
// lm1.requestLocationUpdates(best, 0, 1, ll1);
Log.v("X",
"Response:After creating lm and ll ");
// boolean b1=lm1.addGpsStatusListener((Listener) ll1);
//Log.v("X",
// "Response: "+b1);
lm1.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll1);
Log.v("X",
"Response:After lm1.requestLocationUpdates ");
/*Location loc = null;
loc.getLatitude();
loc.getLongitude();
Log.v("X","Response:"+loc);
ll1.onLocationChanged(loc);*/
}
class MyLocationListetner implements LocationListener {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Log.d("X","Response:inside onLocationChanged ");
Toast.makeText(getApplicationContext(), "inside onLocationChanged()", Toast.LENGTH_LONG).show();
//Log.v("X","Response:"+location);
if (location != null) {
plat = location.getLatitude();
plong = location.getLongitude();
Log.d("X",
"Response:Location " + Double.toString(plat)+Double.toString(plong));
String objectType = "akshayg__User__c";
String objectId = "a02900000089fK3";
HashMap<String, Object> fields = new HashMap<String, Object>();
fields.put("Name", "Ashish");
// fields.put("akshayg__Donor_Location__Latitude__s",
// Double.toString(plat));
// fields.put("akshayg__Donor_Location__Longitude__s",
// Double.toString(plong));
RestRequest request = null;
try {
request = RestRequest.getRequestForUpdate(
getString(R.string.api_version), objectType,
objectId, fields);
// Toast.makeText(this, "Location Updation has started",
// Toast.LENGTH_LONG).show();
} catch (Exception e) {
// printHeader("Could not build update request");
printException(e);
return;
}
client.sendAsync(request, new AsyncRequestCallback() {
#Override
public void onSuccess(RestRequest request,
RestResponse result) {
// Toast.makeText(this,
// ""+Double.toString(plat)+","+Double.toString(plong),
// Toast.LENGTH_LONG).show();
try {
//Toast.makeText(this, "Location Updated",Toast.LENGTH_LONG).show();
Log.v("X",
"Response:inside onSuccess() " + result.toString());
/*JSONArray records = result.asJSONObject()
.getJSONArray("records");
for (int i = 0; i < records.length(); i++) {
// listAdapter.add(records.getJSONObject(i).getString("Name"));
// listAdapter.add(records.getJSONObject(i).getString("akshayg__Phone_Number__c"));
// listAdapter.add(records.getJSONObject(i).getString("akshayg__Donor_Location__Latitude__s"));
// listAdapter.add(records.getJSONObject(i).getString("akshayg__Donor_Location__Longitude__s"));
}
*/
}
catch (Exception e) {
onError(e);
}
}
#Override
public void onError(Exception exception) {
Log.v("X",
"Response: " + exception.toString());
// Toast.makeText(MainActivity.this,
// MainActivity.this.getString(ForceApp.APP.getSalesforceR().stringGenericError(),
// exception.toString()),
// Toast.LENGTH_LONG).show();
}
});
}
}
private void printException(Exception e) {
String err = "Error: " + e.getClass().getSimpleName();
Toast.makeText(getApplicationContext(), err, Toast.LENGTH_LONG)
.show();
}
#Override
public void onProviderDisabled(String provider) {
// 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
}
}
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Location Updation has stoped", Toast.LENGTH_LONG)
.show();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
the toasts till "inside detectLocation" are popped up and log entries made till
04-04 00:42:34.687: V/X(10217): Response:After lm1.requestLocationUpdates
but beyond that the code is just unreachable...
even the GPS sign is shown in action bar but the toast for displaying location is not popped... pls help....!!!

In requestLocationUpdates(LocationManager.GPS_PROVIDER, 10, Two_Min, ll1) you're passing Two_Min (which you've set to 5*60*1000 = 300000) into the minDistance paramter which should be a number of metres. Try setting minDistance to 0 instead.

Related

Service to send GPS coordinates to server

I'm new in android and I am trying to send gps coordinates to a web server. I already get the GPS coord and request updates of them every X seconds.
What I want is to send those coords to a web server using a Service and running the service in different time intervals (user will decide how ofter he wants to update his position).
I have already searched and I want to do it the more efficient possible, that's why I think using a Service would be the best approach.
I'm having trouble knowing where to start the service and how to make it run in time intervals, also if I should use AsyncTask inside the service to POST the coords to the webserver.
Any hint would be appreciated.
Thanks!
Use an AlarmManager that starts a service every X sec.
The service should include a class that implements a location listener.
Refer this tutorial link that will helps you to know about the service and time intervals.
And you simply get the coordinates within an activity from the service and send it to the server using Async task.
Hope it will helps you.
You can do it without using AlarmManager.
I used onLocationChanged() from LocationManager
LocServ.java
import android.app.IntentService;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.SystemClock;
import android.util.Log;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
/**
* Created by BrijD on 14-12-22.
*/
public class LocServ extends Service implements LocationListener {
private static String url_insert_location = "http://172.20.10.4/testing/insert.php";
public static String LOG = "Log";
JSONParser jsonParser = new JSONParser();
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 = 0; // 0 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 ; // 1 second
// Declaring a Location Manager
protected LocationManager locationManager;
public LocServ(Context context){
this.mContext = context;
}
public LocServ(){
super();
mContext = LocServ.this;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
Log.i(LOG, "Service started");
Log.i("asd", "This is sparta");
new SendToServer().execute(Double.toString(getLocation().getLongitude()),Double.toString(getLocation().getLatitude()));
return START_STICKY;
}
#Override
public void onCreate() {
super.onCreate();
Log.i(LOG, "Service created");
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(LOG, "Service destroyed");
}
class SendToServer extends AsyncTask<String,String,String> {
#Override
protected String doInBackground(String... la ) {
try {
Log.i("string" , la[0]);
String longi = la[0];
String lati = la[1];
// Building Parameters
Log.d("value", lati);
Log.d("value", longi);
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("longitude", longi));
params.add(new BasicNameValuePair("latitude", lati));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_insert_location, "POST", params);
Log.d("Create Response", json.toString());
} catch (Exception e) {
Log.i("error", e.toString());
}
return "call";
}
}
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) {
//updates will be send according to these arguments
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;
}
#Override
public void onLocationChanged(Location location) {
//this will be called every second
new SendToServer().execute(Double.toString(getLocation().getLongitude()),Double.toString(getLocation().getLatitude()));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
Use below service related code to achieve your requirement
where in onTick() method you can write your code to send data(GPS cordinate) from your device to web server even you can write your GPS related code here in this service(getting gps cordinate )
TimerService.java
package com.android.yourpackagename;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.CountDownTimer;
import android.os.IBinder;
public class TimerService extends Service {
// variables
MyCounter timer;
#Override
public void onCreate() {
timer = new MyCounter(30 * 60 * 1000, 1000);//counter of 30minutes and tick interval is //1 second(i.e.1000) you can increase its limit whatever you want as per your requirement
super.onCreate();
timer.start();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
private class MyCounter extends CountDownTimer {
public MyCounter(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#SuppressWarnings("static-access")
#Override
public void onFinish() {
//timer finished 30 minutes
stopSelf()//to stop service after counter stop
}
#Override
public void onTick(long millisUntilFinished) {
//timer clock tick event after each 1 second
}
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
timer.cancel();
super.onDestroy();
// call start servce here for lifetime running of service
// startService(new Intent(this, TimerService.class));
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
register your TimerService.java into manifest using below code
<service
android:name="com.android.yourpackagename.TimerService"
android:process=":TimerService" >
</service>
start service from your activity using startService() method like
startService(new Intent(getApplicationContext(), TimerService.class));
stop service using stopService() method like
stopService(new Intent(getApplicationContext(),
TimerService.class));
Hope this will help you cause it worked for me with same requirement :)
i think you should use the volley library instead of asynchronous task
this link explain the difference
and this's a method that can help you understand how to use it :
public static void postLatAndLongAndId(final Context context,String id,String imei,String latitude,String longitude) {
// Tag used to cancel the request
String tag_string_req = "req_login";
// progress bar showing
pDialog.setMessage("votre reservation est en cours de traitement ...");
showDialog();
//create jsonObject to post it
final JSONObject body = new JSONObject();
try {
body.put("id_client",id );
body.put("imei",imei);
body.put("lat",latitude);
body.put("long",longitude);
body.put("type","b2c");
// Log.e(TAG, "jsonObj body: " + body );
} catch (JSONException e) {
e.printStackTrace();
}
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_POSTING_USER_COORDINATES, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Log.e(TAG, "WebS Response: " + response.toString());
try {
JSONObject jObj = new JSONObject(response);
// Log.e(TAG, "affichage de jobj =: " + jObj );
String status = jObj.getString("status");
// Log.e(TAG, "status = ok ?? " + status.equals("OK") );
// Check for error node in json
if (status.equals("OK")){
//data send successfully
hideDialog();
} else {
// Error . Get the error message
String errorMsg = jObj.getString("message");
// Log.e(TAG, "webS Error: "+errorMsg);
Toast.makeText(context,
errorMsg, Toast.LENGTH_LONG).show();
hideDialog();
alert.showAlertDialog(context, "Désolé", " Une erreur est survenue, veuillez essayer ultérieurement",true);
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Log.e(TAG, "webS Error: " + error.getMessage());
Toast.makeText(context,
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
alert.showAlertDialog(context, "Désolé", " Une erreur est survenue, veuillez essayer ultérieurement",true);
}
}) {
#Override
public byte[] getBody() throws AuthFailureError {
// Log.e(TAG, "j'ai executé la methode getBody!! ");
return body.toString().getBytes();
}
#Override
public String getBodyContentType()
{
return "application/json";
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
hope it help :)
Alaram service or timer is good approach to perform time dependant tasks, but its best to use handler with post dalyed of your choice to perform any task you want, if you are using alarm manager than you are requesting OS to perform your task after some time, same with timer but for handlers you are using/managing in your own code

Using AsyncTask to get location information

I'm trying to get user's current location coordinates and address using reverse geocoding.
As This process takes some time, I want to show a progress bar during that time, so I'm using AsyncTask. So, what basically I'm doing is, from one activity's onClick event I start the AsyncTask which finds me the location informations and then from that AsyncTask I start another activity which uses that Information.
This is my First Activity where onClick event starts the AsyncTask:
public void onClickGirl(View view)
{
(new MyAsyncTask(MainActivity.this)).execute();
}
This is the AsyncTask:
public class MyAsyncTask extends AsyncTask<Void, Void, Void> implements LocationListener {
private Context ContextAsync;
public MyAsyncTask (Context context){
this.ContextAsync = context.getApplicationContext();
}
Dialog progress;
private String providerAsync;
private LocationManager locationManagerAsync;
double latAsync=0.0;
double lonAsync=0.0;
String thikanaAsync="Scan sms for location";
String AddressAsync="";
Geocoder GeocoderAsync;
#Override
protected void onPreExecute() {
super.onPreExecute();
progress = ProgressDialog.show(null, "Loading data", "Please wait...");
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
locationManagerAsync = (LocationManager) ContextAsync.getSystemService(ContextAsync.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setCostAllowed(false);
criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
providerAsync = locationManagerAsync.getBestProvider(criteria, false);
if (locationManagerAsync.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
providerAsync = LocationManager.GPS_PROVIDER;
} else if (locationManagerAsync.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
providerAsync = LocationManager.NETWORK_PROVIDER;
/*AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("GPS is disabled in the settings!");
alert.setMessage("It is recomended that you turn on your device's GPS and restart the app so the app can determine your location more accurately!");
alert.setPositiveButton("OK", null);
alert.show();*/
} else if (locationManagerAsync.isProviderEnabled(LocationManager.PASSIVE_PROVIDER)) {
providerAsync = LocationManager.PASSIVE_PROVIDER;
Toast.makeText(ContextAsync, "Switch On Data Connection!!!!", Toast.LENGTH_LONG).show();
}
Location location = locationManagerAsync.getLastKnownLocation(providerAsync);
// Initialize the location fields
if (location != null) {
// System.out.println("Provider " + provider + " has been selected.");
latAsync = location.getLatitude();
lonAsync = location.getLongitude();
onLocationChanged(location);
} else {
Toast.makeText(ContextAsync, " Locationnot available", Toast.LENGTH_SHORT).show();
}
List<Address> addresses = null;
GeocoderAsync = new Geocoder(ContextAsync, Locale.getDefault());
try {
addresses = GeocoderAsync.getFromLocation(latAsync, lonAsync, 1);
String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getAddressLine(1);
String country = addresses.get(0).getCountryName();
AddressAsync = Html.fromHtml(
address + ", " + city + ",<br>" + country).toString();
} catch (Exception e) {
e.printStackTrace();
AddressAsync = "Refresh for the address";
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
progress.dismiss();
Intent intentAsync = new Intent(ContextAsync,Emerg.class);
intentAsync.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intentAsync.putExtra("calculated_Lat", latAsync);
intentAsync.putExtra("calculated_Lon", lonAsync);
intentAsync.putExtra("calculated_address", AddressAsync);
ContextAsync.startActivity(intentAsync);
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
locationManagerAsync.requestLocationUpdates(providerAsync, 0, 0, this);
}
#Override
public void onProviderDisabled(String provider) {
// 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
}
}
This is the Second Activity which run after AsyncTask:`
Intent ixx = getIntent();
elat = Double.parseDouble(ixx.getStringExtra("calculated_Lat"));
elon = Double.parseDouble(ixx.getStringExtra("calculated_Lon"));
eAddress1 = ixx.getStringExtra("calculated_address");
And This is the LogCat:
02-01 17:15:26.734: E/AndroidRuntime(2587): java.lang.IllegalStateException: Could not execute method of the activity
02-01 17:15:26.734: E/AndroidRuntime(2587): at android.view.View$1.onClick(View.java:3814)
02-01 17:15:26.734: E/AndroidRuntime(2587): at android.view.View.performClick(View.java:4424)
02-01 17:15:26.734: E/AndroidRuntime(2587): at android.os.Handler.handleCallback(Handler.java:733)
02-01 17:15:26.734: E/AndroidRuntime(2587): at android.os.Handler.dispatchMessage(Handler.java:95)
02-01 17:15:26.734: E/AndroidRuntime(2587): at android.os.Looper.loop(Looper.java:137)
I have spent hours after this but can't find the problem. Can anyone please help me finding out what I'm missing??
Please find the updated code and test it at your end and let me know in case you have any query:
package com.example.tabhost;
import java.util.List;
import java.util.Locale;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
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.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
public class MyAsyncTask extends AsyncTask<Void, Void, Void> implements LocationListener {
private Context ContextAsync;
public MyAsyncTask (Context context){
this.ContextAsync = context;
}
Dialog progress;
private String providerAsync;
private LocationManager locationManagerAsync;
double latAsync=0.0;
double lonAsync=0.0;
String thikanaAsync="Scan sms for location";
String AddressAsync="";
Geocoder GeocoderAsync;
Location location;
#Override
protected void onPreExecute() {
super.onPreExecute();
progress = ProgressDialog.show(ContextAsync, "Loading data", "Please wait...");
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
locationManagerAsync = (LocationManager) ContextAsync.getSystemService(ContextAsync.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setCostAllowed(false);
criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
providerAsync = locationManagerAsync.getBestProvider(criteria, false);
if (locationManagerAsync.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
providerAsync = LocationManager.GPS_PROVIDER;
} else if (locationManagerAsync.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
providerAsync = LocationManager.NETWORK_PROVIDER;
/*AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("GPS is disabled in the settings!");
alert.setMessage("It is recomended that you turn on your device's GPS and restart the app so the app can determine your location more accurately!");
alert.setPositiveButton("OK", null);
alert.show();*/
} else if (locationManagerAsync.isProviderEnabled(LocationManager.PASSIVE_PROVIDER)) {
providerAsync = LocationManager.PASSIVE_PROVIDER;
//Toast.makeText(ContextAsync, "Switch On Data Connection!!!!", Toast.LENGTH_LONG).show();
}
location = locationManagerAsync.getLastKnownLocation(providerAsync);
// Initialize the location fields
if (location != null) {
// System.out.println("Provider " + provider + " has been selected.");
latAsync = location.getLatitude();
lonAsync = location.getLongitude();
} else {
//Toast.makeText(ContextAsync, " Locationnot available", Toast.LENGTH_SHORT).show();
}
List<Address> addresses = null;
GeocoderAsync = new Geocoder(ContextAsync, Locale.getDefault());
try {
addresses = GeocoderAsync.getFromLocation(latAsync, lonAsync, 1);
String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getAddressLine(1);
String country = addresses.get(0).getCountryName();
AddressAsync = Html.fromHtml(
address + ", " + city + ",<br>" + country).toString();
} catch (Exception e) {
e.printStackTrace();
AddressAsync = "Refresh for the address";
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
progress.dismiss();
onLocationChanged(location);
Log.v("latAsync_lonAsync",latAsync+"_"+lonAsync);
Intent intentAsync = new Intent(ContextAsync,Emerg.class);
intentAsync.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intentAsync.putExtra("calculated_Lat", latAsync);
intentAsync.putExtra("calculated_Lon", lonAsync);
intentAsync.putExtra("calculated_address", AddressAsync);
ContextAsync.startActivity(intentAsync);
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
locationManagerAsync.requestLocationUpdates(providerAsync, 0, 0, this);
}
#Override
public void onProviderDisabled(String provider) {
// 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
}
}
instead of using this.ContextAsync = context.getApplicationContext();
ContextAsync should have Activity instance, no ApplicationContext so use this.ContextAsync = context

Method onLocationChanged() is not getting a different location

package com.example.pointkeeper;
import java.util.ArrayList;
import android.app.Service;
import android.content.Context;
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.IBinder;
import android.util
public class ServicePointKeeper extends Service implements LocationListener{
double latitude;
double longitude;
private LocationManager lm;
ArrayList<Point> pt;
Point p;
private Context context;
private Location loc;
private final static long TEMPO_DE_ATUALIZACAO = 1 * 60 * 1000 ;
private final static float DISTANCIA_DE_ATUALIZACAO = 1 ;
public void setGPS(){
Criteria criteria = new Criteria();
criteria.setAccuracy( Criteria.ACCURACY_FINE );
criteria.setAltitudeRequired(true);
String provider = lm.getBestProvider(criteria, true);
if ( provider == null ) {
Log.d("SistemaGPS.ativar", "Nenhum provedor encontrado.");
} else {
Log.d("SistemaGPS.ativar", "Provedor utilizado: " + provider);
//lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, TEMPO_DE_ATUALIZACAO, DISTANCIA_DE_ATUALIZACAO , this);
lm.requestLocationUpdates(provider, TEMPO_DE_ATUALIZACAO, DISTANCIA_DE_ATUALIZACAO , this);
}
}
public void updateList(){
p.setLatitude(loc.getLatitude());
p.setLongitude(loc.getLongitude());
pt.add(p);
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
loc = location;
Toast.makeText(getApplicationContext(), "Lat: " + loc.getLatitude() + "Long: " + loc.getLongitude(), Toast.LENGTH_LONG).show();
updateList();
}
#Override
public void onProviderDisabled(String provider) {
// 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 int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "Serviço iniciado", Toast.LENGTH_SHORT).show();
this.loc = null;
pt = new ArrayList<Point>();
p = new Point();
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
setGPS();
Toast.makeText(getBaseContext(), "GPS setado", Toast.LENGTH_SHORT).show();
return START_STICKY;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Serviço parado", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "Lat: " + latitude + "Long: " + longitude, Toast.LENGTH_SHORT).show();
Intent it = new Intent(getApplicationContext(), ShowPoints.class);
it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Bundle b = new Bundle();
b.putParcelableArrayList("points", pt);
it.putExtras(b);
startActivity(it);
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
So, in this code, my intention is to save a list of Points in an ArrayList of Points that will be use later. But all the points (latitude and longitude) have the same value, once i have the first value, all the others values are the same, its seems like onLocationChanged is never called.
Can someone help me?
You have a global point p that you're overwriting every call to updateList. Since you aren't creating a new point ever, this overwrites the old values. That means every element in your list will always have the most recent values, rather than the value at that time.
Also, why are you using class variables everywhere rather than passing parameters to functions? I have a feeling you don't understand Java or references very well.
Edit:
Here's what your code should look like, with locals used correctly:
package com.example.pointkeeper;
import java.util.ArrayList;
import android.app.Service;
import android.content.Context;
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.IBinder;
import android.util
public class ServicePointKeeper extends Service implements LocationListener{
private LocationManager lm;
ArrayList<Point> pt;
private final static long TEMPO_DE_ATUALIZACAO = 1 * 60 * 1000 ;
private final static float DISTANCIA_DE_ATUALIZACAO = 1 ;
public void setGPS(){
Criteria criteria = new Criteria();
criteria.setAccuracy( Criteria.ACCURACY_FINE );
criteria.setAltitudeRequired(true);
String provider = lm.getBestProvider(criteria, true);
if ( provider == null ) {
Log.d("SistemaGPS.ativar", "Nenhum provedor encontrado.");
} else {
Log.d("SistemaGPS.ativar", "Provedor utilizado: " + provider);
//lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, TEMPO_DE_ATUALIZACAO, DISTANCIA_DE_ATUALIZACAO , this);
lm.requestLocationUpdates(provider, TEMPO_DE_ATUALIZACAO, DISTANCIA_DE_ATUALIZACAO , this);
}
}
public void updateList(Location loc){
Point p = new Point();
p.setLatitude(loc.getLatitude());
p.setLongitude(loc.getLongitude());
pt.add(p);
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Lat: " + location.getLatitude() + "Long: " + location.getLongitude(), Toast.LENGTH_LONG).show();
updateList(location);
}
#Override
public void onProviderDisabled(String provider) {
// 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 int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "Serviço iniciado", Toast.LENGTH_SHORT).show();
pt = new ArrayList<Point>();
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
setGPS();
Toast.makeText(getBaseContext(), "GPS setado", Toast.LENGTH_SHORT).show();
return START_STICKY;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Serviço parado", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "Lat: " + latitude + "Long: " + longitude, Toast.LENGTH_SHORT).show();
Intent it = new Intent(getApplicationContext(), ShowPoints.class);
it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Bundle b = new Bundle();
b.putParcelableArrayList("points", pt);
it.putExtras(b);
startActivity(it);
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}

Can't compare database latitude and longitude with current location

So I am trying to get current latitude and longitude and comparing it with the data I stored in my database using cursor...but when I am trying to run this app on my cell then its getting force close after some time..don't know why what the reason is....
Here's the code for getting current location and comparing it with database
package com.example.alert;
import java.util.ArrayList;
import java.util.List;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Toast;
public class service extends Service{
LocationManager lm;
DatabaseHelper db=new DatabaseHelper(this);
List<String> arlist=new ArrayList<String>();
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public void onCreate() {
LocationManager lm=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener ll=new MyLocationListener();
//lm.requestLocationUpdates( LocationManager.GPS_PROVIDER, 5*60*10000, 0, ll);
lm.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, ll);
Toast.makeText(this, "Background Service Created", Toast.LENGTH_LONG).show();
}
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
}
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
// Intent myIntent=new Intent(service.this,CurrentLocation.class);
}
/* Class My Location Listener */
public class MyLocationListener implements LocationListener
{
public void onLocationChanged(Location loc)
{
if(loc!=null)
{
double x;
SQLiteDatabase y = db.getWritableDatabase();
String Text = "My current location is: " +"Latitud = " + loc.getLatitude() +"Longitud = " + loc.getLongitude();
Toast.makeText( getApplicationContext(),Text,Toast.LENGTH_SHORT).show();
// String t=loc.getLatitude().toString();
Cursor cr=null;
cr=y.rawQuery("SELECT LATITUDE FROM"+ "data",null);
cr.moveToFirst();
while(cr.moveToNext()) {
arlist.add(cr.getString(cr.getColumnIndex("Latitude")));
}
for(int i=0;i<arlist.size();i++){
if(arlist.get(i)==Double.toString(loc.getLatitude())){
Intent myIntent=new Intent(service.this,SilVib.class);
startActivity(myIntent);
}
}
/* cr.moveToFirst();
while(!cr.isAfterLast()) {
al.add(cr.getString(cr.getColumnIndex(dbAdapter.KEY_NAME))); //add the item
cr.moveToNext();
}*/
// lm.addProximityAlert(loc.getLatitude(), loc.getLongitude(), 10009,, intent)
//for loop, alerters retrieving one by one
// x= calcDistance(loc.getLatitude(),loc.getLongitude(),z,y);
// if(x<1){
// Intent myIntent = new Intent(ViewAlerters.this,CallMode.class);
// startActivity(myIntent);
}
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText( getApplicationContext(),"Gps Disabled - #From :Alert Me",Toast.LENGTH_SHORT ).show();
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText( getApplicationContext(),"Gps Enabled - #From :Alert Me",Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
/* public double calcDistance(double latA, double longA, double latB, double longB) {
double theDistance = (Math.sin(Math.toRadians(latA)) * Math.sin(Math.toRadians(latB)) + Math.cos(Math.toRadians(latA)) * Math.cos(Math.toRadians(latB)) * Math.cos(Math.toRadians(longA - longB)));
return new Double((Math.toDegrees(Math.acos(theDistance))) * 69.09*1.6093);
}
*/
}

setTestProviderLocation does not trigger onLocationChanged in the service test case

I have small service implementing LocationListener. I tested it manually with my application and it works properly.
I wrote also a test case for the service.
I used setTestProviderLocation expecting that service will receive location update.
However, it does not happen.
Does anybody know what's a problem? I'd like to emphasize that the same service works in real application.
Test case is added below
package com.gkatz.android.mtg.test;
import java.util.List;
import com.gkatz.android.mtg.LocationService;
import com.gkatz.android.mtg.LocationService.LocationBinder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.os.IBinder;
import android.os.SystemClock;
import android.test.ServiceTestCase;
public class LocationServiceTest extends ServiceTestCase<LocationService> implements LocationListener{
public LocationServiceTest() {
super(LocationService.class);
// TODO Auto-generated constructor stub
}
#Override
protected void setUp() throws Exception {
// TODO Auto-generated method stub
super.setUp();
}
public void testBinding(){
IBinder locationBinder;
locationBinder = getServiceBinder();
assertNotNull(locationBinder);
}
public void testStart(){
Intent locationIntent = new Intent(getContext(), LocationService.class);
startService(locationIntent);
}
public void testNoStart(){
LocationService locationService = getService();
assertNull(locationService);
}
public void testLocationUpdate() throws InterruptedException{
LocationBinder locationBinder;
LocationService locationService;
Context context = getContext();
LocationManager lm = getLocationManager();
context.registerReceiver(locationReceiver,
new IntentFilter("android.mtg.custom.intent.action.GPS_LOCATION"));
locationBinder = (LocationBinder)getServiceBinder();
assertNotNull(locationBinder);
locationService = getService();
assertNotNull(locationService);
Location loc = new Location(LocationManager.GPS_PROVIDER);
loc.setLongitude(4.890935);
loc.setLatitude(52.373801);
loc.setTime(System.currentTimeMillis());
lm.setTestProviderLocation(LocationManager.GPS_PROVIDER, loc);
SystemClock.sleep(3000);
loc.setLongitude(35.2276757);
loc.setLatitude(31.7765488);
loc.setTime(System.currentTimeMillis());
lm.setTestProviderLocation(LocationManager.GPS_PROVIDER, loc);
synchronized (this) {
this.wait(2000);
}
Location lastLoc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
System.out.println("Last known longitude: " + Double.toString(lastLoc.getLongitude()) +
"Last known latitude: " + Double.toString(lastLoc.getLatitude()));
assertEquals(35.2276757, locationService.getLongitude());
assertEquals(31.7765488, locationService.getLatitude());
context.unregisterReceiver(locationReceiver);
lm.removeTestProvider(LocationManager.GPS_PROVIDER);
}
private BroadcastReceiver locationReceiver=new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
assertTrue(intent.getAction().equals("android.mtg.custom.intent.action.GPS_LOCATION"));
System.out.println("Action received: " + intent.getAction());
this.notify();
}
};
private IBinder getServiceBinder(){
Intent locationIntent = new Intent(getContext(), LocationService.class);
return bindService(locationIntent);
}
private LocationManager getLocationManager(){
LocationManager lm = (LocationManager)
getContext().getSystemService(Context.LOCATION_SERVICE);
lm.addTestProvider(LocationManager.GPS_PROVIDER,
true, true, true, true, true, true, true,
Criteria.POWER_LOW, Criteria.ACCURACY_FINE);
lm.setTestProviderStatus(LocationManager.GPS_PROVIDER,
LocationProvider.AVAILABLE, null, System.currentTimeMillis());
lm.setTestProviderEnabled(LocationManager.GPS_PROVIDER, true);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,this);
return lm;
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
System.out.println("LocationServiceTest, onLocationChanged, lon:" +
Double.toString(location.getLongitude()) + ", lat:" +
Double.toString(location.getLatitude()));
}
#Override
public void onProviderDisabled(String provider) {
// 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
}
}
Try with
// Register the listener with the Location Manager to receive location updates
lm.requestLocationUpdates("YOUR PROVIDER", 0, 0, YOUR_LOCATION_LISTENER);
Found at Location guide of Android Developers

Categories

Resources