我正在尝试编写一个简单的应用程序,它将更改 Android(我的版本是 2.3.3)设置,但我有一些问题。我的 API 级别是 10,所以我使用 System.Secure,因为 Settings.System 已弃用,而 Settings.Global 在较新的 API 中。
当我使用此代码时,应用程序崩溃:(:
public class OnOff extends Activity {
TextView msg;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//buttonLED = (ToggleButton) findViewById(R.id.toggleButton);
ToggleButton toggle = (ToggleButton) findViewById(R.id.toggleButton);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// The toggle is enabled
Settings.Secure.putInt(getContentResolver(), Settings.Secure.WIFI_ON, 1);
} else {
// The toggle is disabled
Settings.Secure.putInt(getContentResolver(), Settings.Secure.WIFI_ON, 0);
}
}
});
}
}
当然我在清单中使用权限
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
我也用 android:onClick="toggle" 尝试了这段代码,但它也不起作用:/
public class OnOff extends Activity {
TextView msg;
private ToggleButton buttonLED;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void toggle(View v){
if(buttonLED.isChecked()){
Toast.makeText(OnOff.this, "Setting ON", Toast.LENGTH_SHORT).show();
Settings.Secure.putInt(getContentResolver(), Settings.Secure.WIFI_ON, 1);
}
else{
Toast.makeText(OnOff.this, "Setting OFF", Toast.LENGTH_SHORT).show();
Settings.Secure.putInt(getContentResolver(), Settings.Secure.WIFI_ON, 0);
}
}
}
有谁知道如何使它工作?