如何在 android 中检测整个应用程序的飞行模式

How to detect airplane mode on whole application in android

我正在开发一个 Android 应用程序,它将在整个应用程序中检测飞行模式。我在哪里添加此代码?

@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;
    }       
}

您可以在要检测连接是否可用的地方添加此代码。

例如:

@Override
    public void onClick(View v) {
boolean isonair = myApp.isAirplaneModeOn(this);
Toast.makeText(this, "IS on AIR? " + isonair, Toast.LENGTH_LONG).show();
}

如果您想访问静态函数,请在应用程序中使用它们 class:

public class myApp extends Application {
public static function isAirplaneModeOn() {
...
}
}

在任何 activity 中使用此访问权限:myApp.isAirplaneModeOn()

别忘了更新你的 AndroidManifest.xml:

<application
        android:largeHeap="true"
        android:name=".myApp" <<<<<<<<<<<<<<<<<<< this is your class name
        android:icon="@drawable/somedrawable"
        android:label="@string/app_alias"
        android:theme="@style/AppTheme" >

创建一个类似 AirplaneModeManager 的接口,其实现扩展 广播接收器 以在激活飞行模式的情况下得到通知

您可以在实现中使用此代码来跟踪并在整个应用程序中使用它的方法来获取状态!!