How can I check the current status of the GPS receiver?

前端 未结 17 1778
时光取名叫无心
时光取名叫无心 2020-11-22 08:53

How can I check the current status of the GPS receiver? I already checked the LocationListener onStatusChanged method but somehow it seems that is not working,

17条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-22 09:47

    If you do not need an update on the very instant the fix is lost, you can modify the solution of Stephen Daye in that way, that you have a method that checks if the fix is still present.

    So you can just check it whenever you need some GPS data and and you don't need that GpsStatus.Listener.

    The "global" variables are:

    private Location lastKnownLocation;
    private long lastKnownLocationTimeMillis = 0;
    private boolean isGpsFix = false;
    

    This is the method that is called within "onLocationChanged()" to remember the update time and the current location. Beside that it updates "isGpsFix":

    private void handlePositionResults(Location location) {
            if(location == null) return;
    
            lastKnownLocation = location;
            lastKnownLocationTimeMillis = SystemClock.elapsedRealtime();
    
            checkGpsFix(); // optional
        }
    

    That method is called whenever I need to know if there is a GPS fix:

    private boolean checkGpsFix(){
    
        if (SystemClock.elapsedRealtime() - lastKnownLocationTimeMillis < 3000) {
            isGpsFix = true;
    
        } else {
            isGpsFix = false;
            lastKnownLocation = null;
        }
        return isGpsFix;
    }
    

    In my implementation I first run checkGpsFix() and if the result is true I use the variable "lastKnownLocation" as my current position.

提交回复
热议问题