寻求Android每日重复通知最新代码及定时实现方案
Hey there! Let's work through your notification problems and get that daily repeating alarm sorted out step by step.
1. Replacing the Deprecated NotificationCompat.Builder
Starting from Android API 26, notifications require a notification channel, which is why the old NotificationCompat.Builder(Context) constructor got deprecated. Here's how to update your code properly:
First, create a notification channel (you only need to run this once, like in your Application class or MainActivity's onCreate):
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { String channelId = "daily_reminder_channel"; CharSequence channelName = "Daily Reminders"; String channelDescription = "Channel for your daily scheduled notifications"; int importance = NotificationManager.IMPORTANCE_DEFAULT; NotificationChannel channel = new NotificationChannel(channelId, channelName, importance); channel.setDescription(channelDescription); // Register the channel with the system NotificationManager notificationManager = getSystemService(NotificationManager.class); notificationManager.createNotificationChannel(channel); }
Then build your notification using the channel-aware constructor:
Intent i = new Intent(this, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity( this, 0, // Use a unique number if you have multiple PendingIntents i, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE // FLAG_IMMUTABLE is recommended for API 31+ ); NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "daily_reminder_channel") .setSmallIcon(R.drawable.your_notification_icon) .setContentTitle("Daily Check-In") .setContentText("It's time to take action!") .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setContentIntent(pendingIntent) .setAutoCancel(true); // Show the notification NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this); notificationManager.notify(1, builder.build()); // 1 is your unique notification ID
2. Troubleshooting Red Markers in Your Manifest
Red flags in the Android Manifest almost always point to syntax errors or missing required declarations. Here are the most common fixes to check:
- Verify your
MainActivitydeclaration: Make sure you have a properly closed<activity>tag forMainActivity:<activity android:name=".MainActivity" android:exported="true"> <!-- Set to true if this is your launcher activity --> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> - Add required permissions: For Android 13 (API 33+) and above, you need to declare the
POST_NOTIFICATIONSpermission in your manifest:<uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> - Check for syntax typos: Hover over the red line in Android Studio—you'll get a tooltip explaining the exact error, like unclosed tags, misspelled attribute names, or missing required fields.
3. Setting Up Daily Repeating Notifications
To make your existing PendingIntent trigger at a specific time every day, you'll use AlarmManager to schedule a repeating alarm. Here's how to do it right:
First, calculate your target trigger time (e.g., 9:00 AM every day):
Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); calendar.set(Calendar.HOUR_OF_DAY, 9); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); // If today's target time has already passed, schedule for tomorrow if (calendar.getTimeInMillis() < System.currentTimeMillis()) { calendar.add(Calendar.DAY_OF_YEAR, 1); }
Then, you'll need a BroadcastReceiver to trigger the notification when the alarm fires (you can't directly launch a notification from AlarmManager with an Activity intent):
- Create the receiver class:
public class DailyNotificationReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // Build and show your notification here (reuse the code from section 1) Intent activityIntent = new Intent(context, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity( context, 0, activityIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE ); NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "daily_reminder_channel") .setSmallIcon(R.drawable.your_notification_icon) .setContentTitle("Daily Check-In") .setContentText("It's time to take action!") .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setContentIntent(pendingIntent) .setAutoCancel(true); NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); notificationManager.notify(1, builder.build()); } }
- Register the receiver in your manifest:
<receiver android:name=".DailyNotificationReceiver" android:exported="false" />
Finally, schedule the repeating alarm with AlarmManager:
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); PendingIntent alarmPendingIntent = PendingIntent.getBroadcast( this, 100, // Unique request code (different from your notification ID) new Intent(this, DailyNotificationReceiver.class), PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE ); // Use battery-friendly repeating for API 19+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { alarmManager.setInexactRepeating( AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, alarmPendingIntent ); } else { alarmManager.setRepeating( AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, alarmPendingIntent ); }
That's all! This setup will fire your notification at your specified time every single day.
内容的提问来源于stack exchange,提问作者Mr. Benbenbenbenben




