我正在尝试在活动之间传递布尔值:
主要活动
boolean stream = false; boolean wifi = false; public void onToggleClicked(View view) { if (((ToggleButton)view).isChecked()) { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, alarmTimePicker.getCurrentHour()); calendar.set(Calendar.MINUTE, alarmTimePicker.getCurrentMinute()); Intent myIntent = new Intent(MainActivity.this, AlarmReceiver.class); myIntent.putExtra("snooze",false); myIntent.putExtra("stream",stream); myIntent.putExtra("wifi",wifi); pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent, 0); alarmManager.setExact(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent); } }
然后在我的广播接收器中检索它:
报警接收器
public class AlarmReceiver extends WakefulBroadcastReceiver { @Override public void onReceive(final Context context, Intent intent) { Boolean wifi = intent.getBooleanExtra("wifi"); Boolean stream = intent.getBooleanExtra("stream"); Boolean snooze = intent.getBooleanExtra("snooze"); //.....
对于每个getBooleanExtra我都会收到错误:
error: method getBooleanExtra in class Intent cannot be applied to given types; required: String,boolean found: boolean reason: actual and formal argument lists differ in length
如果我将Boolean更改为boolean,则错误更改为found:String而不是found:boolean
我怎样才能解决这个问题?
getBooleanExtra返回primitive boolean
类型,您必须提供默认值
Boolean stream = intent.getBooleanExtra("stream",false); // ^^ wrapper class ^^^ default value
或者你可以更好的使用boolean
,以避免不必要autoboxing
的boolean
到Boolean
。
boolean wifi = intent.getBooleanExtra("wifi",false); boolean stream = intent.getBooleanExtra("stream",false); boolean snooze = intent.getBooleanExtra("snooze",false);