Location returned is null when provider is gps?

前端 未结 3 920
你的背包
你的背包 2020-12-11 08:50

I am trying to retrieve the my current location coordinates in the following piece of code

LocationManager locationManager= (LocationManager) getSystemServic         


        
3条回答
  •  忘掉有多难
    2020-12-11 09:10

    I think the problem is that GPS take a fiew second to syncronice. You must to use a thread. Take this example:

    @Override
    public void run() {
    
        mLocationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
    
        if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            Looper.prepare();
            mToast.Make(getContext(),"GPS",0);
            mLocationListener = new MyLocationListener();
            mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener);
            Looper.loop(); 
            Looper.myLooper().quit(); 
    
        } else if (mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
            Looper.prepare();
            mToast.Make(getContext(),"Triangulacion",0);
            mLocationListener = new MyLocationListener();
            mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mLocationListener);
            Looper.loop();
            Looper.myLooper().quit();
        }else{
            mToast.Make(context,"No se encuentra señal se procede a mandar un mensaje normal",0);
            Looper.prepare();
            handlerNormal.sendEmptyMessage(0);
            Looper.loop();
            Looper.myLooper().quit();
        }   
    
    }
    

    and a Location Listener

    private class MyLocationListener implements LocationListener 
    {
        @Override
        public void onLocationChanged(Location loc) {
            if (loc != null) {
                setCurrentLocation(loc);
                handler.sendEmptyMessage(0);
            }
        }  
    

    //...
    }

提交回复
热议问题