2013-11-01 62 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(); 
     }