You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在应用设置中添加开关禁用Mobile Data并保留WiFi使用?

Got it, let's figure out how to build that "Use Mobile Data" toggle you want—one that fully cuts off mobile data while keeping WiFi active, no constant checks required. Since implementation differs between Android and iOS, I’ll walk you through both platforms:

Android Implementation

Required Permissions

First, add these permissions to your AndroidManifest.xml—they’re necessary to modify network state:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />

Note that CHANGE_NETWORK_STATE is a dangerous permission, so you’ll need to request it dynamically from the user at runtime.

Toggle Logic

This code directly enables/disables system-level mobile data—no app-level workarounds. Here’s a Kotlin implementation that works across most Android versions:

private const val REQUEST_CODE_NETWORK_PERMISSION = 1001

// Check if we have the necessary permissions to modify network state
fun hasNetworkPermissions(context: Context): Boolean {
    return ContextCompat.checkSelfPermission(
        context,
        Manifest.permission.CHANGE_NETWORK_STATE
    ) == PackageManager.PERMISSION_GRANTED
}

// Toggle mobile data on or off
fun toggleMobileData(context: Context, enable: Boolean) {
    if (!hasNetworkPermissions(context)) {
        // Request permission if it's not granted yet
        ActivityCompat.requestPermissions(
            context as Activity,
            arrayOf(Manifest.permission.CHANGE_NETWORK_STATE),
            REQUEST_CODE_NETWORK_PERMISSION
        )
        return
    }

    val telephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
    when {
        Build.VERSION.SDK_INT >= Build.VERSION_CODES.O -> {
            // Use the official API for Android 8.0 and above
            telephonyManager.setDataEnabled(enable)
        }
        else -> {
            // Fallback using reflection for older Android versions
            try {
                val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
                val method = connectivityManager.javaClass.getDeclaredMethod(
                    "setMobileDataEnabled",
                    Boolean::class.java
                )
                method.isAccessible = true
                method.invoke(connectivityManager, enable)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
}

Just hook this function up to your switch’s onCheckedChangeListener, and it’ll fully disconnect mobile data when toggled off.

iOS Implementation

iOS restricts apps from modifying system-level settings like mobile data for security reasons, so we have two practical workarounds:

Option 1: Restrict Your App to WiFi Only

If you just want your app to avoid using mobile data (even if it’s enabled system-wide), configure your network sessions to block cellular access:

// For a specific URLSession
let config = URLSessionConfiguration.default
config.allowsCellularAccess = false
let session = URLSession(configuration: config)

// To apply this to your entire app, set the default configuration early in your app's lifecycle
URLSessionConfiguration.default.allowsCellularAccess = false

This ensures your app never uses mobile data, but it doesn’t turn off mobile data system-wide.

Option 2: Guide the User to System Settings

If you need a full system-level mobile data disconnect, you’ll have to direct the user to the iOS Settings app—apps can’t modify this setting directly:

func openMobileDataSettings() {
    guard let settingsURL = URL(string: UIApplication.openSettingsURLString) else { return }
    if UIApplication.shared.canOpenURL(settingsURL) {
        UIApplication.shared.open(settingsURL, options: [:], completionHandler: nil)
    }
}

Trigger this function when the user toggles the switch off, and add a friendly message explaining they need to disable mobile data manually in settings.


内容的提问来源于stack exchange,提问作者Jonas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:08:30