通过这个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报警不会断
发布评论