嗨我正在開發應用程序,當它接收到推送通知時,應該獲取它的位置並調用服務器,然後根據它顯示通知或吞下它。從GcmListenerService獲取更新位置onMessageReceived
我遇到的問題是地點變得流利,然後我不能及時通知我的客戶,這是至關重要的。我顯然不能訂閱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";
}
有沒有更合適的解決方案來做到這一點?
但是,沒有辦法只是觸發獲取當前位置而不必創建偵聽器或禁用緩存。我喜歡getTime的想法,但據我所知,我必須以某種方式跟蹤本地存儲時間+我並不真正關心原型的良好實踐和電池壽命。 –
不,不存在 – tyczj
如果您使用Fused Location API,您可以獲得一次性位置,但仍然需要您啓動位置偵聽器https://developers.google.com/android/reference/com/google/android/克/位置/ LocationRequest#恆定摘要 – tyczj