AlarmManager结合PendingIntent与广播接收器失效问题求助
Hey there! Let's figure out why your alarm isn't doing anything after you set the time. Looking at the code snippet you shared, there are a few critical pieces missing that are keeping your alarm from working properly. Here's what you need to fix:
1. Complete the OnTimeSetListener Implementation
Your code cuts off right when defining the OnTimeSetListener—this is the callback that runs after the user selects a time, and it's where you need to trigger the actual alarm setup. Without finishing this method, nothing happens once the time is picked.
Fix it by adding the full implementation:
protected TimePickerDialog.OnTimeSetListener kTimePickerListener = new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker view, int selectedHour, int selectedMinute) { // Save the selected time values hour = selectedHour; min = selectedMinute; // Call a method to actually set up the alarm setupAlarm(hour, min); } };
2. Add AlarmManager Logic to Schedule the Alarm
Right now, you're just showing a time picker—but you never tell Android's AlarmManager to actually trigger the alarm at the selected time. You need a dedicated method to handle this:
private void setupAlarm(int targetHour, int targetMinute) { AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); // Create an intent that will trigger your alarm receiver Intent alarmIntent = new Intent(this, AlarmReceiver.class); PendingIntent pendingIntent = PendingIntent.getBroadcast( this, 0, alarmIntent, PendingIntent.FLAG_IMMUTABLE // Use FLAG_UPDATE_CURRENT if you need to update the intent later ); // Use Calendar to set the exact alarm time Calendar alarmCalendar = Calendar.getInstance(); alarmCalendar.set(Calendar.HOUR_OF_DAY, targetHour); alarmCalendar.set(Calendar.MINUTE, targetMinute); alarmCalendar.set(Calendar.SECOND, 0); // If the selected time is already passed today, set it for tomorrow if (alarmCalendar.getTimeInMillis() < System.currentTimeMillis()) { alarmCalendar.add(Calendar.DAY_OF_YEAR, 1); } // Schedule the alarm (use exact methods for reliability) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, alarmCalendar.getTimeInMillis(), pendingIntent); } else { alarmManager.setExact(AlarmManager.RTC_WAKEUP, alarmCalendar.getTimeInMillis(), pendingIntent); } // Optional: Confirm the alarm is set with a toast Toast.makeText(this, "Alarm set for " + targetHour + ":" + targetMinute, Toast.LENGTH_SHORT).show(); }
3. Create a BroadcastReceiver to Handle Alarm Triggers
When the alarm time hits, Android needs a way to notify your app—this is done with a BroadcastReceiver. Create a new class for this:
public class AlarmReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // This is where you trigger your alarm's action: play a sound, show a notification, etc. Toast.makeText(context, "Wake up! Your alarm is going off!", Toast.LENGTH_LONG).show(); // Example: Show a high-priority notification (required for Android O+) NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, "ALARM_CHANNEL_ID") .setSmallIcon(R.drawable.ic_alarm) // Replace with your app's alarm icon .setContentTitle("Custom Alarm") .setContentText("Time's up!") .setPriority(NotificationCompat.PRIORITY_HIGH) .setCategory(NotificationCompat.CATEGORY_ALARM); NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); notificationManager.notify(1, notificationBuilder.build()); } }
Don't forget to register this receiver in your AndroidManifest.xml:
<receiver android:name=".AlarmReceiver" />
4. Add Required Permissions and Notification Channel
- For Android 12+: You need the
SCHEDULE_EXACT_ALARMpermission to schedule exact alarms. Add this to yourAndroidManifest.xml:<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" /> - For Android O+: You must create a notification channel to show alarm notifications. Add this code to your
MainActivity'sonCreatemethod:if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel alarmChannel = new NotificationChannel( "ALARM_CHANNEL_ID", "Alarm Notifications", NotificationManager.IMPORTANCE_HIGH ); NotificationManager notificationManager = getSystemService(NotificationManager.class); notificationManager.createNotificationChannel(alarmChannel); }
Quick Check: Make Sure You're Showing the Dialog
Double-check that you're actually triggering the time picker dialog somewhere in your code, like with a button click:
// Example: Trigger dialog when a button is clicked Button setAlarmBtn = findViewById(R.id.set_alarm_btn); setAlarmBtn.setOnClickListener(v -> showDialog(DIALOG_ID));
Putting all these pieces together should get your alarm working as expected!
内容的提问来源于stack exchange,提问作者Fahad Shahid

