从AlarmManager报警不会断

编程入门 行业动态 更新时间:2024-10-18 12:35:02
本文介绍了从AlarmManager报警不会断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

通过这个code我设置在的onCreate 的报警我 MainActivity 使用 AlarmManager :

With this code I am setting an alarm in onCreate of my MainActivity using the AlarmManager:

Intent startServiceIntent = new Intent(this, MyService.class); AlarmManager manager = (AlarmManager) getSystemService(Activity.ALARM_SERVICE); PendingIntent pendingIntent = PendingIntent.getService(this, 0, startServiceIntent, 0); Calendar cal = Calendar.getInstance(); cal.set(Calendar.HOUR_OF_DAY, 7); cal.set(Calendar.MINUTE, 47); cal.set(Calendar.SECOND, 00); cal.set(Calendar.YEAR, 2014); cal.set(Calendar.MONTH, 07); cal.set(Calendar.DAY_OF_MONTH, 28); manager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 1000, pendingIntent);

和为MyService 的code是:

public class MyService extends Service { @Override public IBinder onBind(Intent arg0) { return null; } @Override public void onCreate() { Toast.makeText(getApplicationContext(), "Service Created", Toast.LENGTH_SHORT).show(); super.onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Toast.makeText(getApplicationContext(), "Service Working", 1).show(); return super.onStartCommand(intent, flags, startId); } }

但没有的祝酒词从为MyService 显示?谁能告诉我什么,我做错了吗?

But none of the Toasts from MyService are shown? Can anybody tell me what I'm doing wrong?

推荐答案

我认为问题就在这里:

Calendar cal = Calendar.getInstance(); cal.set(Calendar.HOUR_OF_DAY, 7); cal.set(Calendar.MINUTE, 47); cal.set(Calendar.SECOND, 00); cal.set(Calendar.YEAR, 2014); cal.set(Calendar.MONTH, 07); cal.set(Calendar.DAY_OF_MONTH, 28);

您要设置日历到 2014年8月28日上午7时47 。所以这将是从现在起一个月......这个问题的原因是在这里:

You are setting the calendar to the 28th August 2014 7:47 AM. So that would be in a month from now... The cause of this problem is here:

cal.set(Calendar.MONTH, 07);

在日历月份是从零开始:

0 -> January 1 -> Febuary 2 -> March 3 -> April 4 -> May 5 -> June 6 -> July 7 -> August 8 -> September 9 -> October 10 -> November 11 -> December

所以,如果你想设置在七月,你需要做这样的日期的东西:

So if you want to set the date to something in July you need to do it like this:

cal.set(Calendar.MONTH, 6);

也可以尝试加入的运营商和逗号后的空间,让你的code一万次以上的可读性。哦,和一些适当的缩进也将是不错。我已经固定的code格式化这个时候。

编辑:

该警报是重复的,因为你是用设置 setRepeating重复报警()。如果您希望闹钟响一次,那么你只需要调用设置()来代替,就像这样:

The alarm is repeating because you are setting a repeating alarm with setRepeating(). If you want the alarm to go off only once then you just need to call set() instead, like this:

AlarmManager manager = (AlarmManager) getSystemService(Activity.ALARM_SERVICE); manager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);

更多推荐

从AlarmManager报警不会断

本文发布于:2023-11-27 07:38:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1637147.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:AlarmManager

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!