给出AlarmBroadcastReceiver类
时间: 2023-10-03 22:03:58 浏览: 23
好的,下面是AlarmBroadcastReceiver类的代码:
```
public class AlarmBroadcastReceiver extends BroadcastReceiver {
private MediaPlayer mediaPlayer;
@Override
public void onReceive(Context context, Intent intent) {
// 创建MediaPlayer对象
mediaPlayer = MediaPlayer.create(context, R.raw.alarm_sound);
// 设置循环播放
mediaPlayer.setLooping(true);
// 开始播放
mediaPlayer.start();
// 显示通知
showNotification(context);
}
private void showNotification(Context context) {
// 创建PendingIntent对象
Intent intent = new Intent(context, AlarmActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
// 创建Notification对象
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "default")
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("闹钟")
.setContentText("时间到了!")
.setContentIntent(pendingIntent)
.setAutoCancel(true);
// 获取NotificationManager对象
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// 发送通知
notificationManager.notify(0, builder.build());
}
public void stopAlarm() {
// 停止播放
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
}
}
```
在该类中,我们在`onReceive()`方法中播放铃声,并在`showNotification()`方法中显示通知。同时,我们还提供了一个`stopAlarm()`方法,在响铃停止时调用。