我正在使用AlarmManager创建一个闹钟,我遇到了一些麻烦:
打开通知时如何停止通知声音?
如何针对某一天(或整周)发出警报,而不是针对特定日期?
private void restartNotify()
{
Calendar calendar = Calendar.getInstance();
// current Month - 1
calendar.set(Calendar.MONTH, 5);
calendar.set(Calendar.YEAR, 2015);
calendar.set(Calendar.DAY_OF_MONTH, 28);
calendar.set(Calendar.HOUR_OF_DAY, 1);
calendar.set(Calendar.MINUTE, 40);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.AM_PM, Calendar.PM);
Intent timeIntent = new Intent(MainActivity.this, TimeNotification.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, timeIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
}
public class TimeNotification extends WakefulBroadcastReceiver
{
@Override
public void onReceive(final Context context, Intent intent)
{
Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alarmUri == null) {
alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri);
ringtone.play();
//this will send a notification message
ComponentName comp = new ComponentName(context.getPackageName(),
AlarmService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
公共类AlarmService扩展了IntentService {
private NotificationManager alarmNotificationManager;
public AlarmService() {
super("AlarmService");
}
@Override
public void onHandleIntent(Intent intent)
{
sendNotification("Wake Up! Wake Up!");
}
private void sendNotification(String msg)
{
alarmNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
NotificationCompat.Builder alamNotificationBuilder = new NotificationCompat.Builder(
this).setContentTitle("Alarm").setSmallIcon(R.drawable.abc_btn_radio_material)
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg);
alamNotificationBuilder.setContentIntent(contentIntent);
alarmNotificationManager.notify(1, alamNotificationBuilder.build());
}