2016-06-07 134 views
0

我有一個按鈕,就可以在每次用戶點擊,我叫javascriptinterface getLocation(),如果定位服務是關閉的,帶來了用戶設置,讓用戶打開它。位置後啓用位置服務,

我通過onConnectedonLocationChanged得到的位置。每當我打開我的應用程序,onConnected被解僱,並將獲得位置。但我注意到,當我能夠從設置的位置服務,回來馬上應用程序,該onConnected被炒魷魚,但位置仍然是null。看起來像是有延遲或什麼的。直到約3秒後,我再試一次,它會工作,併爲我獲得位置。

這裏是我相關的代碼:

Android的一面:

protected Location location; 
public void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.web_view); 

    webView = (WebView) findViewById(R.id.webview); 

    ...... 
} 

// JavaScript Interface for location on Pick Listing Page 
public class LocationInterface 
{ 
    @JavascriptInterface 
    public String getLocation() throws JSONException 
    { 
     JSONObject json = new JSONObject(); 
     if (location != null) 
     { 
      json.put("lat", location.getLatitude()); 
      json.put("lon", location.getLongitude()); 
      return(json.toString()); 
     } 
     else 
     { 
      Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
      startActivity(intent); 
     } 
     return(null); 
    } 
} 

......//many override lifecycle methods here 

@Override 
public void onConnected(Bundle connectionHint) 
{ 
    location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient); 
} 

@Override 
public void onLocationChanged(Location newLocation) 
{ 
    location = newLocation; 
} 

我的問題是,我怎麼能得到位置沒有延遲。

回答

0

請確保您在活動的onStart()中請求位置更新,以便當您從位置設置返回時,活動將請求位置更新。

+0

補充一點:'LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient,locationRequest,這一點);'? –

+0

似乎不起作用。它殺死了應用程序。 –

+0

你能分享你的logcat輸出嗎? –

0

我找到了出路,最終:

添加一個條件getLocation()

.... 
    if (location != null) 
    { 
     .... 
    } 
    else if (location == null && isLocationEnabled(context) 
    { 
     long startTime = System.currentTimeMillis(); 
     while (location == null && (System.currentTimeMillis()-startTime) < 5000) 
     { 
      location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient); 
     } 
     if (location != null) 
     { 
      json.put("lat", location.getLatitude()); 
      json.put("lon", location.getLongitude()); 
      return(json.toString()); 
     } 
     return(null); 
    } 
    else 
    { 
     Intent intent = .... 
     .... 
    } 
    return(null);