开关只工作一次



即使我已经将我的OnCheckedChangeListener放在onCreateOptionsMenu和onPrepareOptionsMenu中,当我从我的服务中停用它时,开关只能工作一次。之后,如果我再次打开它,什么都不会发生。

在主活动中:

@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;
}

感谢您的任何帮助!

为了记录,答案是将我的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;
}

最新更新