获取用户当前位置android

时间:2013-11-01 07:46:35

标签: android location

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

检索当前位置http://developer.android.com/training/location/retrieve-current.html

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

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

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

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

如果我做错了,请纠正。需要帮忙。谢谢。

2 个答案:

答案 0 :(得分:2)

这就是我将用户当前位置用于我的Google地图的方式。

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

答案 1 :(得分:1)

GPS listener solution你需要。

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

相关问题