onLocationChanged从未调用过

时间:2017-04-02 19:03:45

标签: android geolocation location maps

我不知道为什么当我按下按钮时我的地图不会调用onLocationChanged。这些是我的权限:

<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.ACCESS_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />

这是我的班级:

公共类NuevaCarreraFragment扩展了Fragment实现OnMapReadyCallback,LocationListener,View.OnClickListener {

private View view;
private LiveButton btnIniciarCarrera;
private LiveButton btnFinalizarCarrera;
private SupportMapFragment mapFragment;
private GoogleMap mGoogleMap;
private LocationManager locationManager;


public static NuevaCarreraFragment newInstance() {
    Bundle args = new Bundle();
    NuevaCarreraFragment fragment = new NuevaCarreraFragment();
    fragment.setArguments(args);
    return fragment;
}

/** Ciclo de vida **/

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    // Comprobamos si la vista ya ha sido inflada previamente
    if (view != null) {
        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null)
            parent.removeView(view);
    }

    try {// Si no ha sido inflada previamente...
        view = inflater.inflate(R.layout.fragment_nueva_carrera, container, false);

        // Instanciamos los componentes
        btnIniciarCarrera = (LiveButton) view.findViewById(R.id.button_iniciar_carrera);
        btnFinalizarCarrera = (LiveButton) view.findViewById(R.id.button_finalizar_carrera);
        mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);

        // Escuchamos a nuestros componentes
        btnIniciarCarrera.setOnClickListener(this);
        btnFinalizarCarrera.setOnClickListener(this);

        // Sincronizamos nuestro mapa
        mapFragment.onCreate(savedInstanceState);
        mapFragment.getMapAsync(this);

    } catch (InflateException e) {
        e.printStackTrace();
    }

    return view;
}

@Override
public void onStart() {
    super.onStart();
}

@Override
public void onResume() {
    super.onResume();
    if (mapFragment != null) {
        mapFragment.onResume();
    }
}

@Override
public void onPause() {
    if (mapFragment != null) {
        locationManager.removeUpdates(this);
        mapFragment.onPause();
    }
    super.onPause();
}

@Override
public void onStop() {
    super.onStop();
}

@Override
public void onDestroy() {
    Fragment fragment = getFragmentManager().findFragmentById(R.id.map);
    if (fragment != null) {
        getFragmentManager().beginTransaction()
                .remove(fragment)
                .commit();
    }
    super.onDestroy();
}

@Override
public void onDestroyView() {
    super.onDestroyView();
    Fragment fragment = getFragmentManager().findFragmentById(R.id.map);
    if (fragment != null) {
        getFragmentManager().beginTransaction()
                .remove(fragment)
                .commit();
    }
}


@Override
public void onLowMemory() {
    super.onLowMemory();
    if (mapFragment != null) {
        mapFragment.onLowMemory();
    }
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    if (mapFragment != null) {
        mapFragment.onSaveInstanceState(outState);
    }
}

/** OnClickListener **/

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.button_iniciar_carrera:
            // Inicializamos el localizador
            locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
            if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
            if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
            } else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
            }
            break;
        case R.id.button_finalizar_carrera:
            locationManager.removeUpdates(this);
            break;
    }

}

/** OnMapReadyCallback and LocationListener interface methods **/

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

    LatLng sydney = new LatLng(-33.867, 151.206);

    mGoogleMap.addMarker(new MarkerOptions()
            .title("Sydney")
            .snippet("The most populous city in Australia.")
            .position(sydney));

    mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 13));
}

/** LocationListener interface methods **/

@Override
public void onLocationChanged(Location location) {
    double latitude = location.getLatitude();
    double longitude = location.getLongitude();
    LatLng misCoordenadas = new LatLng(latitude, longitude);
    Geocoder geocoder = new Geocoder(getContext());
    try {
        List<Address> addressList = geocoder.getFromLocation(latitude, longitude, 1);
        String direccion = addressList.get(0).getAddressLine(0);
        direccion += "," + addressList.get(0).getLocality();
        direccion += "," + addressList.get(0).getCountryName();

        mGoogleMap.addMarker(new MarkerOptions()
                .position(misCoordenadas)
                .title(direccion)
                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
        mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(misCoordenadas, 17));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}

地图已正确显示,但无法获取我的位置:(。 有什么想法吗?

更新

最后,我能够解决实施Google API客户端和融合位置功能的问题。

1 个答案:

答案 0 :(得分:0)

  1. 该应用是否有权限?你处理了未批准的案件吗?
  2. 这些应用程序请求的提供程序是否已启用?
  3. 您是否调试了该应用,并且到达了locationManager.requestLocationUpdates行的任何一行?
  4. 似乎应用程序由于缺少1和2而没有请求