I am working on a simple GeoFence Service. I am not using the GeofencingApi because I am working with a jni bridge and making the library available would be to much overhead for my project.
So my Problem now is, that the LocationManager is not removing Updates after I am calling removeUpdates. I don't understand why. My code is as follows:
public class GeoFenceService extends Service {
public GeoFenceService() { Log.v("GeoFenceService","GeoFenceService init"); }
public static LocationManager mlocManager;
public static LocationListener mlocListener;
public void updateLocationAndCheckGeoFences() {
Log.d("GeoFenceService","Updating Location");
GeoFenceService.mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
GeoFenceService.mlocListener = new MyLocationListener();
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
String bestProvider = GeoFenceService.mlocManager.getBestProvider(criteria, true);
GeoFenceService.mlocManager.requestLocationUpdates(bestProvider, 0, 0, GeoFenceService.mlocListener);
//Location loc = mlocManager.getLastKnownLocation(bestProvider);
//checkGeoFences4(loc);
}
public void checkGeoFences4(Location locCurrent) {
Log.d("GeoFenceService","Checking GeoFence for Location:"
+locCurrent.getLatitude()+"/"+locCurrent.getLongitude());
for (Voucher voucher : listVouchers) {
Location locVoucher = new Location("Voucher");
locVoucher.setLatitude(voucher.dblLat);
locVoucher.setLongitude(voucher.dblLon);
float distance = locCurrent.distanceTo(locVoucher);
Log.d("GeoFenceService","\tGeoFence for Voucher"+voucher.strText+" Distance:"+distance);
if (distance < voucher.dblRadius) {
showNotification(voucher.strText,voucher.intEntryId);
}
}
}
public class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location loc)
{
try {
checkGeoFences4(loc);
try {
GeoFenceService.mlocManager.removeUpdates(GeoFenceService.mlocListener);
Log.d("GeoFenceService","Location Update suspended");
} catch(Exception e) {
Log.e("GeoFenceService","Failed to suspend Location Update"+e.getMessage());
}
} catch (Exception e) { }
}
#Override
public void onProviderDisabled(String provider)
{
}
#Override
public void onProviderEnabled(String provider)
{
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
//Stuff for class GeoFenceService (simplyfied)
private final int UPDATE_INTERVAL = 15 * 60 * 1000;
private Timer timer = new Timer();
public void onCreate() { Log.d("GeoFenceService","GeoFenceService created"); }
public void onDestroy() { if (timer != null) { timer.cancel(); } }
public int onStartCommand(Intent intent, int flags, int startid) {
Log.d("GeoFenceService","GeoFenceService started");
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
updateLocationAndCheckGeoFences();
}
}, 0, UPDATE_INTERVAL);
return START_STICKY;
}
}
While updateLocationAndCheckGeoFences is succesfully starting the Location Updates removing them is not working.
The Log continuely logging:
D/GeoFenceService( 9953): Checking GeoFence for Location:♣♣.♣♣♣♣♣♣♣♣♣♣♣♣♣♣/♣♣.♣♣♣♣♣♣♣♣♣♣♣♣♣♣
D/GeoFenceService( 9953): GeoFence for VoucherRestaurant ♣♣♣♣: GUTSCHEIN jetzt einlösen Distance:315341.0
D/GeoFenceService( 9953): Location Update suspended
I hope someone can help me,
thanks in advance
Related
I need to get the user current location using gps in certain time interval even after closing the application. i have done using service.
here is my service class.
public class MyService extends Service {
private static final String TAG = "BOOMBOOMTESTGPS";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 1000;
private static final float LOCATION_DISTANCE = 0f;
private class LocationListener implements android.location.LocationListener {
Location mLastLocation;
public LocationListener(String provider) {
Log.e(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(Location location) {
Log.e(TAG, "LocationListener " + location);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.e(TAG, "onStatusChanged " + provider);
}
#Override
public void onProviderEnabled(String provider) {
Log.e(TAG, "onProviderEnabled " + provider);
}
#Override
public void onProviderDisabled(String provider) {
Log.e(TAG, "onProviderDisabled" + provider);
}
}
android.location.LocationListener[] mLocationListener = new android.location.LocationListener[]{
new LocationListener(LocationManager.GPS_PROVIDER), new LocationListener(LocationManager.NETWORK_PROVIDER)
};
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
#Override
public void onCreate() {
Log.e(TAG, "onCreate");
initializeLocationManagrr();
try {
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE, mLocationListener[0]);
}catch(java.lang.SecurityException ex){
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex1){
Log.d(TAG, "gps provider does not exist " + ex1.getMessage());
}
}
#Override
public void onDestroy() {
Log.e(TAG,"onDestroy");
super.onDestroy();
if(mLocationManager!=null){
for(int i=0;i<mLocationListener.length;i++){
try{
mLocationManager.removeUpdates(mLocationListener[i]);
}catch ( Exception e2){
Log.i(TAG, "fail to remove location listners, ignore", e2);
}
}
}
}
private void initializeLocationManagrr(){
Log.e(TAG,"initializeLocationManagaer");
if(mLocationManager==null){
mLocationManager=(LocationManager)getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
}
And am calling this class from MainActivity.java like this
startService(new Intent(MainActivity.this,MyService.class));
and in my Log nothing is shown regarding the location.
And also i have added the google service config files in my app.
My main problem is am not getting any user location in my Log cat but the app is running fine.
Can Anyone help me please.
you can use LocationListener which gets called when your location get changed and moreover you can provide time interval too
LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener(context);
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 1,mlocL istener);
// syntax: mlocManager.requestLocationUpdates(provider, minTime, minDistance, listener)
you can set time and distance both in this method see ths syntax
I am new in using background service and retrofit library, i am getting no error, by debugging my app i come to know that its getting coordinates but not sending to server(in background service)
Any help will appreciated, thanks in advance, happy coding!
GPS Service
public class LocationUpdaterService extends Service
{
public static final int TWO_MINUTES = 120000; // 120 seconds
public static Boolean isRunning = false;
public LocationManager mLocationManager;
public LocationUpdaterListener mLocationListener;
public Location previousBestLocation = null;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocationListener = new LocationUpdaterListener();
super.onCreate();
}
Handler mHandler = new Handler();
Runnable mHandlerTask = new Runnable(){
#Override
public void run() {
if (!isRunning) {
startListening();
}
mHandler.postDelayed(mHandlerTask, TWO_MINUTES);
}
};
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mHandlerTask.run();
return START_STICKY;
}
#Override
public void onDestroy() {
stopListening();
mHandler.removeCallbacks(mHandlerTask);
super.onDestroy();
}
private void startListening() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (mLocationManager.getAllProviders().contains(LocationManager.NETWORK_PROVIDER))
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mLocationListener);
if (mLocationManager.getAllProviders().contains(LocationManager.GPS_PROVIDER))
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener);
}
isRunning = true;
}
private void stopListening() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLocationManager.removeUpdates(mLocationListener);
}
isRunning = false;
}
public class LocationUpdaterListener implements LocationListener
{
#Override
public void onLocationChanged(Location location) {
if (isBetterLocation(location, previousBestLocation)) {
previousBestLocation = location;
try {
// Script to post location data to server..
Call<Update> loginCall;
String deviceKey;
deviceKey = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
loginCall = MyApplication.getInstance().getAPI().update(deviceKey,String.valueOf(location.getLatitude()),String.valueOf(location.getLongitude()));
loginCall.enqueue(new Callback<Update>() {
#Override
public void onResponse(Call<Update> call, Response<Update> response) {
if(response.getClass() != null)
{
}
}
#Override
public void onFailure(Call<Update> call, Throwable t) {
}
});
}
catch (Exception e) {
e.printStackTrace();
}
finally {
stopListening();
}
}
}
#Override
public void onProviderDisabled(String provider) {
stopListening();
}
#Override
public void onProviderEnabled(String provider) { }
#Override
public void onStatusChanged(String provider, int status, Bundle extras) { }
}
protected boolean isBetterLocation(Location location, Location currentBestLocation) {
if (currentBestLocation == null) {
// A new location is always better than no location
return true;
}
// Check whether the new location fix is newer or older
long timeDelta = location.getTime() - currentBestLocation.getTime();
boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
boolean isNewer = timeDelta > 0;
// If it's been more than two minutes since the current location, use the new location
// because the user has likely moved
if (isSignificantlyNewer) {
return true;
// If the new location is more than two minutes older, it must be worse
} else if (isSignificantlyOlder) {
return false;
}
// Check whether the new location fix is more or less accurate
int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
boolean isLessAccurate = accuracyDelta > 0;
boolean isMoreAccurate = accuracyDelta < 0;
boolean isSignificantlyLessAccurate = accuracyDelta > 200;
// Check if the old and new location are from the same provider
boolean isFromSameProvider = isSameProvider(location.getProvider(), currentBestLocation.getProvider());
// Determine location quality using a combination of timeliness and accuracy
if (isMoreAccurate) {
return true;
} else if (isNewer && !isLessAccurate) {
return true;
} else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
return true;
}
return false;
}
/** Checks whether two providers are the same */
private boolean isSameProvider(String provider1, String provider2) {
if (provider1 == null) {
return provider2 == null;
}
return provider1.equals(provider2);
}
My Application
import android.app.Application;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MyApplication extends Application {
private API api;
private OkHttpClient client;
private static MyApplication sInstance;
#Override
public void onCreate() {
super.onCreate();
sInstance = this;
configureAPI();
}
private void configureAPI() {
client = new OkHttpClient.Builder()
.connectTimeout(80, TimeUnit.SECONDS)
.writeTimeout(300, TimeUnit.SECONDS)
.readTimeout(80, TimeUnit.SECONDS)
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Server.API_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
api = retrofit.create(API.class);
}
public API getAPI() {
return api;
}
public static MyApplication getInstance() {
return sInstance;
}
}
API
public interface API {
#FormUrlEncoded
#POST("updateLocation")
Call<Update> update(#Query("token") String token, #Query("lat") String latitude, #Field("long") String longitude);
}
Server
public class Server {
public static final String API_URL = "http://192.168.146.2:8090/";
public static final String REG_API_URL = "http://192.168.120.2:8090/";
public static final String SndMsg_API_URL = "http://192.168.120.2:8090/";
}
MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent serviceIntent = new Intent(getApplicationContext(), LocationUpdaterService.class);
startService(serviceIntent);
}
}
Your code looks pretty good. There are few things those might be causing problems. please check those.
First of all make sure compiler is going inside the "OnLocationChanged()" method.
Second thing make sure your web-service call method is of "Update" type. Because you are using "Update". It can be "Post".
Third thing is print the response in "OnFailure()" method, maybe it is going to failure.
I hope you will find the problem by checking these scenarios.
I want to insert into SQLite the location every 5 minutes, but the location is inserted every time it changes, I'm new with this, I know I have the insert inside the onlocationchange, but it's supposed to call every x time. I do not know what to do
public class GPS extends Service {
public static final int notify = 1000*60*5; //interval between two services(Here Service run every 5 Minute)
private Handler mHandler = new Handler();
private Timer mTimer = null;
private LocationManager locationMangaer = null;
private LocationListener locationListener = null;
private static final String TAG = "Debug";
private Boolean flag = false;
#Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate() {
if (mTimer != null)
mTimer.cancel();
else {
mTimer = new Timer();
mTimer.scheduleAtFixedRate(new TimeDisplay(), 0, notify);
}
locationMangaer = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
}
private Boolean displayGpsStatus() {
ContentResolver contentResolver = getBaseContext().getContentResolver();
boolean gpsStatus = Settings.Secure.isLocationProviderEnabled(contentResolver,LocationManager.GPS_PROVIDER);
if (gpsStatus) {
return true;
} else {
return false;
}
}
public class MyLocationListener implements LocationListener {
dbISMLock dbismlock = new dbISMLock(getBaseContext());
final SQLiteDatabase db =dbismlock.getWritableDatabase();
#Override
public void onLocationChanged(Location loc) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentDateandTime = sdf.format(new Date());
Toast.makeText(getBaseContext(),"fecha: "+ currentDateandTime +"Location changed : Lat: " + loc.getLatitude()+ " Lng: " + loc.getLongitude(),Toast.LENGTH_SHORT).show();
String longitude = "Longitude: " +loc.getLongitude();
Log.v(TAG, longitude);
String latitude = "Latitude: " +loc.getLatitude();
Log.v(TAG, latitude);
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String phoneID = telephonyManager.getDeviceId();
//INSERT
db.execSQL("INSERT INTO GEOLOCATION( phoneId,Fecha,longitude, latitude) VALUES('"+phoneID+"','"+currentDateandTime+"','"+longitude+"','"+latitude+"')");
Log.d("insertamos "," geolocation" );
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
#Override
public void onDestroy() {
super.onDestroy();
mTimer.cancel();
Toast.makeText(this, "Service is Destroyed", Toast.LENGTH_SHORT).show();
}
class TimeDisplay extends TimerTask {
#Override
public void run() {
mHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(GPS.this, coordenadas(), Toast.LENGTH_SHORT).show();
flag = displayGpsStatus();
if (flag) {
Log.v(TAG, "onClick");
locationListener = new MyLocationListener();
if (ActivityCompat.checkSelfPermission(GPS.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(GPS.this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationMangaer.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener);
} else {
Log.d("Gps Status!!", "Your GPS is: OFF");
}
}
});
}
}
}
You can use a Service to listen to location change in background and update it every 5 minutes. onLocationchange() is used to listen manually to changes. So you can ignore it for example and use the Service.
The thing is that I'm trying on the emulator, and it works but only once I press the "send location to device" on the emulator but before that I don't have the chance to get the location....How do I get the location for the first time using this service?. I don't have a real device right know and the emulator is my only way of testing this for now.....I tried to send a 0,0 at first to see if that would trigger a location update but it's not working as well......any ideas?
#SuppressWarnings("MissingPermission")
public class GPSService extends Service {
private LocationListener listener;
private LocationManager locationManager;
private String lastKnownLatitude;
private String lastKnownLongitude;
private Boolean isFirstTime=true;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
broadcastLocation("0","0");
listener= new LocationListener() {
#Override
public void onLocationChanged(Location location) {
//To transfer the data to the main activity I use broadcast receiver in the main activity, using an intent filter location_update
Intent intentSendLocationMainActivity = new Intent("location_update");
lastKnownLatitude=""+location.getLatitude();
lastKnownLongitude=""+location.getLongitude();
Log.d("LOCATION-UPDATE",lastKnownLatitude+" long:"+lastKnownLongitude);
broadcastLocation(lastKnownLatitude,lastKnownLongitude);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
Log.d("GPS-Stat-Changed",s);
}
#Override
public void onProviderEnabled(String s) {
Log.d("GPS-Provider-Enabled",s);
}
#Override
public void onProviderDisabled(String s) {
Intent activateGPSIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
activateGPSIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(activateGPSIntent);
}
};
locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
//noinspection MissingPermission, listen for updates every 3 seconds
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,5000,0,listener);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("ClearFromRecentService", "Service Started");
Log.d("LAST_LAT_AND_LONG",lastKnownLatitude+" "+lastKnownLongitude);
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d("ClearFromRecentService", "Service Destroyed, Removing update location listener");
//unregistering the listener
/*if(locationManager != null){
locationManager.removeUpdates(listener);
}*/
}
public void onTaskRemoved(Intent rootIntent) {
Log.e("ClearFromRecentService", "END");
//here you can call a background network request to post you location to server when app is killed
Toast.makeText(getApplicationContext(), "I'm still getting user coordinates", Toast.LENGTH_LONG).show();
//stopSelf(); //call this method to stop the service
}
public void broadcastLocation(String latitude,String longitude){
Intent intentSendLocationMainActivity = new Intent("location_update");
intentSendLocationMainActivity.putExtra("latitude",latitude);
intentSendLocationMainActivity.putExtra("longitude",longitude);
//I need to differentiate here if the app is killed or not to send the location to main activity or to a server
sendBroadcast(intentSendLocationMainActivity);
}
}
EDIT: This is the complete service working. For the first time it gets the coordinates with the getLastKnownLocation() and the on sucesive times with the listener onLocationChanged()
#SuppressWarnings("MissingPermission")
public class GPSService extends Service {
private LocationListener listener;
private LocationManager locationManager;
private String lastKnownLatitude;
private String lastKnownLongitude;
private Boolean isFirstTime=true;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
listener= new LocationListener() {
#Override
public void onLocationChanged(Location location) {
//To transfer the data to the main activity I use broadcast receiver in the main activity, using an intent filter location_update
Intent intentSendLocationMainActivity = new Intent("location_update");
lastKnownLatitude=""+location.getLatitude();
lastKnownLongitude=""+location.getLongitude();
Log.d("LOCATION-UPDATE",lastKnownLatitude+" long:"+lastKnownLongitude);
broadcastLocation(lastKnownLatitude,lastKnownLongitude);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
Log.d("GPS-Stat-Changed",s);
}
#Override
public void onProviderEnabled(String s) {
Log.d("GPS-Provider-Enabled",s);
}
#Override
public void onProviderDisabled(String s) {
Intent activateGPSIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
activateGPSIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(activateGPSIntent);
}
};
locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
//noinspection MissingPermission, listen for updates every 3 seconds
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,5000,0,listener);
Map<String, String> coordinates=getLastKnownLocation(locationManager);
broadcastLocation(coordinates.get("latitude"),coordinates.get("longitude"));
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("ClearFromRecentService", "Service Started");
Log.d("LAST_LAT_AND_LONG",lastKnownLatitude+" "+lastKnownLongitude);
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d("ClearFromRecentService", "Service Destroyed, Removing update location listener");
//unregistering the listener
/*if(locationManager != null){
locationManager.removeUpdates(listener);
}*/
}
public void onTaskRemoved(Intent rootIntent) {
Log.e("ClearFromRecentService", "END");
//here you can call a background network request to post you location to server when app is killed
Toast.makeText(getApplicationContext(), "I'm still getting user coordinates", Toast.LENGTH_LONG).show();
//stopSelf(); //call this method to stop the service
}
private void broadcastLocation(String latitude,String longitude){
Intent intentSendLocationMainActivity = new Intent("location_update");
intentSendLocationMainActivity.putExtra("latitude",latitude);
intentSendLocationMainActivity.putExtra("longitude",longitude);
//I need to differentiate here if the app is killed or not to send the location to main activity or to a server
sendBroadcast(intentSendLocationMainActivity);
}
private Map<String, String> getLastKnownLocation(LocationManager lm){
Location lastKnownLocation=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
String ll=""+lastKnownLocation.getLatitude();
Map<String, String> coordinates = new HashMap<String, String>();
// Check everytime this value, it may be null
if(lastKnownLocation != null){
coordinates.put("latitude",""+lastKnownLocation.getLatitude());
coordinates.put("longitude",""+lastKnownLocation.getLongitude());
}else{
coordinates.put("latitude","0");
coordinates.put("longitude","0");
}
return coordinates;
}
}
#Override
public void onCreate() {
super.onCreate();
locationManager = (LocationManager) getApplicationContext()
.getSystemService(Context.LOCATION_SERVICE);
Location lastKnownLocation = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
// Check everytime this value, it may be null
if(lastKnownLocation != null){
double latitude = lastKnownLocation.getLatitude();
double longitude = lastKnownLocation.getLongitude();
// Use values as you wish
}
broadcastLocation("0","0");
....
}
I'm having some troubles trying to stop a services which I started previously on the onCreate() of class that is extended of an Android Application class. The GPS is supposed to be running during the execution of the app (that part is working fine) but when the app is closed the service is still running. I tried to use the onTerminate() because onClose() doesn´t exist in Applicaction class and the service keep running.
public class ControlEntrega extends Application {
public GPSBean posicion;
public ServicioGPS servicio;
public void onCreate() {
Log.d(TAG,"onCreate");
super.onCreate();
usuario=null;
cliente=null;
entrega=null;
dal=new DAL(getApplicationContext());
crearDB();
util=new Utilitario();
servicio=new ServicioGPS();
posicion=new GPSBean();
iniciarGPS();
}
#Override
public void onTerminate() {
super.onTerminate();
Log.d(TAG,"onTerminate");
try {
stopService(new Intent(this,ServicioGPS.class));
} catch (Exception e) {
Log.d(TAG,"onTerminate error: "+e.getMessage());
}
}
}
The Service Class:
public class ServicioGPS extends Service implements LocationListener{
String TAG=ServicioGPS.class.getCanonicalName();
LocationManager locationManager=null;
public int tiempoGPS=1;
public int distanciaMetros=10;
Intent notificacion;
ControlEntrega controlador;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG,"onDestroy");
locationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
locationManager.removeUpdates(this);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand");
controlador= (ControlEntrega)getApplicationContext();
if(controlador!=null){
if(controlador.posicion!=null){
controlador.posicion.imprimir();
}
}
locationManager =(LocationManager)getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria,true);
//LocationManager.GPS_PROVIDER
//LocationManager.NETWORK_PROVIDER
locationManager.requestLocationUpdates(provider,1000 * 60 * tiempoGPS,distanciaMetros,this);
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onLocationChanged(Location location) {
Log.d(TAG, "onLocationChanged");
//Seteando los valores del objeto location
if(controlador!=null){
Log.d(TAG, "seteando bean GPS");
controlador.posicion=new GPSBean();
controlador.posicion.latitud=location.getLatitude();
controlador.posicion.longitud=location.getLongitude();
controlador.posicion.altitud=location.getAltitude();
controlador.posicion.precision=location.getAccuracy();
controlador.posicion.proveedor=location.getProvider();
controlador.posicion.tiempo=location.getTime();
controlador.posicion.velocidad=location.getSpeed();
controlador.posicion.imprimir();
}
//Notificación
Intent notificacion = new Intent(getString(R.string.intentGPS));
sendBroadcast(notificacion);
//Se para asi mismo, ya se calendarizo antes
stopSelf();
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
There is a way I could know when the application stops completely? So I can stop the service.
Regards
Alfredo
public class EyeCastApplication extends Application {
static Context context;
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
context = getApplicationContext();
}
/***
* start Heart Beat Loop
*/
public static void stopHeartBeatLoop() {
context.stopService(new Intent(context, CmdConnectService.class));
}
enter code here
enter code here
}