How to time out GPS signal acquisition

前端 未结 3 518
抹茶落季
抹茶落季 2020-12-14 23:20

My app uses the LocationListener to get one position fix and then removeUpdates() once every minute (to conserve battery). The problem is that if a user moves i

3条回答
  •  暖寄归人
    2020-12-15 00:08

    Well my solution to this problem is somewhat very simple and I don't know if it's good practice. Let's assume we have a long named timeToQuit that determines how many millis you wanna wait before aborting the search for a position just put:

    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 
                                  2000, 0, locationListener);
    Handler handler = new Handler();    // android.os.Handler
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            locationManager.removeUpdates(locationListener);
        }
    };
    handler.postDelayed(runnable, timeToQuit);
    

    Of course you have to have a LocationListener and your own LocationListener. Values in locationManager.requestLocationUpdates are from my app so you propapbly should adapt them. This code works like a charm for me. I know I'm a little late, but I couldn't find this approach anywhere and propably it helps someone. Cheers

提交回复
热议问题