2013-11-01 218 views
5

嗨我正在開發android應用程序,我希望用戶當前的位置足夠精確。所以我有2個選項來實現這一個獲取用戶當前位置android

正在檢索當前位置http://developer.android.com/training/location/retrieve-current.html

接收位置更新http://developer.android.com/training/location/receive-location-updates.html

因此,這裏是我的問題。我經歷了檢索當前位置,最終我意識到它給了我用戶最後一個最有名的位置。但我的要求是用戶目前的位置。

所以我正在接收位置更新。我雖然我可以得到第一次更新,我會停止更新。但這也是第一次,它給了我最後一個位置不是新的位置。並在第一次閱讀後開始GPS連續更新。但我只對第一次更新感興趣。

所以我需要一個好的解決方案,它會給我的用戶準確的當前位置。無論是使用GPS或網絡或WiFi任何一個可用。

如果我做錯了什麼,請更正。需要幫忙。謝謝。

回答

1

GPS listener solution你需要。

添加到位置監聽器,但選擇GPS。只有public void onLocationChanged(Location loc)將具有當前位置。

+0

謝謝您的建議。我想通過你的解決方案。但是我覺得它不會提供那麼大的靈活性。我的意思是我提到那些照顧位置提供者的API。這意味着如果GPS不可用,那麼它會自動使用其他提供商的位置。所以我會錯過這些功能。當然,我會嘗試你的解決方案。 – nilkash

2

所以這就是我如何獲得用戶當前位置用於我的谷歌地圖。

if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { 
      mMap.setMyLocationEnabled(true); 
      Criteria criteria = new Criteria(); 
      LocationManager locationManager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE); 
      String provider = locationManager.getBestProvider(criteria, false); 
      Location location = locationManager.getLastKnownLocation(provider); 
      double lat = location.getLatitude(); 
      double lng = location.getLongitude(); 
      LatLng coordinate = new LatLng(lat, lng); 
      CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, 13); 
      mMap.animateCamera(yourLocation); 

     } else { 
      final AlertDialog alertDialogGPS = new AlertDialog.Builder(getActivity()).create(); 

      alertDialogGPS.setTitle("Info"); 
      alertDialogGPS.setMessage("Looks like you have not given GPS permissions. Please give GPS permissions and return back to the app."); 
      alertDialogGPS.setIcon(android.R.drawable.ic_dialog_alert); 
      alertDialogGPS.setButton("OK", new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int which) { 

        Intent intentSettings = new Intent(Settings.ACTION_APPLICATION_SETTINGS); 
        startActivity(intentSettings); 
        alertDialogGPS.dismiss(); 
       } 

      }); 

      alertDialogGPS.show(); 
     }