You need to enable JavaScript to run this app. Android Studio 基于EditText日期时间选择器的通知调度set按钮实现疑问
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio 基于EditText日期时间选择器的通知调度set按钮实现疑问

定时通知功能补全实现

核心问题定位

当前代码逻辑断链的两个核心问题:

  • 用户选择的时间存在showDateTimeDialog方法的局部Calendar变量里,点击set按钮时拿不到准确的时间值,只能读取EditText里的格式化字符串,手动解析字符串极易因格式不匹配触发崩溃
  • set按钮分支仅做了非空校验,没有调用AlarmManager的定时设置方法,闹钟自然不会触发

具体修改步骤

1. 替换时间存储为全局成员变量

将原来的局部Calendar改成Activity级别的全局变量,避免方法回收后丢失用户选择的时间:

// Activity成员变量区定义
private Calendar selectedCalendar = Calendar.getInstance();
private AlarmManager alarmManager;
private PendingIntent alarmIntent;
private int notificationId = 1;
private EditText dateTimeIn;

同步修改日期、时间选择的回调逻辑:选完时间直接更新全局selectedCalendar实例,给EditText赋值仅作为用户侧的展示用途,不参与核心定时计算:

// DatePicker选中回调
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
    selectedCalendar.set(Calendar.YEAR, year);
    selectedCalendar.set(Calendar.MONTH, month);
    selectedCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
    // 弹出时间选择框的原有逻辑保持不变
}

// TimePicker选中回调
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
    selectedCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
    selectedCalendar.set(Calendar.MINUTE, minute);
    selectedCalendar.set(Calendar.SECOND, 0); // 清零秒数,消除触发时间偏差
    SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yy HH:mm", Locale.getDefault());
    dateTimeIn.setText(sdf.format(selectedCalendar.getTime()));
}

2. 全局初始化闹钟相关对象

把原来在onClick方法里重复创建的AlarmManager、PendingIntent挪到onCreate方法中做全局初始化,保证set和cancel操作使用同一个PendingIntent实例——如果两边的PendingIntent不是同一实例,cancel操作根本找不到之前注册的闹钟,功能完全失效:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_jadwal_wc);

    // 初始化系统闹钟服务
    alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    // 构建接收闹钟广播的Intent
    Intent alarmBaseIntent = new Intent(JadwalWc.this, AlarmReceiver.class);
    alarmBaseIntent.putExtra("notificationId", notificationId);
    // 兼容Android 12以上版本对PendingIntent的标志位要求
    int pendingFlags = PendingIntent.FLAG_CANCEL_CURRENT;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
        pendingFlags |= PendingIntent.FLAG_IMMUTABLE;
    }
    alarmIntent = PendingIntent.getBroadcast(this, 0, alarmBaseIntent, pendingFlags);

    // 原有点击监听逻辑保持不变
    findViewById(R.id.setBtn).setOnClickListener(this);
    findViewById(R.id.cancelBtn).setOnClickListener(this);
    dateTimeIn = findViewById(R.id.dateTimeInput);
    dateTimeIn.setInputType(InputType.TYPE_NULL);
    dateTimeIn.setOnClickListener(v -> showDateTimeDialog(dateTimeIn));
}

3. 补全set按钮的定时设置逻辑

替换原有set分支的空逻辑,加上时间合法性校验、跨版本适配的闹钟调用代码:

case R.id.setBtn:
    String selectedTimeStr = dateTimeIn.getText().toString().trim();
    if (selectedTimeStr.isEmpty()) {
        Toast.makeText(this, "Please select date and time", Toast.LENGTH_SHORT).show();
        break;
    }
    // 校验用户选择的时间不能早于当前时间
    long triggerMills = selectedCalendar.getTimeInMillis();
    if (triggerMills <= System.currentTimeMillis()) {
        Toast.makeText(this, "Selected time can't be earlier than current time", Toast.LENGTH_SHORT).show();
        break;
    }
    // 按系统版本适配闹钟设置方法,保证精确触发,不受系统省电模式影响
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        alarmManager.setExactAndAllowWhileIdle(
            AlarmManager.RTC_WAKEUP,
            triggerMills,
            alarmIntent
        );
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        alarmManager.setExact(
            AlarmManager.RTC_WAKEUP,
            triggerMills,
            alarmIntent
        );
    } else {
        alarmManager.set(
            AlarmManager.RTC_WAKEUP,
            triggerMills,
            alarmIntent
        );
    }
    Toast.makeText(this, "Schedule success!", Toast.LENGTH_SHORT).show();
    break;

必查注意事项

  • 必须在AndroidManifest.xml中注册AlarmReceiver,否则广播发出后没有接收方,通知不会弹出
  • 应用targetSdkVersion为33及以上时,需要申请POST_NOTIFICATIONS运行时权限,否则通知无法弹出
  • 原有cancel按钮的逻辑不需要修改,全局统一使用同一个alarmManager和alarmIntent实例时,直接调用cancel方法即可正常取消已设置的闹钟

内容的提问来源于stack exchange,提问作者Azer89

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.12 08:45:10