首页 文章

获取用户当前位置android

提问于
浏览
5

嗨,我正在开发Android应用程序,我希望用户当前位置足够准确 . 所以我有2个选项来实现这一个

Retrieving the Current Location . http://developer.android.com/training/location/retrieve-current.html

Receiving Location Updates http://developer.android.com/training/location/receive-location-updates.html

所以这是我的问题 . 我经历了检索当前位置,我意识到最后它给了我用户最后知名的位置 . 但我的要求是用户当前位置 .

所以我走向接收位置更新 . 我虽然可以获得第一次更新,但我会停止更新 . 但这也是第一次它给了我最后的位置而不是新的位置 . 并在第一次阅读后启动gps以提供连续更新 . 但我只对第一次更新感兴趣 .

所以我需要一个好的解决方案,它会给我用户准确的当前位置 . 使用gps或网络或wifi任何可用的 .

如果我做错了什么请更正 . 需要帮忙 . 谢谢 .

2 回答

  • 1

    这就是我如何获取用户当前位置以用于我的Google Map .

    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();
            }
    
  • 2

    你需要GPS listener solution

    添加到位置侦听器,但选择GPS . 只有 public void onLocationChanged(Location loc) 才能拥有当前位置 .

相关问题