使用此代码,我使用onCreate
在MainActivity
的{{1}}设置了警报:
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
但是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);
}
}
中的Toasts
都没有显示出来?谁能告诉我我做错了什么?
答案 0 :(得分:1)
我认为问题在于:
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 。那就是从现在开始的一个月......这个问题的原因在于:
cal.set(Calendar.MONTH, 07);
Calendar
中的月份从零开始:
0 -> January
1 -> Febuary
2 -> March
3 -> April
4 -> May
5 -> June
6 -> July
7 -> August
8 -> September
9 -> October
10 -> November
11 -> December
因此,如果您想在7月份将日期设置为某事,则需要按照以下方式进行:
cal.set(Calendar.MONTH, 6);
还尝试在运算符周围添加空格,在逗号后面,使代码的可读性提高一百万倍。哦,一些适当的凹痕也会很好。我这次已经修改了你的代码格式。
修改强>
警报正在重复,因为您正在使用setRepeating()
设置重复警报。如果您只想让闹钟响一次,那么您只需拨打set()
,就像这样:
AlarmManager manager = (AlarmManager) getSystemService(Activity.ALARM_SERVICE);
manager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);