如何在Android上检测飞行模式?

我的应用程序中有用于检测Wi-Fi是否已主动连接的代码。如果启用飞行模式,则该代码将触发RuntimeException。无论如何,我想在此模式下显示单独的错误消息。如何可靠地检测Android设备是否处于飞行模式?



智慧大石
浏览 577回答 3
3回答

白猪掌柜的

/*** 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;}

叮当猫咪

通过扩展Alex的答案以包括SDK版本检查,我们可以:/**&nbsp;* Gets the state of Airplane Mode.&nbsp;*&nbsp;&nbsp;* @param context&nbsp;* @return true if enabled.&nbsp;*/@SuppressWarnings("deprecation")@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)public static boolean isAirplaneModeOn(Context context) {&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {&nbsp; &nbsp; &nbsp; &nbsp; return Settings.System.getInt(context.getContentResolver(),&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Settings.System.AIRPLANE_MODE_ON, 0) != 0;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; return Settings.Global.getInt(context.getContentResolver(),&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Settings.Global.AIRPLANE_MODE_ON, 0) != 0;&nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp;}

蝴蝶不菲

而且,如果您不想轮询“飞行模式”是否处于活动状态,则可以为SERVICE_STATE Intent注册一个BroadcastReceiver并对其做出反应。在您的ApplicationManifest(Android 8.0之前的版本)中:<receiver android:enabled="true" android:name=".ConnectivityReceiver">&nbsp; &nbsp; <intent-filter>&nbsp; &nbsp; &nbsp; &nbsp; <action android:name="android.intent.action.AIRPLANE_MODE"/>&nbsp; &nbsp; </intent-filter></receiver>或以编程方式(所有Android版本):IntentFilter intentFilter = new IntentFilter("android.intent.action.AIRPLANE_MODE");BroadcastReceiver receiver = new BroadcastReceiver() {&nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; public void onReceive(Context context, Intent intent) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Log.d("AirplaneMode", "Service state changed");&nbsp; &nbsp; &nbsp; }};context.registerReceiver(receiver, intentFilter);并且,如其他解决方案中所述,您可以在收到通知时轮询飞行模式,并抛出异常。
打开App,查看更多内容
随时随地看视频慕课网APP