获取片段中的更新和lastknownlocation

时间:2018-02-14 09:41:52

标签: android android-location android-fusedlocation

对java非常陌生,我对获取lastknownlocationupdated location非常困惑。

在过去的几天里,我设法在预定义的位置上获得了标记,但我在使用fusedlocationproviderclient获取当前位置时非常努力。

如果有人帮助我做到这一点,我将不胜感激。 我正在使用:

compile 'com.google.android.gms:play-services-maps:11.8.0'
compile 'com.google.android.gms:play-services-location:11.8.0'

虽然不是更新的位置,但下面是固定位置的标记代码

public class SecondFragment extends Fragment implements OnMapReadyCallback {

    private GoogleMap mMap;

    public GoogleMap getMap() {
    return mMap;
    }
    public static SecondFragment newInstance() {
        SecondFragment fragment = new SecondFragment();
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_maps, null, false);

        SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        return view;
    }


    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }
}

1 个答案:

答案 0 :(得分:1)

我用它来获取我的位置:

 LocationManager locationManager = (LocationManager)getActivity().getSystemService(getContext().LOCATION_SERVICE);
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
                Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

和听众:

 LocationListener locationListener = new LocationListener() {
                    @Override
                    public void onLocationChanged(Location location) {
                        Log.e("osm", "onLocationChanged: "+location.getLongitude() );
                    }

                    @Override
                    public void onStatusChanged(String s, int i, Bundle bundle) {

                    }

                    @Override
                    public void onProviderEnabled(String s) {

                    }

                    @Override
                    public void onProviderDisabled(String s) {

                    }
                };

不要忘记写清楚这一点:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 

和新版Android(6及更高版本)的运行时权限:

String[] permission = new String[]{Manifest.permission.CALL_PHONE,Manifest.permission.ACCESS_FINE_LOCATION};
        ActivityCompat.requestPermissions(this,permission,PERMISSON_CODE);`