将整数值传递给Broadcast Receiver类

时间:2015-03-25 20:18:45

标签: java android android-intent broadcastreceiver android-timepicker

我正在尝试获取开始时间并停止用户在一个班级中使用Time Picker然后将此时间传递给广播课程。

但是当我通过使用Toast消息检查广播接收器类中是否达到开始时间和停止时间的值时,我无法获得所需的开始时间或停止时间。

代码[主类]:

protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.setting);
    initialize();
    alarmIntent = new Intent(Settings.this, AlarmReceiver.class);
    pendingIntent = PendingIntent.getBroadcast(Settings.this, 0, alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT);
    alarmRepeat();              
}
@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    Calendar c = Calendar.getInstance();
    switch(v.getId()){
    case R.id.startTime :
        // Process to get Current Time
        startHour = c.get(Calendar.HOUR_OF_DAY);
        startMinute = c.get(Calendar.MINUTE);

        // Launch Time Picker Dialog
        TimePickerDialog tpd1 = new TimePickerDialog(this,
                new TimePickerDialog.OnTimeSetListener() {

                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay,
                            int minute) {
                        // Display Selected time in textbox
                        eStart.setText(hourOfDay + ":" + minute);
                        startHour = hourOfDay;
                        startMinute = minute;
                        alarmIntent.putExtra("startHour", startHour);
                        alarmIntent.putExtra("startMinute", startMinute);//passing these variables to Broadcast class
                    }
                }, startHour, startMinute, false);
        tpd1.show();

public void alarmRepeat(){
    Calendar cal = Calendar.getInstance();
    AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    manager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 1000, pendingIntent);
}

广播课程:

public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub
    startHour = intent.getIntExtra("startHour", 0);
    stopHour = intent.getIntExtra("StopHour", 0);

    Toast.makeText(context, startHour + ":" + startMinute, Toast.LENGTH_LONG).show();

程序说明:我已将startHour和startMinute从主类中的onTimeSet方法传递给广播类。

在广播类中,我将此startHour和StopMinute存储在上面定义的变量中。

1 个答案:

答案 0 :(得分:0)

此处的问题是您要在onCreate中创建闹钟,然后在onClick中更新您的信息。我非常确定您的pendingIntent声明需要在您向alarmIntent提供信息之后。

修改:我会在更新pendingIntent后立即重新创建alarmIntent,然后再次致电alarmRepeat()。就个人而言,我会将pendingIntent的分配放在警报方法中并将alarmIntent作为参数传递,但这是一种风格选择。

只要挂起的意图相同(不包括添加到其中的意图中的额外内容),alarmmanager将使用新警报覆盖任何现有警报