从broadcastreceiver android切换状态

时间:2013-07-02 14:51:05

标签: android broadcastreceiver oncreate onresume togglebutton

我有一个切换,当BATTERY_LOW为真时关闭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写一些东西,但我不知道什么时候我使用BroadcastReceiver。我想我必须检查COMPONENT_ENABLED_STATE_DISABLED或{ {1}}对吗?。有人可以帮帮我吗?感谢

1 个答案:

答案 0 :(得分: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);