AlarmManager调度不同日期的警报

时间:2016-04-19 13:08:49

标签: android broadcastreceiver alarmmanager android-broadcastreceiver

我想建立一个水提醒应用程序。根据应用程序预先做的一些计算,这个应用程序应该每次你应该喝水时发送通知。我知道如何使用AlarmManager来安排一次性警报和重复警报。在搜索了很多之后我还没想到的是,我将如何使用AlarmManager每天安排特定数量的警报(比如6),在白天的特定时间停止(比如说晚上10点)并在第二天开始发送通知(比如说早上7点)。所有这一切都应该在用户不必打开应用程序的情况下发生。我该怎么做呢?这是我的代码:

MainActivity的一部分:

Long alertTime = nextAlarm.getTimeInMillis();
    Intent alertIntent = new Intent(this, AlertReceiver.class);

    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    alarmManager.set(AlarmManager.RTC_WAKEUP, alertTime,
            PendingIntent.getBroadcast(this, 1, alertIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT));

AlertReceiver:

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;

public class AlertReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent



intent) {
        createNotification(context, "Hydrate", "Time to drink water", "Alert");
    }

public void createNotification(Context context, String msg, String msgText, String msgAlert) {

    PendingIntent notificationIntent = PendingIntent.getActivity(context, 0,
            new Intent(context, MainActivity.class), 0);

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.ic_drop_24dp)
            .setContentTitle(msg)
            .setContentText(msgText)
            .setTicker(msgAlert);

    notificationBuilder.setContentIntent(notificationIntent);

    notificationBuilder.setDefaults(Notification.DEFAULT_ALL);

    notificationBuilder.setAutoCancel(true);

    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(1, notificationBuilder.build());

    }

}

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

如果要以固定间隔发送通知,请以固定间隔设置重复警报,并在广播接收器中检查当前时间并发送通知。

@Override
public void onReceive(Context context, Intent intent) {

    //get current hour in 24 hour format
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    int curHour = calendar.get(Calendar.HOUR_OF_DAY);

    if(curHour > 7 && curHour < 22)
        createNotification(context, "Hydrate", "Time to drink water", "Alert");
}