首页 文章

在TimePickerDialog中获取Context

提问于
浏览
2

我正在创建一个应用程序,我向用户提供DatePicker和TimePicker,以便为AlarmManager创建未来的日期值 .

我正在链接TimePicker以显示用户何时在DatePicker中选择日期 .

然后在TimePicker内部,一旦用户选择了时间,我想创建一个待定的意图并设置AlarmManager . 当我尝试创建一个Intent时,我遇到了崩溃,因为我似乎无法获得上下文 .

但奇怪的是,如果我在DatePicker中创建Intent,它就可以工作 .

public void onDateSet(DatePicker view, int year, int month, int day) {

    mCallback.onDateSelected(year, month, day);

    calendar.set(Calendar.YEAR, year);
    calendar.set(Calendar.MONTH, month);
    calendar.set(Calendar.DAY_OF_MONTH, day);

    TimePickerDialog timePickerDialog = new TimePickerDialog(getContext(), this, 1, 1, true);
    timePickerDialog.show();
}

/**
 * @param view
 * @param hourOfDay
 * @param minute
 */
@Override
public void onTimeSet(android.widget.TimePicker view, int hourOfDay, int minute) {

    mTimeCallback.onTimeSelected(hourOfDay, minute);

    calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
    calendar.set(Calendar.MINUTE, minute);
    Long millis = calendar.getTimeInMillis();
    long futureInMillis = SystemClock.elapsedRealtime() + millis;


    Intent notificationIntent = new Intent(getContext(), NotificationPublisher.class);
    notificationIntent.putExtra(NotificationPublisher.NOTIFICATION, getNotification());
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getContext(), 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 100, pendingIntent);

    Log.i("Got here", "yes");
}

2 回答

  • 2

    您可以在 onTimeSet() 内使用 view.getContext()

    它不会为空 .

  • 2

    只需使用 view.getContext() 解决问题,但要小心在片段中使用它,因为视图上下文将从您的活动或片段更改为对话框的简单传递上下文参数

相关问题