1

I have a done button in my app which I would like to disable when I switch to airplane mode. I have working code for the same in my app. However, it doesn't disable as soon as I switch my app to airplane mode. It disables only when I switch to some other view and then return to this view. Is there a way I can instantly disable it, the moment my app detects offline mode? Here's my code so far:

  private static boolean isAirplaneModeOn(Context context) {

            return Settings.System.getInt(context.getContentResolver(),
                    Settings.System.AIRPLANE_MODE_ON, 0) != 0;

        }

In my oncreateview, I have:

if(isAirplaneModeOn(Application.getAppContext())){
            Toast toast = Toast.makeText(this.getActivity(),getResources().getString(R.string.offline), Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
            mDoneBtn.setActivated(false);
            mDoneBtn.setTextColor(Color.DKGRAY);
            mDoneBtn.setOnClickListener(null);

        }else {
            mDoneBtn.setOnClickListener(this);
        }

Is there any other way of doing this which is better? or can this be improved to achieve my goal? Any ideas? Thanks!

1 Answers1

2

Why not trying disabling it:

IntentFilter intentFilter = new IntentFilter("android.intent.action.AIRPLANE_MODE");

BroadcastReceiver receiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {
       if (!isAirplaneModeOn(this)) { 
          mDoneBtn.setEnabled(false);
       } else { 
          mDoneBtn.setEnabled(true); 
       } 
  }
 };

context.registerReceiver(receiver, intentFilter);

@Override
public void onDestroy() {
    super.onDestroy();
    unregisterRecievers();
}

private void unregisterRecievers() {
    try {
        unregisterReceiver(receiver);
    } catch (Exception e) {
        e.printStackTrace();
    }


}
Kristy Welsh
  • 7,828
  • 12
  • 64
  • 106
  • that doesn't work for me ,as even with my code i have to go back 1 step and then return to my view to see the done button disabled. Is there any way, that it instantly goes offline, the moment you return to your app view you left from –  Nov 10 '15 at 15:41
  • Edited answer to reflect a broadcast receiver. – Kristy Welsh Nov 10 '15 at 15:55
  • Hi, How do I get my done button to an active state once the user is connected again? where and how do i unregister the receiver? –  Nov 11 '15 at 15:04
  • thanks! unregisterReceiver(receiver) shows as error as undefined. is there something I need to import or change for it to work –  Nov 11 '15 at 15:35
  • 1
    unregisterReceiver was added in API level 1. I don't think you need anything special. – Kristy Welsh Nov 11 '15 at 16:10
  • http://stackoverflow.com/questions/21136464/when-to-use-unregisterreceiver-onpause-ondestroy-or-onstop – Kristy Welsh Nov 11 '15 at 16:12