在TimePickerDialog中获取Context

时间:2017-10-31 09:05:07

标签: android android-intent datepicker alarmmanager timepicker

我正在创建一个应用程序,我向用户提供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 个答案:

答案 0 :(得分:2)

您只需在static void Main(string[] args) { DeviceUserGroup folder = GetTopLevelGroupAsYouWish(); BuildHierarchy (folder); Console.ReadKey(); } static void BuildHierarchy(DeviceUserGroup userGroup) { try { foreach (Device device in userGroup.Devices) Console.WriteLine(device.Name); foreach (DeviceUserGroup group in userGroup.Groups) { Console.WriteLine(group.Name); BuildHierarchy(group); } } catch (System.Exception ex) { Console.WriteLine(ex.Message); } }

中使用view.getContext()即可

它不会为空。

答案 1 :(得分:2)

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