如何在Android中以编程方式禁用GSM连接

9

我想要启用/禁用安卓手机的GSM连接,需要根据需要禁用/启用电话和短信。我该如何做到这一点?

2个回答

5

编辑:这个解决方案也会关闭wifi、蓝牙等功能...

如果你只想关闭无线电,我认为它与这个问题有关:http://code.google.com/p/android/issues/detail?id=1065我非常悲观,不过好奇其他答案。

请查看博客文章Android: Controlling Airplane Mode

// Toggle airplane mode.
Settings.System.putInt(
      context.getContentResolver(),
      Settings.System.AIRPLANE_MODE_ON, isEnabled ? 0 : 1);

// Post an intent to reload.
Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
intent.putExtra("state", !isEnabled);
sendBroadcast(intent);

isEnabled表示是否启用飞行模式。

但请不要忘记,您需要WRITE_SETTINGS权限才能执行此操作。


当您将手机切换到飞行模式时,您也会关闭Wi-Fi和蓝牙。我认为这不是预期的结果。主要任务是仅抑制GSM连接... - Barmaley
是的,我已经尝试过飞行模式。但那会禁用蓝牙。我只想禁用通话和短信,这可能吗?我已经禁用了GPRS。是否有其他方法可用? - Ram
2
抱歉,你是完全正确的。我认为没有“适当”的解决方案,可以参考http://code.google.com/p/android/issues/detail?id=1065,但如果你有聪明的用户,你可以提示他们菜单(在拨号器中输入*#*#INFO#*#* (##4636##))。我会编辑我的答案。 - Waza_Be

5
/* Toggle airplane mode for 1 of the 4 allowed types
 * type allowed values: cell, wifi, bluetooth, nfc
 */
private void changeRadioComponentEnabled(Context context, String type, boolean radio_component_enabled, boolean reset){     
        // now toggle airplane mode from on to off, or vice versa
        Settings.System.putInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, radio_component_enabled ? 0 : 1);

        // now change system behavior so that only one component is turned off
        // this also affects the future behavior of the system button for toggling air-plane mode. 
        // to reset it in order to maintain the system behavior, set reset to true, otherwise we lazily make sure mobile voice is always on
        Settings.System.putString(context.getContentResolver(), Settings.System.AIRPLANE_MODE_RADIOS, type); 

        // post an intent to reload so the menu button switches to the new state we set
        Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
        intent.putExtra("state", radio_component_enabled ? false : true);
        context.sendBroadcast(intent);

        // revert to default system behavior or not
        if (reset){ Settings.System.putString(context.getContentResolver(), Settings.System.AIRPLANE_MODE_RADIOS, "cell,bluetooth,wifi,nfc"); }
        // if reset to default is not chosen, always enable mobile cell at  least
        // but only if NOT changing the mobile connection...
        else if (type.indexOf("cell") == 0) { Settings.System.putString(context.getContentResolver(), Settings.System.AIRPLANE_MODE_RADIOS, "cell");}
}//end method

自然地,这需要权限 android.permission.WRITE_SETTINGS,对于蓝牙则需要 android.permission.BLUETOOTH_ADMIN。对于NFC,您可能需要使用 android.permission.NFC

我的手机在Settings.System.AIRPLANE_MODE_RADIOS中也有wimax: "cell,bluetooth,wifi,nfc,wimax"。这很令人惊讶,因为这款手机不支持4G WiMax! - pmont

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接