要实现Android上的多个闹钟,并且每个闹钟都有不同的通知,可以使用AlarmManager和NotificationManager来实现。
首先,需要在AndroidManifest.xml文件中添加以下权限:
接下来,创建一个AlarmReceiver类,用于接收闹钟触发的广播,并在其中处理通知逻辑:
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// 处理通知逻辑
String message = intent.getStringExtra("message");
showNotification(context, message);
}
private void showNotification(Context context, String message) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "channel_id")
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("闹钟通知")
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_HIGH);
// 显示通知
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
notificationManager.notify(0, builder.build());
}
}
然后,在Activity中设置闹钟和通知:
public class MainActivity extends AppCompatActivity {
private AlarmManager alarmManager;
private PendingIntent alarmIntent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);
intent.putExtra("message", "闹钟1");
alarmIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
// 设置第一个闹钟
Calendar calendar1 = Calendar.getInstance();
calendar1.setTimeInMillis(System.currentTimeMillis());
calendar1.set(Calendar.HOUR_OF_DAY, 8);
calendar1.set(Calendar.MINUTE, 0);
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar1.getTimeInMillis(), alarmIntent);
// 设置第二个闹钟
Intent intent2 = new Intent(this, AlarmReceiver.class);
intent2.putExtra("message", "闹钟2");
PendingIntent alarmIntent2 = PendingIntent.getBroadcast(this, 1, intent2, 0);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTimeInMillis(System.currentTimeMillis());
calendar2.set(Calendar.HOUR_OF_DAY, 9);
calendar2.set(Calendar.MINUTE, 0);
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar2.getTimeInMillis(), alarmIntent2);
}
}
在上面的代码中,我们创建了两个闹钟,分别在早上8点和9点触发。每个闹钟都会发送一个包含通知内容的广播。在AlarmReceiver中,我们通过获取广播中的消息内容,使用NotificationCompat.Builder创建通知,并使用NotificationManagerCompat显示通知。
需要注意的是,为了确保闹钟能够准确触发,我们使用了AlarmManager的setExact方法,并设置了不同的requestCode来区分不同的闹钟。此外,我们还需要在AndroidManifest.xml文件中注册AlarmReceiver:
以上就是实现Android多个闹钟并带有不同通知的示例代码。