我已切换bottun以在MainActivity
和Map
活动的操作栏中显示服务状态。单击按钮后,用户将被重定向到地图活动。布尔serviceStauts
变量用于检测两个活动中服务的状态。我面临的问题是将布尔值作为意图传递给地图活动,因为该值在MainActivity的开头是ture,当我点击false
的地图活动时,我点击了serviceStauts
清单(我没有触及操作栏中的图标)!?
可以指导我为什么在地图活动中弄错了吗?
MainActivity:
public class MainActivity extends ActionBarActivity {
boolean serviceStauts = true;
....
private void createCheckboxList(final ArrayList<Integer> items) {
Intent serviceStatusIntent = new Intent(MainActivity.this, Map.class);
serviceStatusIntent.putExtra("booleanServicfeStatus", serviceStauts);
startActivity(serviceStatusIntent);
}
....
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_toggle:
if (serviceStauts) {
item.setIcon(R.drawable.off);
item.setTitle("OFF");
serviceStauts = false;
mService.stopTrackingService();
System.out.println("ABC Map onOptionsitemSelected OFF");
} else {
item.setIcon(R.drawable.on);
item.setTitle("ON");
serviceStauts = true;
Intent i = new Intent(this, TrackingService.class);
startService(i);
System.out.println("ABC Map onOptionsitemSelected ON");
}
}
return super.onOptionsItemSelected(item);
}
}
地图活动:
public class Map extends ActionBarActivity {
boolean serviceStauts;
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
serviceStauts = getIntent().getExtras().getBoolean("booleanServicfeStatus");
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
System.out.println("ABC MAP onPrepareOptionsMenu was invoked.");
MenuItem item = menu.findItem(R.id.menu_toggle);
if(serviceStauts){
item.setIcon(R.drawable.on);
}else{
item.setIcon(R.drawable.off);
}
return super.onPrepareOptionsMenu(menu);
}
}
答案 0 :(得分:1)
如果密钥不存在,您正在使用'onNewIntent for the first time an
活动is called, which means the
额外s are absent. Then you use
getBoolean which defaults to
false`。
除特定情况外,您不应实施onNewIntent
。只需使用getIntent
来获取您的捆绑包。
答案 1 :(得分:0)
将此添加到您的Map
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
serviceStauts = getIntent().getExtras().getBoolean("booleanServicfeStatus");
}
您可以删除onNewIntent
方法,它可用于其他一些情况。