当前位置:  开发笔记 > 编程语言 > 正文

getBooleanExtra不能应用于布尔变量

如何解决《getBooleanExtra不能应用于布尔变量》经验,为你挑选了1个好方法。

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

主要活动

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

我怎样才能解决这个问题?



1> Pavneet_Sing..:

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

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

或者你可以更好的使用boolean,以避免不必要autoboxingbooleanBoolean

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

推荐阅读
coco2冰冰
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有