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

时间:2011-09-09 05:09:12

标签: android gsm

我想启用/停用Android手机的GSM连接。我需要根据需要禁用/启用呼叫和短信。我怎么能这样做?

2 个答案:

答案 0 :(得分: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权限才能这样做。

答案 1 :(得分: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

EDITS :自原版以来经过大量修改,因为我实际上是在自己的应用中以不同的方式使用它