android check if user turned off location

后端 未结 3 410
谎友^
谎友^ 2020-12-21 13:30

I am building an application in which I have to constantly save user\'s location and then send it to the server. For that, I am using FusedLocationApis in a service. For the

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-21 14:11

    You can use location state changed receiver to know when user manually turns of location GpsReceiver.java

    public class GpsReceiver extends BroadcastReceiver {
        private final LocationCallBack locationCallBack;
    
        /**
         * initializes receiver with callback
         * @param iLocationCallBack Location callback
         */
        public GpsReceiver(LocationCallBack iLocationCallBack){
                this.locationCallBack = iLocationCallBack;
        }
    
        /**
         * triggers on receiving external broadcast
         * @param context Context
         * @param intent Intent
         */
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
                locationCallBack.onLocationTriggered();
            }
        }
    }
    

    Create an interface to communicate GPS changes to Activity

    public interface LocationCallBack {
        /**
         * on Location switch triggered
         */
        void onLocationTriggered();
    }
    

    Register receiver in onCreate() of Activity to start listening to GPS state changes

    public void onCreate(Bundle savedInstance){
    //---
    registerReceiver(new GpsReceiver(new LocationCallBack() {
                @Override
                public void onLocationTriggered() {
                    //Location state changed
                }
            }), new IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION));
    //---
    }
    

提交回复
热议问题