如何在Xamarin.Forms及Android、iOS平台开关飞行模式?
Hey there! Let's walk through how to handle Airplane Mode toggling in Xamarin.Forms. Since this is a platform-specific system feature, we can't do it directly in the shared code—we'll use Xamarin's Dependency Service to implement the functionality separately for Android and iOS.
First, create an interface in your Xamarin.Forms shared project to standardize the methods across platforms:
public interface IAirplaneModeService { // Check if Airplane Mode is currently enabled bool IsAirplaneModeEnabled(); // Toggle Airplane Mode (or open settings if platform restricts direct control) void ToggleAirplaneMode(bool enable); }
Android has different behavior depending on the OS version, so we'll split the logic for pre-Android 10 and Android 10+.
1. Add Permissions
First, add these permissions to your AndroidManifest.xml:
<uses-permission android:name="android.permission.WRITE_SETTINGS" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
2. Implement the Service
Create the platform-specific implementation in your Android project:
[assembly: Dependency(typeof(AirplaneModeService))] namespace YourAppNamespace.Droid { public class AirplaneModeService : IAirplaneModeService { public bool IsAirplaneModeEnabled() { // Read the system setting for Airplane Mode return Settings.System.GetString( Android.App.Application.Context.ContentResolver, Settings.System.AirplaneModeOn) == "1"; } public void ToggleAirplaneMode(bool enable) { if (Build.VERSION.SdkInt >= BuildVersionCodes.Q) { // Android 10+ blocks programmatic toggling—open the Airplane Mode settings page instead var intent = new Intent(Settings.ActionAirplaneModeSettings); intent.AddFlags(ActivityFlags.NewTask); Android.App.Application.Context.StartActivity(intent); } else { // For older Android versions, we can toggle directly if we have permission if (Settings.System.CanWrite(Android.App.Application.Context)) { // Update the system setting Settings.System.PutInt( Android.App.Application.Context.ContentResolver, Settings.System.AirplaneModeOn, enable ? 1 : 0); // Broadcast the change to update the system UI var broadcastIntent = new Intent(Intent.ActionAirplaneModeChanged); broadcastIntent.PutExtra("state", enable); Android.App.Application.Context.SendBroadcast(broadcastIntent); } else { // Request permission to modify system settings var permissionIntent = new Intent(Settings.ActionManageWriteSettings); permissionIntent.SetData(Android.Net.Uri.Parse($"package:{Android.App.Application.Context.PackageName}")); permissionIntent.AddFlags(ActivityFlags.NewTask); Android.App.Application.Context.StartActivity(permissionIntent); } } } } }
iOS enforces strict sandbox restrictions—third-party apps cannot programmatically toggle Airplane Mode. We can only check the current state and redirect users to the system settings page to make changes.
1. Implement the Service
Create the iOS-specific implementation in your iOS project (you'll need to reference the CoreTelephony framework):
[assembly: Dependency(typeof(AirplaneModeService))] namespace YourAppNamespace.iOS { public class AirplaneModeService : IAirplaneModeService { public bool IsAirplaneModeEnabled() { // Read Airplane Mode state from NSUserDefaults return NSUserDefaults.StandardUserDefaults.BoolForKey("AirplaneMode"); } public void ToggleAirplaneMode(bool enable) { // iOS doesn't allow app-controlled toggling—open the Airplane Mode settings page var settingsUrl = new NSUrl("App-Prefs:root=AIRPLANE_MODE"); if (UIApplication.SharedApplication.CanOpenUrl(settingsUrl)) { UIApplication.SharedApplication.OpenUrl(settingsUrl); } else { // Fallback to the app's general settings if the direct URL fails UIApplication.SharedApplication.OpenUrl(new NSUrl(UIApplication.OpenSettingsUrlString)); } } } }
Now you can use the service anywhere in your Xamarin.Forms shared code (e.g., a ViewModel or Page code-behind):
// Get the service instance var airplaneModeService = DependencyService.Get<IAirplaneModeService>(); // Check current Airplane Mode state bool isAirplaneModeOn = airplaneModeService.IsAirplaneModeEnabled(); // Toggle (or open settings, depending on platform) airplaneModeService.ToggleAirplaneMode(!isAirplaneModeOn);
- Android 10+: Google restricted programmatic control of Airplane Mode, so we have to redirect users to the system settings.
- iOS: Apple's sandbox rules prevent any app from modifying Airplane Mode directly—redirecting to settings is the only option.
- Android Permissions: On Android 6.0+, you need to dynamically request the
WRITE_SETTINGSpermission before attempting to modify the setting. - iOS URL Scheme: The
App-Prefs:root=AIRPLANE_MODEURL may be restricted in some iOS versions, so always include the fallback to general settings.
内容的提问来源于stack exchange,提问作者Dmitry

