How to? Listen for Location Setting being turned ON (Android App)

后端 未结 3 1449
借酒劲吻你
借酒劲吻你 2021-01-02 02:30

So I\'ve spent the past few weeks working on my Android App and looking into the best way of implementing what I need to do, but still can\'t quite get it right.. Any/all he

3条回答
  •  盖世英雄少女心
    2021-01-02 03:32

    Here is a solution using dynamic registration:

    In your fragment or activity's onResume() method, listen to changes in LocationManager.PROVIDERS_CHANGED_ACTION

    IntentFilter filter = new IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION);
    filter.addAction(Intent.ACTION_PROVIDER_CHANGED);
    mActivity.registerReceiver(gpsSwitchStateReceiver, filter);
    

    Here is a code sample for the gpsSwitchStateReceiver object:

    private BroadcastReceiver gpsSwitchStateReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
    
    
                if (LocationManager.PROVIDERS_CHANGED_ACTION.equals(intent.getAction())) {
                    // Make an action or refresh an already managed state.
    
                    LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
                    boolean isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
                    boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    
                    if (isGpsEnabled || isNetworkEnabled) {
                        Log.i(this.getClass().getName(), "gpsSwitchStateReceiver.onReceive() location is enabled : isGpsEnabled = " + isGpsEnabled + " isNetworkEnabled = " + isNetworkEnabled);
                    } else {
                        Log.w(this.getClass().getName(), "gpsSwitchStateReceiver.onReceive() location disabled ");
                    }
                }
            }
        };
    

    In your onPause() method, unregister the receiver

    mActivity.unregisterReceiver(gpsSwitchStateReceiver);
    

提交回复
热议问题