我有一个用于创建alarmManager
主要活动
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, 14);
c.set(Calendar.MINUTE, 41);
c.set(Calendar.SECOND, 0);
Intent intentAlarm = new Intent(this, AlarmReceiver.class);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC,c.getTimeInMillis(), pendingIntent.getBroadcast(this, 0, intentAlarm, pendingIntent.FLAG_ONE_SHOT));
在AlarmReceive
课程中我有:
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm Scheduled for Tommrrow", Toast.LENGTH_LONG).show();
intent = new Intent(context, firstservice.class);
context.startService(intent);
}
在服务firstservice
我做了一些操作。问题是警报是按时调用广播接收器,但在此之后,当我打开应用程序时,它也会调用广播接收器,这意味着该服务再次运行。
答案 0 :(得分:1)
我也有这个问题。几个小时后,我可以指出这个解决方案的问题。简而言之,我使用了意图附加功能来通知闹钟时间。
在manifest.xml中,注册接收者。 <receiver android:name=".receivers.DayAlarmReceiver"/>
这就是我设置闹钟管理器的方式
public void setDayAlarm(Context context) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 4);
AlarmManager alarmMgr = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent alarmIntent = new Intent(context, DayAlarmReceiver.class);
alarmIntent.putExtra("HOUR_OF_DAY", 4);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 5555, alarmIntent, 0);
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY, pendingIntent);
Log.d("Set the day alarm");
}
这是我的DayAlarmReceiver类的OnReceive()方法
@Override
public void onReceive(Context context, Intent intent) {
int setHour = intent.getIntExtra("HOUR_OF_DAY", -1);
Calendar rightNow = Calendar.getInstance();
int currentHour = rightNow.get(Calendar.HOUR_OF_DAY);
if(currentHour == setHour){
Log.d("This is perfect, Trigger the alarm");
showNotification(context, msg);
}else{
Log.d("This is perfect, Trigger the alarm");
}
快乐编码:)
答案 1 :(得分:0)
尝试为您的意图添加额外内容,并检查它以区分您的预定闹钟与您的接收器所服务的任何其他广播
...
c.set(Calendar.SECOND, 0);
Intent intentAlarm = new Intent(this, AlarmReceiver.class);
intentAlarm.putExtra("myalarm",Boolean.TRUE)
AlarmManager alarmManager = (AlarmManager) ...
public void onReceive(Context context, Intent intent) {
if (null != intent){
Bundle extras = intent.getExtras();
if(extras != null && extras.getBoolean("myalarm", Boolean.TRUE)){
//Do your actions ...
}
}
}