Hi I am working on app that when it receives push notification should get it's location and call server where then based on that it gets to show notification or swallow it.
Problem that I am a experiencing is that location is getting cashed and then I don't get to notify my clients in time which is essential. I obviously cannot subscribe to onLocationChanged
as I need to make decision on message right then.
I have read about it and one of suggestions was to initialize com.google.android.gms.location.LocationListener
which should reset cache which I don't think it does, however enabling google maps does indeed help to get updated coordinates so I would assume this is indeed issue with caching.
Currently code looks like this (please don't judge it's prototype only):
private String getLocation() {
// Get the location manager
new LocationListener() {
@Override
public void onLocationChanged(Location location) {
}
};
LocationManager locationManager = (LocationManager)
getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, false);
if (bestProvider != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return "-1.1329097,51.257538";
}
}
Location location = locationManager.getLastKnownLocation(bestProvider);
try {
return location.getLatitude() + "," + location.getLongitude();
} catch (NullPointerException e) {
return "-1.1329097,51.257538";
}
}
return "-1.1329097,51.257538";
}
public void onMessageReceived(String from, Bundle data) {
String message = data.getString("message");
Log.d(TAG, "From: " + from);
Log.d(TAG, "Message: " + message);
sendNotification = true;
callEmergency();
}
public boolean callEmergency(){
StringBuffer chaine = new StringBuffer("");
try{
InstanceID instanceID = InstanceID.getInstance(this);
String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
URL url = new URL("http://www.ears.uk.com/User/CheckForEmergency?token="+token+"&coordinates="+getLocation());
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
// connection.setRequestProperty("User-Agent", "");
connection.setRequestMethod("GET");
// connection.setDoInput(true);
connection.connect();
int code = connection.getResponseCode();
InputStream inputStream = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while ((line = rd.readLine()) != null) {
chaine.append(line);
}
if(chaine.toString().equals("True")){
sendNotification("Emergency Vehicle Approaching");
}
} catch (IOException e) {
// writing exception to log
e.printStackTrace();
}
return chaine.toString() == "True";
}
Is there a more appropriate solution to do this?