我有一个屏幕(活动),它执行以下操作:它有一个切换飞行模式的切换按钮;它通过使用产生新线程的服务来实现。它还有一个按钮,以完全相同的方式执行完全相同的操作。正如下面的代码片段所示,真的没有什么花哨的。虽然切换按钮的一切都按预期工作(如果当前手机未处于飞行模式,飞行模式将变为“开启”;如果当前处于飞行模式,则变为“关闭”),当单击按钮时,飞行模式会连续切换(飞行模式从“开”切换到“关”,然后再切换回“开”,然后再切换到“关”……)就好像它陷入了一个循环一样。在网上查了一些资料后,我怀疑这与在 Android 中触发电话/服务状态的意图/广播接收器的方式有关;因为切换按钮有两种状态,有效地阻止了意图再次被广播。它是否正确??如果是这样,使用按钮(与单选按钮或切换按钮相比)切换飞行模式的正确方法是什么?
/** Handler for the button. */
runToggleAirplaneModeServiceBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startService(new Intent(SleepScheduleController.this, AirplaneModeService.class));
}
});
/** Handler for the toggle button. */
airplaneModeToggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
startService(new Intent(SleepScheduleController.this, AirplaneModeService.class));
}
});
/** In the same screen as the toggle button and the button.
* Need this to update the state of the toggle button once
* the toggling command is executed.
*/
intentFilter = new IntentFilter("android.intent.action.SERVICE_STATE");
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
displayAirplaneMode();
}};
registerReceiver(receiver, intentFilter);
private void displayAirplaneMode() {
if(airplaneModeToggler.isInAirplaneMode()){
airplaneModeToggleButton.setChecked(true);
airplaneModeTextView.setText(R.string.airplane_mode_on);
}else{
airplaneModeToggleButton.setChecked(false);
airplaneModeTextView.setText(R.string.airplane_mode_off);
}
}
/** Code snippet in AirplaneModeService*/
@Override
public void onCreate() {
airplaneModeToggler = new AirplaneModeToggler(this);
Thread mThread = new Thread(null, airplaneModeToggleTask, "AirplaneModeToggleTask");
mThread.start();
}
private Runnable airplaneModeToggleTask = new Runnable() {
@Override
public void run() {
airplaneModeToggler.toggle(null);
AirplaneModeService.this.stopSelf();
}
};
/** Code snippet in the Utility class used by AirplaneModeService.*/
public Boolean toggleAirplaneMode(Boolean enabling) {
boolean _enabling = enabling == null ? !isInAirplaneMode() : enabling.booleanValue();
Settings.System.putInt(mContext.getContentResolver(),
Settings.System.AIRPLANE_MODE_ON,
_enabling ? AIRPLANE_MODE_ON : AIRPLANE_MODE_OFF);
Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
intent.putExtra("state", _enabling);
mContext.sendBroadcast(intent);
return _enabling;
}