我有用于创建 alarmManager 主要活动的代码
I have a code for creating an alarmManager main activity
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); }在使用中第一服务我做了一些手术。问题在于警报正在按时调用广播接收器,但是之后,当我打开应用程序时,它也会调用广播接收器,这意味着服务将再次运行。
In service firstservice I did some operation. The problem is that the alarm is calling the broadcast receiver on time but after that when I open the app it also call the broadcast receiver and this mean that the service is worked again.
推荐答案我也遇到了这个问题。在几个小时之后,我可以指出此解决方案的问题。简而言之,我已经使用了意图附加功能来通知警报时间。
I also had this problem. After copple of hours, I could point out the problem with this solution. In brief I have used intent extras to notify the alarm time.
在manifest.xml中,注册接收者。
in the manifest.xml, register the receiver.
<receiver android:name=".receivers.DayAlarmReceiver"/>这是我设置警报管理器的方式
This is how I set the alarm manager
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()方法
This is the OnReceive() method of my DayAlarmReceiver class
@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"); }快乐编码:)
更多推荐
每当我打开应用程序时,Android中的AlarmManager都会运行
发布评论