Set airplane mode, must declare the android.Manifest.permission#WRITE_APN_SETTINGS permission in its manifest. - Android Phone

Android examples for Phone:Airplane Mode

Description

Set airplane mode, must declare the android.Manifest.permission#WRITE_APN_SETTINGS permission in its manifest.

Demo Code

/*// w  w w  .j  a  v a2  s  .  co m
 * Copyright (C) 2016 venshine.cn@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.provider.Settings;

public class Main {
  /**
   * Set airplane mode, must declare the
   * {@link android.Manifest.permission#WRITE_APN_SETTINGS} permission in its
   * manifest.
   *
   * @param context
   * @param enable
   * @return
   */
  public static boolean setAirplaneMode(Context context, boolean enable) {
    boolean result = true;
    if (isAirplaneModeOpen(context) != enable) {
      if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
        result = Settings.System.putInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, enable ? 1 : 0);
      } else {
        result = Settings.Global.putInt(context.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
      }
      context.sendBroadcast(new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED));
    }
    return result;
  }

  /**
   * Judge whether airplane is open, must declare the
   * {@link android.Manifest.permission#WRITE_APN_SETTINGS} permission in its
   * manifest.
   *
   * @param context
   * @return true:open, false:close, default:close
   */
  public static boolean isAirplaneModeOpen(Context context) {
    return getAirplaneMode(context) == 1 ? true : false;
  }

  /**
   * Get airplane mode, must declare the
   * {@link android.Manifest.permission#WRITE_APN_SETTINGS} permission in its
   * manifest.
   *
   * @param context
   * @return 1:open, 0:close, default:close
   */
  public static int getAirplaneMode(Context context) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
      return Settings.System.getInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0);
    } else {
      return Settings.Global.getInt(context.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0);
    }
  }
}

Related Tutorials