onLocationChanged没有被调用

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了onLocationChanged没有被调用相关的知识,希望对你有一定的参考价值。

我的android应用程序有问题,我无法检索设备的当前位置。从调试应用程序看来,我的LocationListener中的onLocationChange没有被触发。 我已经设置了requestLocationUpdates来处理我的LocationListener,以及输出到onLocationChange中的Log,但我什么也没收到。 我还注意到,当我使用应用程序时,手机顶部栏中没有GPS图标,但如果我切换到谷歌地图应用程序,图标会立即显示... 我现在正在努力解决这个问题,所以任何帮助都会受到赞赏。谢谢。

map fragment.Java:

public class MapFragment extends Fragment implements OnMapReadyCallback {

    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;

    private OnFragmentInteractionListener mListener;

    private SupportMapFragment mapFragment;
    private GoogleMap googleMap;

    LocationManager locationManager;

    public MapFragment() {
        // Required empty public constructor
    }

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

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {


        }
    }

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

        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_map, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mapFragment = (SupportMapFragment) this.getChildFragmentManager().findFragmentById(R.id.map);
        mapFragment.onCreate(savedInstanceState);
        mapFragment.onResume();
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface OnFragmentInteractionListener {

        void onFragmentInteraction(Uri uri);
    }


    @Override
    public void onMapReady(GoogleMap map) {

        googleMap = map;

        locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);

        checkLocationPermission();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_LOCATION: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // location-related task you need to do.
                    if (ContextCompat.checkSelfPermission(getActivity(),
                            Manifest.permission.ACCESS_FINE_LOCATION)
                            == PackageManager.PERMISSION_GRANTED) {

                        //Request location updates:
                        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener);
                        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mLocationListener);
                    }

                } else {


                    // functionality that depends on this permission.

                }
                return;
            }

        }
    }

    private final LocationListener mLocationListener = new LocationListener() {

        @Override
        public void onLocationChanged(final Location location) {
            //your code here

            Log.v("LOCATION UPDATE", "IN ON LOCATION CHANGE, lat=" + location.getLatitude() + ", lon=" + location.getLongitude());

            /*
            LatLng userPosition = new LatLng(location.getLatitude(),location.getLongitude());

            googleMap.addMarker(new MarkerOptions()
                    .position(userPosition)
                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_pin_fill))
                    .title("Test Pin"));*/
        }

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

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    };

    public boolean checkLocationPermission() {

        if (ContextCompat.checkSelfPermission(getActivity(),
                Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {

            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                    Manifest.permission.ACCESS_FINE_LOCATION)) {

                //dialog to ask for permission
                new AlertDialog.Builder(getActivity())
                        .setTitle("Permission")
                        .setMessage("Need permission")
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                //Prompt the user once explanation has been shown
                                ActivityCompat.requestPermissions(getActivity(),
                                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                        MY_PERMISSIONS_REQUEST_LOCATION);
                            }
                        })
                        .create()
                        .show();
            }
            else {

                ActivityCompat.requestPermissions(getActivity(),
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION);

                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener);
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mLocationListener);
            }
            return false;

        } else {

            return true;
        }
    }

}

不确定是否相关但是fragment_map.xml

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MapFragment" />
答案

你确定locationManager.requestLocationUpdates()正在执行吗?基于此代码,如果在启动时已经授予ACCESS_FINE_LOCATION,则checkLocationPermission()将返回true,并且没有任何内容调用requestLocationUpdates()

以上是关于onLocationChanged没有被调用的主要内容,如果未能解决你的问题,请参考以下文章

onLocationChanged 未被调用

onLocationChanged 在每个时间间隔调用两次

onLocationChanged 永远不会被调用 Emulator

onLocationChanged 在应用程序启动时被多次调用

为啥 Android 服务中没有调用 OnlocationChanged?

没有使用 fusedLocationAPI.requestLocationUpdates 调用 onLocationChanged