I have a issue where I’m trying to create a class that uses the location manager but isn’t the currently running activity. So when I call this class from any activity it just does it all in the background. I tried extending Services but keeps returning a null pointer error.
It is this line of code that returns the error.
public class BackgroundGps extends Service{
UserObject uo = null;
BackgroundGps(UserObject userObj){
uo = userObj;
uo.setHeader("GPSUpdate");
}
public void locationListener(){
LocationManager mlocManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new LocationListener(){
public void onLocationChanged(Location location){
if(uo.getLatitude() == ("" + location.getLatitude()) && uo.getLongitude() == ("" + location.getLongitude())){}
else{
uo.setLatitude("" + location.getLatitude());
uo.setLongitude("" + location.getLongitude());
updateGPS();
}
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 5, mlocListener);
mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 60000, 5, mlocListener);
}
Thanks
Acquire a reference to the system Location Manager
locationManager will not throw a nullpointer on a device, will on a emulator
Register the listener with the Location Manager to receive location updates. Here you can use NETWORK_PROVIDER OR GPS_PROVIDER etc as per your need*