0

我有一个开关,当 BATTERY_LOW 为 true 时会关闭 wifi:

public void getToggle(View view) { 
    // Is the toggle on?
   boolean on = ((ToggleButton) view).isChecked(); 
    if (on) {
            PackageManager pm = getPackageManager();
    ComponentName compName = 
    new ComponentName(getApplicationContext(), 
        LowBatteryReceiver.class);
        pm.setComponentEnabledSetting(
        compName,
        PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 
        PackageManager.DONT_KILL_APP);
    } else {                
           PackageManager pm = getPackageManager();
           ComponentName compName = 
           new ComponentName(getApplicationContext(), 
           LowBatteryReceiver.class);
           pm.setComponentEnabledSetting(
           compName,
           PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 
           PackageManager.DONT_KILL_APP);           
      }
    }

这里的wifi代码:

public class LowBatteryReceiver extends BroadcastReceiver {

    public void onReceive(Context context, Intent intent) {
        wifiManager = (WifiManager) MainActivity.this.getSystemService(Context.WIFI_SERVICE); 
                        wifiManager.setWifiEnabled(false);
    }
}


public class OkBatteryReceiver extends BroadcastReceiver {

    public void onReceive(Context context, Intent intent) {
        wifiManager = (WifiManager) MainActivity.this.getSystemService(Context.WIFI_SERVICE); 
                        wifiManager.setWifiEnabled(true);
    }
}

当我离开我的应用程序并再次打开它时,我如何“记住”切换的选择?我知道我必须在其中写一些东西,onResumeonCreate我不知道当我使用广播接收器时会发生什么。我想我必须检查一下是否COMPONENT_ENABLED_STATE_DISABLED正确COMPONENT_ENABLED_STATE_ENABLED?有人可以帮助我吗?谢谢

4

1 回答 1

0

我建议您阅读有关在 Android 中保存数据的信息:http: //developer.android.com/training/basics/data-storage/index.html

//set Preference
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();

//get Preference
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);
于 2013-07-02T16:07:42.543 回答