getBooleanExtra不能应用于布尔变量

时间:2017-01-16 21:07:39

标签: java android

我试图在活动之间传递布尔值:

MainActivity

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

然后在我的broadcastreceiver中检索它:

AlarmReceiver

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

如果我将布尔值更改为布尔值,则错误更改为 found:String 而不是 found:boolean

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:4)

getBooleanExtra返回primitive boolean类型,您必须提供默认值

Boolean stream = intent.getBooleanExtra("stream",false);
// ^^ wrapper class                              ^^^ default value 

或更好,您可以使用boolean来避免不必要的auto-unboxing

    boolean wifi = intent.getBooleanExtra("wifi",false);
    boolean stream = intent.getBooleanExtra("stream",false);
    boolean snooze = intent.getBooleanExtra("snooze",false);