即使我已将OnCheckedChangeListener放在onCreateOptionsMenu和onPrepareOptionsMenu中,但如果我从服务中停用它,交换机只能工作一次。之后,如果我再次打开它,没有任何反应。
在MainActivity中:
@Override
public boolean onCreateOptionsMenu(Menu mMenu) {
getMenuInflater().inflate(R.menu.menu, mMenu);
switchlistener(mMenu);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
mMenu = menu;
switchlistener(mMenu);
return super.onPrepareOptionsMenu(menu);
}
方法:
private void switchlistener(Menu mMenu) {
MenuItem appBarSwitch = mMenu.findItem(R.id.app_bar_switch);
appBarSwitch.setActionView(R.layout.switch_item);
mSwitch = mMenu.findItem(R.id.app_bar_switch).getActionView().findViewById(R.id.action_switch);
mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if (isChecked) {
Toast.makeText(MainActivity.this, "Fired up!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), BroadcastReceiverService.class);
startService(intent);
} else {
Intent intent = new Intent(getApplicationContext(), BroadcastReceiverService.class);
stopService(intent);
}
}
});
}
在服务类:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction() != null && intent.getAction().equals("SWITCH OFF")) {
stopForeground(true);
stopSelf();
Menu menu = MainActivity.getThis().getMenu();
MenuItem appBarSwitch = menu.findItem(R.id.app_bar_switch);
appBarSwitch.setActionView(R.layout.switch_item);
appBarSwitch.setChecked(false);
} else {
Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();
}
return START_NOT_STICKY;
}
感谢您的帮助!
答案 0 :(得分:1)
对于记录,答案是将我的switchListener方法放在OnStartCommand中。这样,它再次被调用。
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction() != null && intent.getAction().equals("SWITCH OFF")) {
stopForeground(true);
stopSelf();
Menu menu = MainActivity.getThis().getMenu();
MenuItem appBarSwitch = menu.findItem(R.id.app_bar_switch);
appBarSwitch.setActionView(R.layout.switch_item);
appBarSwitch.setChecked(false);
Switch mSwitch = menu.findItem(R.id.app_bar_switch).getActionView().findViewById(R.id.action_switch);
mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if (isChecked) {
Intent intent = new Intent(getApplicationContext(), BroadcastReceiverService.class);
startService(intent);
} else {
Intent intent = new Intent(getApplicationContext(), BroadcastReceiverService.class);
stopService(intent);
}
}
});
} else {
Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();
}
return START_NOT_STICKY;
}