嗨,我正在开发应用程序,当它收到推送通知时应该获取它的位置并调用服务器,然后根据它显示通知或吞下它。
我遇到的问题是位置正在兑现,然后我没有及时通知我的客户,这是必不可少的。我显然不能订阅,onLocationChanged
因为那时我需要对消息做出决定。
我已经阅读过它,其中一个建议是初始化com.google.android.gms.location.LocationListener
哪个应该重置缓存,我认为它不会,但是启用谷歌地图确实有助于获取更新的坐标,所以我认为这确实是缓存的问题。
目前的代码是这样的(请不要仅仅判断它的原型):
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";
}
有没有更合适的解决方案来做到这一点?