アプリケーションにWi-Fiがアクティブに接続されているかどうかを検出するコードがあります。機内モードが有効になっている場合、そのコードはRuntimeExceptionをトリガーします。とにかく、このモードのときに別のエラーメッセージを表示したいと思います。Androidデバイスが機内モードかどうかを確実に検出するにはどうすればよいですか?
アプリケーションにWi-Fiがアクティブに接続されているかどうかを検出するコードがあります。機内モードが有効になっている場合、そのコードはRuntimeExceptionをトリガーします。とにかく、このモードのときに別のエラーメッセージを表示したいと思います。Androidデバイスが機内モードかどうかを確実に検出するにはどうすればよいですか?
回答:
/**
* Gets the state of Airplane Mode.
* 
* @param context
* @return true if enabled.
*/
private static boolean isAirplaneModeOn(Context context) {
   return Settings.System.getInt(context.getContentResolver(),
           Settings.Global.AIRPLANE_MODE_ON, 0) != 0;
}Settings.Global。
                    android.intent.action.AIRPLANE_MODEモードの変更が完了するまでに時間がかかるため、これがintentに応じて呼び出したときに不確定な結果をもたらしました。チェックするIntent.ACTION_AIRPLANE_MODE_CHANGEDそれを行うかどうかをてください。
                    アレックスの回答を拡張してSDKバージョンチェックを含めることにより、次のようになります。
/**
 * Gets the state of Airplane Mode.
 * 
 * @param context
 * @return true if enabled.
 */
@SuppressWarnings("deprecation")
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public static boolean isAirplaneModeOn(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) != 0;          
    } else {
        return Settings.Global.getInt(context.getContentResolver(), 
                Settings.Global.AIRPLANE_MODE_ON, 0) != 0;
    }       
}@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)メソッドの前に追加しない限り、Eclipseはこれをコンパイルしません。
                    また、機内モードがアクティブかどうかをポーリングしない場合は、SERVICE_STATEインテントのBroadcastReceiverを登録して、それに反応できます。
ApplicationManifest(Android 8.0より前)のいずれか:
<receiver android:enabled="true" android:name=".ConnectivityReceiver">
    <intent-filter>
        <action android:name="android.intent.action.AIRPLANE_MODE"/>
    </intent-filter>
</receiver>またはプログラムで(すべてのAndroidバージョン):
IntentFilter intentFilter = new IntentFilter("android.intent.action.AIRPLANE_MODE");
BroadcastReceiver receiver = new BroadcastReceiver() {
      @Override
      public void onReceive(Context context, Intent intent) {
            Log.d("AirplaneMode", "Service state changed");
      }
};
context.registerReceiver(receiver, intentFilter);また、他のソリューションで説明されているように、受信者に通知されたときに機内モードをポーリングして例外をスローできます。
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED);/<action android:name="android.intent.action.AIRPLANE_MODE" />
                    boolean isPlaneModeOn = intent.getBooleanExtra("state", false);  ブール値isPlaneModeOnはtrue、ユーザーが飛行機モードをオンにした場合、またはfalseオフにした場合
                    機内モードBroadcastReceiver(@saxos回答)を登録するとき、やIntent Extrasを呼び出さないようにするために、からすぐに機内モード設定の状態を取得することは非常に理にかなっていると思います。Settings.GlobalSettings.System
@Override
public void onReceive(Context context, Intent intent) {
    boolean isAirplaneModeOn = intent.getBooleanExtra("state", false);
    if(isAirplaneModeOn){
       // handle Airplane Mode on
    } else {
       // handle Airplane Mode off
    }
}減価償却の不満を取り除くために(API17 +を対象とし、下位互換性をあまり気にしない場合)、以下と比較する必要がありSettings.Global.AIRPLANE_MODE_ONます。
/** 
 * @param Context context
 * @return boolean
**/
private static boolean isAirplaneModeOn(Context context) {
   return Settings.System.getInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) != 0);
}より低いAPIを検討する場合:
/** 
 * @param Context context
 * @return boolean
**/
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
@SuppressWarnings({ "deprecation" })
private static boolean isAirplaneModeOn(Context context) {
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1){
        /* API 17 and above */
        return Settings.Global.getInt(context.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0) != 0;
    } else {
        /* below */
        return Settings.System.getInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) != 0;
    }
}オレオでは、機内モードのBroadCastReceiverを使用しないでください。それは暗黙の意図です。削除されました。これが現在の例外リストです。現在リストに含まれていないため、データの受信に失敗するはずです。死んだと考えてください。
上記の別のユーザーが述べたように、次のコードを使用します。
 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    @SuppressWarnings({ "deprecation" })
    public static boolean isAirplaneModeOn(Context context) {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1){
        /* API 17 and above */
            return Settings.Global.getInt(context.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0) != 0;
        } else {
        /* below */
            return Settings.System.getInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) != 0;
        }
    }マニフェストコード:
<receiver android:name=".airplanemodecheck" android:enabled="true"
 android:exported="true">
  <intent-filter>
     <action android:name="android.intent.action.AIRPLANE_MODE"></action>
  </intent-filter>
</receiver>Javaコード:Broadcast Receiver Javaファイル
if(Settings.System.getInt(context.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0)== 0)
{
  Toast.makeText(context, "AIRPLANE MODE Off", Toast.LENGTH_SHORT).show();
}
else
{
 Toast.makeText(context, "AIRPLANE MODE On", Toast.LENGTH_SHORT).show();
}Javaコード:アクティビティJavaファイル
インターネットにアクセスするときに飛行機のチェックモードがオンまたはオフになっているなど、アクティビティが開いているときにのみアクションを実行する場合は、マニフェストにコードを追加する必要がないアプリケーションオープンでブロードキャストレシーバーを登録します。
airplanemodecheck reciver;
@Override
protected void onResume() {
   super.onResume();
   IntentFilter intentFilter = new IntentFilter();
   intentFilter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
   reciver = new airplanemodecheck();
   registerReceiver(reciver, intentFilter);
}
@Override
protected void onStop() {
  super.onStop();
  unregisterReceiver(reciver);
}Javaコード:Broadcast Receiver Javaファイル
if(Settings.System.getInt(context.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0)== 0)
{
  Toast.makeText(context, "AIRPLANE MODE Off", Toast.LENGTH_SHORT).show();
}
else
{
 Toast.makeText(context, "AIRPLANE MODE On", Toast.LENGTH_SHORT).show();
}役立つかもしれないこのクラスを書いた。機内モードが有効か無効かを示すブール値を直接返しませんが、機内モードが変更されたときに通知します。
public abstract class AirplaneModeReceiver extends BroadcastReceiver {
    private Context context;
    /**
     * Initialize tihe reciever with a Context object.
     * @param context
     */
    public AirplaneModeReceiver(Context context) {
        this.context = context;
    }
    /**
     * Receiver for airplane mode status updates.
     *
     * @param context
     * @param intent
     */
    @Override
    public void onReceive(Context context, Intent intent) {
        if(Settings.System.getInt(
                context.getContentResolver(),
                Settings.Global.AIRPLANE_MODE_ON, 0
        ) == 0) {
            airplaneModeChanged(false);
        } else {
            airplaneModeChanged(true);
        }
    }
    /**
     * Used to register the airplane mode reciever.
     */
    public void register() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
        context.registerReceiver(this, intentFilter);
    }
    /**
     * Used to unregister the airplane mode reciever.
     */
    public void unregister() {
        context.unregisterReceiver(this);
    }
    /**
     * Called when airplane mode is changed.
     *
     * @param enabled
     */
    public abstract void airplaneModeChanged(boolean enabled);
}使用法
// Create an AirplaneModeReceiver
AirplaneModeReceiver airplaneModeReceiver;
@Override
protected void onResume()
{
    super.onResume();
    // Initialize the AirplaneModeReceiver in your onResume function
    // passing it a context and overriding the callback function
    airplaneModeReceiver = new AirplaneModeReceiver(this) {
        @Override
        public void airplaneModeChanged(boolean enabled) {
            Log.i(
                "AirplaneModeReceiver",
                "Airplane mode changed to: " + 
                ((active) ? "ACTIVE" : "NOT ACTIVE")
            );
        }
    };
    // Register the AirplaneModeReceiver
    airplaneModeReceiver.register();
}
@Override
protected void onStop()
{
    super.onStop();
    // Unregister the AirplaneModeReceiver
    if (airplaneModeReceiver != null)
        airplaneModeReceiver.unregister();
}これが私のために働いた唯一のものです(API 27):
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
this.registerReceiver(br, filter);brBroadcastReceiverはどこにありますか。私は今の許可の最近の変化との両方のことを信じているConnectivityManager.CONNECTIVITY_ACTIONし、Intent.ACTION_AIRPLANE_MODE_CHANGED必要とされています。
Jelly Bean(ビルドコード17)以降、このフィールドはグローバル設定に移動されました。したがって、最高の互換性と堅牢性を実現するには、両方のケースに対応する必要があります。次の例はKotlinで記述されています。
fun isInAirplane(context: Context): Boolean {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        Settings.Global.getInt(
            context.contentResolver, Settings.Global.AIRPLANE_MODE_ON, 0
        )
    } else {
        Settings.System.getInt(
            context.contentResolver, Settings.System.AIRPLANE_MODE_ON, 0
        )
    } != 0
}注:Jelly Beanより前のバージョンのサポートを維持しない場合は、if節を省略できます。
を参照しているときに得られる値Settings.System.AIRPLANE_MODE_ONは、[グローバル]の下にある値と同じです。*
    /**
     * @deprecated Use {@link android.provider.Settings.Global#AIRPLANE_MODE_ON} instead
     */
    @Deprecated
    public static final String AIRPLANE_MODE_ON = Global.AIRPLANE_MODE_ON;これは、前のコードのjelly beanバージョンです。
fun isInAirplane(context: Context): Boolean {
    return Settings.Global.getInt(
        context.contentResolver, Settings.Global.AIRPLANE_MODE_ON, 0
    ) != 0
}インターネットがオンになっているかどうかを確認できます
public class ConnectionDetector {
private Context _context;
public ConnectionDetector(Context context){
    this._context = context;
}
public boolean isConnectingToInternet(){
    ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
      if (connectivity != null)
      {
          NetworkInfo[] info = connectivity.getAllNetworkInfo();
          if (info != null)
              for (int i = 0; i < info.length; i++)
                  if (info[i].getState() == NetworkInfo.State.CONNECTED)
                  {
                      return true;
                  }
      }
      return false;
}}