java - 如何使用 setExact 设置重复闹钟以及如何取消重复闹钟?

标签 java android alarmmanager android-notifications repeat

我正在使用警报管理器和广播接收器设置通知。我尝试使用警报管理器的 setInexactRepeating 方法,但它不会在 API 19 以上的确切时间发出警报。

所以我得到了使用 setExact 方法并手动设置警报的建议。我不知道我该怎么做。我需要计算一年中每周的日期吗?

如果事件被删除,我也想删除我正在创建的警报。我怎样才能取消这个?使用取消方法我尝试取消警报。为了测试,我尝试设置多个闹钟并将其删除。

如果我删除一个事件,那么该事件的相关警报应该被取消,但可能所有警报都会被取消,因为删除事件后我没有收到任何通知。

我为此使用了唯一的 ID。作为最终静态 int RQS_1 = 1;用于设置闹钟。

有人可以帮我解决这个问题吗?

设置闹钟:

 public void setNotificationTime(Calendar c)
{

    Date dateFrom = new Date();
    df = new SimpleDateFormat("E MMM dd hh:mm:ss zzzz yyyy");
    try {
        dateFrom = df.parse(startTime);
    }
    catch (ParseException ex) {

    }

    dateFrom.getTime();
    c.setTime(dateFrom);

    hour = c.get(Calendar.HOUR_OF_DAY);
    minute = c.get(Calendar.MINUTE);


    if(notificationTime.equals("10 Minutes Before"))
    {


        c.set(Calendar.HOUR_OF_DAY, hour);
        c.set(Calendar.MINUTE, minute - 10);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        c.set(Calendar.DATE, day);
        // c.set(Calendar.DAY_OF_WEEK,);

        SetDay(c);

        notification = c.getTime();
        notificationTime = df.format(notification);

        Toast.makeText(getApplicationContext(),notificationTime,Toast.LENGTH_SHORT).show();

        intent = new Intent(getBaseContext(),NotificationReceiver.class);
        pendingIntent = PendingIntent.getBroadcast(getBaseContext(),RQS_1, intent, 0);
        alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), AlarmManager.INTERVAL_DAY * 7, pendingIntent);

    }



    else if(notificationTime.equals("30 Minutes Before"))
    {

        c.set(Calendar.HOUR_OF_DAY, hour);
        c.set(Calendar.MINUTE, minute - 30);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        c.set(Calendar.DATE, day);
        // c.set(Calendar.DAY_OF_WEEK,);

        SetDay(c);

        notification = c.getTime();
        notificationTime = df.format(notification);

        Toast.makeText(getApplicationContext(),notificationTime,Toast.LENGTH_SHORT).show();

        intent = new Intent(getBaseContext(),NotificationReceiver.class);
        pendingIntent = PendingIntent.getBroadcast(getBaseContext(),RQS_1, intent, 0);
        alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), AlarmManager.INTERVAL_DAY * 7, pendingIntent);

    }
}

我创建了 setDay 方法来设置用户从对话框中选择的日期并设置日期。

setDay函数:

public void SetDay(Calendar c)
{
    switch (dayOfWeek)
        {
            case  "Mon":
                c.set(Calendar.DAY_OF_WEEK, 2);
                c.getTime();
                Toast.makeText(getApplicationContext(),dayOfWeek,Toast.LENGTH_SHORT).show();
                break;
            case "Tue":
                c.set(Calendar.DAY_OF_WEEK, 3);
                c.getTime();
                Toast.makeText(getApplicationContext(),dayOfWeek,Toast.LENGTH_SHORT).show();
                break;

}

通知接收者

 public class NotificationReceiver  extends BroadcastReceiver {


    public static int MY_NOTIFICATION_ID = 0;
    NotificationManager notificationManager;
    Notification myNotification;

    EventTableHelper db;

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


        Toast.makeText(context, "Time is set", Toast.LENGTH_LONG).show();

        db = new EventTableHelper(context);

        List<EventData> testSavings = db.getAllEvents();

        for (EventData ts : testSavings) {
            String log = "from date:" + ts.getFromDate()
                    + " ,to date: " + ts.getToDate()
                    + " ,location: " + ts.getLocation()
                    + " ,title " + ts.getTitle();

            Calendar c = Calendar.getInstance();
            Date date = new Date();
            Date date1 = new Date();
            Log.d("Result: ", log);

            SimpleDateFormat df = new SimpleDateFormat("E MMM dd hh:mm:ss zzzz yyyy");
            SimpleDateFormat df2 = new SimpleDateFormat("hh:mm a");

            try {
                date = df.parse(ts.getFromDate());
                date1 = df.parse(ts.getToDate());
            } catch (ParseException ex) {

            }
            String timeFrom = df2.format(date);
         //   String startTime = String.valueOf(timeFrom);

            String timeTo = df2.format(date1);
           // String endTime = String.valueOf(timeTo);


            String location = ts.getLocation();
            String title = ts.getTitle();


            Intent myIntent = new Intent(context, MainActivity.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(
                    context,
                    0,
                    myIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT);

            if(location.equals(""))
            {
                String msg = "From : " + timeFrom + "\nTo : " + timeTo;

                myNotification = new NotificationCompat.Builder(context)
                        .setContentTitle("Event : " + title)
                        .setContentText(msg)
                        .setWhen(System.currentTimeMillis())
                        .setContentIntent(pendingIntent)
                        .setAutoCancel(true)
                        .setSmallIcon(R.drawable.eventicon)
                        .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                        .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
                        .setDefaults(Notification.DEFAULT_SOUND)
                        .build();

            }

            else
            {
                String msg = "From : " + timeFrom + "\nTo : " + timeTo + "\nAt : " + location;
                myNotification = new NotificationCompat.Builder(context)
                        .setContentTitle("Event : " + title)
                        .setContentText(msg)
                        .setWhen(System.currentTimeMillis())
                        .setContentIntent(pendingIntent)
                        .setAutoCancel(true)
                        .setSmallIcon(R.drawable.eventicon)
                        .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                        .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
                        .setDefaults(Notification.DEFAULT_SOUND)
                        .build();

            }

            Log.i("Notify", "Notification");
            notificationManager =
                    (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(MY_NOTIFICATION_ID, myNotification);

            myNotification.flags=Notification.FLAG_AUTO_CANCEL;

        }
    }
}

是的,忘记添加取消代码:

 alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
                                intent = new Intent(getApplicationContext(), NotificationReceiver.class);
                                pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), RQS_1, intent, 0);
                                alarmManager.cancel(pendingIntent);

谢谢你..

最佳答案

像这样,

pendingIntent = PendingIntent.getBroadcast(getBaseContext(),RQS_1, intent, 0);
    alarmManager.cancel(pendingIntent); //Remove any alarms with a matching Intent

了解更多信息AlarmManager

关于java - 如何使用 setExact 设置重复闹钟以及如何取消重复闹钟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35332474/

相关文章:

Java仅调用以parent作为函数参数的方法

android - 无法从 KeyStore 检索私钥

java - AlarmManager 没有在正确的时间关闭

java - 即使应用程序未运行,如何每 10 分钟在后台获取位置信息?

Android 5神秘杀死alarmmanager任务

java - Spring boot 使用的默认值 - spring-boot-starter-parent

java - 当背后的代码存在时,简单的异步任务按钮不输出 boolean 值

java - 设置 CountDownTimer 来运行 onDestroy() 的正确方法是什么?

android - 应用程序 :transformClassesAndResourcesWithProguardForRelease 构建失败

java - 发布一个 Eclipse 项目