onLocationChanged 未被调用

Posted

技术标签:

【中文标题】onLocationChanged 未被调用【英文标题】:onLocationChanged not being called 【发布时间】:2019-02-07 05:32:30 【问题描述】:

我的 android 应用程序出现问题,我无法检索设备的当前位置。从调试应用来看,我的 LocationListener 中的 onLocationChange 似乎没有触发。 我已设置 requestLocationUpdates 以与我的 LocationListener 一起使用,并在 onLocationChange 中向日志输出,但我什么也没收到。 我还注意到,当我使用该应用程序时,手机的顶部栏中没有出现 GPS 图标,但如果我切换到 Google 地图应用程序,该图标会立即出现...我'在这一点上正在努力解决这个问题,所以任何帮助都将不胜感激。谢谢。

MapFragment.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_
android:layout_
tools:context=".MapFragment" />

【问题讨论】:

尝试使用 FusedLocationApiClient 代替位置管理器 这可能对你有帮助github.com/kdblue/GetMyCurrentLocation 【参考方案1】:

你确定locationManager.requestLocationUpdates() 正在执行吗?根据此代码,如果在启动时已授予 ACCESS_FINE_LOCATION,checkLocationPermission() 将返回 true,并且不会调用 requestLocationUpdates()

【讨论】:

不完全确定,不。我想你可能会有所作为。回家后我会进行调试,看看是否真的调用过 .requestLocationUpdates()。 感谢您的回答! 抱歉,来晚了。有一段时间没有从事这个项目了,但这正是正在发生的事情! if 语句直接放入 else 中,从不调用代码。感谢您的帮助!

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

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

在 Android 中未调用 onlocationchanged

onLocationChanged没有被调用

onLocationChanged 只调用一次,不刷新

在 Android 设备上未调用 onLocationChanged()

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