如何在React Native Android应用中自动启用和禁用离线模式
Hey there! Great question—React Native doesn’t come with a built-in API to directly toggle Android’s offline mode out of the box, but you can absolutely pull this off by bridging to native Android code. Since controlling network state is a system-level operation, we’ll need to create a native module to access Android’s underlying APIs. Let me break down the two most common scenarios for you:
Airplane mode disables all network connections (Wi-Fi, mobile data, Bluetooth, etc.) for a complete offline state. Note that starting from Android 4.2, regular apps need special permissions to modify this setting.
Step 1: Add Required Permissions
Open android/app/src/main/AndroidManifest.xml and add these permissions inside the <manifest> tag:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.WRITE_SETTINGS" />
The WRITE_SETTINGS permission is a special one—users have to manually grant your app permission to "modify system settings" through Android’s settings menu.
Step 2: Create the Android Native Module
Create a new Java class (e.g., NetworkModule.java) in your app’s package directory (like com/yourappname/):
package com.yourappname; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import android.provider.Settings; import android.content.Intent; import android.net.Uri; import android.os.Build; public class NetworkModule extends ReactContextBaseJavaModule { public NetworkModule(ReactApplicationContext reactContext) { super(reactContext); } @Override public String getName() { // This is the name React Native will use to access the module return "NetworkModule"; } // Check if we have permission to modify system settings @ReactMethod public boolean hasWriteSettingsPermission() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { return Settings.System.canWrite(getReactApplicationContext()); } // Pre-Marshmallow devices grant this permission by default return true; } // Prompt user to grant system settings modification permission @ReactMethod public void requestWriteSettingsPermission() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS); intent.setData(Uri.parse("package:" + getReactApplicationContext().getPackageName())); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); getReactApplicationContext().startActivity(intent); } } // Toggle airplane mode on/off @ReactMethod public void toggleAirplaneMode() { if (!hasWriteSettingsPermission()) { requestWriteSettingsPermission(); return; } // Check current airplane mode state boolean isAirplaneModeEnabled = Settings.Global.getInt( getReactApplicationContext().getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0 ) == 1; // Flip the state Settings.Global.putInt( getReactApplicationContext().getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, isAirplaneModeEnabled ? 0 : 1 ); // Send broadcast to notify system of the state change Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED); intent.putExtra("state", !isAirplaneModeEnabled); getReactApplicationContext().sendBroadcast(intent); } }
Step 3: Register the Native Module
Create a package class (e.g., NetworkPackage.java) to register your module:
package com.yourappname; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class NetworkPackage implements ReactPackage { @Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { List<NativeModule> modules = new ArrayList<>(); modules.add(new NetworkModule(reactContext)); return modules; } @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { return Collections.emptyList(); } }
Then open MainApplication.java and add the package to the getPackages() method:
@Override protected List<ReactPackage> getPackages() { @SuppressWarnings("UnnecessaryLocalVariable") List<ReactPackage> packages = new PackageList(this).getPackages(); packages.add(new NetworkPackage()); // Add this line to register your module return packages; }
Step 4: Call the Module from React Native
Now you can access the module in your React Native code:
import { NativeModules } from 'react-native'; const { NetworkModule } = NativeModules; // Function to toggle offline mode via airplane mode const toggleFullOfflineMode = async () => { const hasPermission = await NetworkModule.hasWriteSettingsPermission(); if (!hasPermission) { // Prompt user to grant permission if we don't have it NetworkModule.requestWriteSettingsPermission(); return; } // Toggle airplane mode NetworkModule.toggleAirplaneMode(); };
If you don’t need full airplane mode, you can control Wi-Fi or mobile data separately.
Toggle Wi-Fi
Add Permissions
Add these to your AndroidManifest.xml:
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Add Method to Native Module
Add this method to your NetworkModule.java:
import android.content.Context; import android.net.wifi.WifiManager; // ... existing code ... @ReactMethod public void toggleWifi() { WifiManager wifiManager = (WifiManager) getReactApplicationContext().getSystemService(Context.WIFI_SERVICE); if (wifiManager != null) { // Flip Wi-Fi state wifiManager.setWifiEnabled(!wifiManager.isWifiEnabled()); } }
Call from React Native
NetworkModule.toggleWifi();
Toggle Mobile Data (Note Android Version Limits)
- Android 9 and below: You can use
TelephonyManager.setDataEnabled()with theCHANGE_NETWORK_STATEpermission, but this method is deprecated in Android 10+. - Android 10+: Regular apps can no longer directly control mobile data. Your best bet is to redirect users to the system settings page:
Add this method to yourNetworkModule.java:
import android.provider.Settings; // ... existing code ... @ReactMethod public void openMobileDataSettings() { Intent intent = new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); getReactApplicationContext().startActivity(intent); }
Call it from React Native:
NetworkModule.openMobileDataSettings();
- Permissions are critical: Android’s security model restricts system-level operations, so always handle permission checks and requests gracefully.
- Version compatibility: API changes across Android versions mean some methods won’t work on newer devices—make sure to add version checks in your native code.
- User experience: Modifying network state can disrupt the user’s workflow. Always inform users why you’re making the change and only do it when necessary.
内容的提问来源于stack exchange,提问作者Hussian Shaik




