使用 CheckBoxPreference 切换 phone 声音、振动和互联网访问 On/Off

Toggle phone sound, vibration and internet access On/Off using a CheckBoxPreference

如何使用 Android 中的 CheckBoxPreference 切换整个系统声音、振动、数据连接和 wifi? 当我的应用程序中 activity 为 运行 时,我希望有可能禁用这些东西。

我想通了。

res/xml/preferences.xml 中添加 CheckBoxPreferences:

    <CheckBoxPreference
        android:defaultValue="false"
        android:key="pref_disableSoundAndVibration"
        android:title="Disable sound and vibration" />
    <CheckBoxPreference
        android:defaultValue="false"
        android:key="pref_disableWifi"
        android:title="Disable Wi-Fi" />

在您的 MainActivity 中,添加两个布尔值成员来存储音频和 wifi 复选框状态,并添加一个整数来存储铃声状态(静音、振动、声音)。

protected void onCreate(Bundle savedInstanceState) {
    ...
    mDisableSoundAndVibration = mPref.getBoolean("pref_disableSoundAndVibration", false);
    AudioManager aManager=(AudioManager)getSystemService(AUDIO_SERVICE);
    mRingerMode = aManager.getRingerMode();

    mDisableWifi = mPref.getBoolean("pref_disableWifi", false);
    WifiManager wifiManager  = (WifiManager)this.getSystemService(WIFI_SERVICE);
    mWifiMode = wifiManager.isWifiEnabled();
    ...
    if (savedInstanceState != null) {
        mDisableSoundAndVibration = savedInstanceState.getBoolean("disableSoundAndVibration");
        mDisableWifi = savedInstanceState.getBoolean("disableWifi");
...
}

public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) {
    ...
    mDisableSoundAndVibration = mPref.getBoolean("pref_disableSoundAndVibration", false);
    mDisableWifi = mPref.getBoolean("pref_disableWifi", false);
    ...
}
protected void onSaveInstanceState(Bundle outState) {
    ...
    outState.putBoolean("disableSoundAndVibration", mDisableSoundAndVibration);
    outState.putInt("ringerMode", mRingerMode);
    outState.putBoolean("disableWifi", mDisableWifi);
    ....
}

如果您想暂时关闭声音和wifi并保持初始状态:

    if (mDisableSoundAndVibration){
        AudioManager aManager=(AudioManager)getSystemService(AUDIO_SERVICE);
        aManager.setRingerMode(aManager.RINGER_MODE_SILENT);
            }
    if (mDisableWifi){
        WifiManager wifiManager  = (WifiManager)this.getSystemService(this.WIFI_SERVICE);
        wifiManager.setWifiEnabled(false);
            }

然后恢复初始值:

    if (mDisableSoundAndVibration){
        AudioManager aManager=(AudioManager)getSystemService(AUDIO_SERVICE);
        aManager.setRingerMode(mRingerMode);
    }
    if(mDisableWifi){
        WifiManager wifiManager = (WifiManager)this.getSystemService(WIFI_SERVICE);
        wifiManager.setWifiEnabled(mWifiMode);
    }