在 TimePickerDialog 中获取上下文

Getting Context inside a TimePickerDialog

我正在创建一个应用程序,我在其中向用户显示 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");
}

您可以在 onTimeSet()

中简单地使用 view.getContext()

不会为空。

只需使用 view.getContext() 即可解决问题,但要小心在片段中使用它,因为视图上下文将更改为来自 activity 或片段[的对话框的简单传递上下文参数=11=]