Android闹钟服务AlarmManager介绍
Android闹钟服务AlarmManager是Android系统提供的一种定时服务,它可以让应用程序在指定时间执行特定的任务,并且可以指定多个任务,在指定的时间执行。它提供了多种定时服务,包括定时执行任务、定时发送广播、定时发送通知等。
Android闹钟服务AlarmManager使用方法
使用Android闹钟服务AlarmManager的使用方法非常简单,只需要实现一个AlarmReceiver类,实现onReceive()方法,在该方法中实现所需要执行的任务,使用AlarmManager的set()方法设置定时任务,设置定时任务的参数有:
- type:定时任务类型,有ELAPSED_REALTIME、ELAPSED_REALTIME_WAKEUP、RTC和RTC_WAKEUP四种。
- triggerAtTime:定时任务触发的时间,如果type为ELAPSED_REALTIME或ELAPSED_REALTIME_WAKEUP,则该参数为从系统开机到当前的毫秒数;如果type为RTC或RTC_WAKEUP,则该参数为指定的日期时间。
- interval:定时任务的间隔时间,只有当type为ELAPSED_REALTIME、ELAPSED_REALTIME_WAKEUP、RTC_WAKEUP时才有效。
- operation:定时任务要执行的动作,由PendingIntent来指定。
使用AlarmManager的cancel()方法可以取消指定的定时任务,取消定时任务的参数也是PendingIntent,只需要传入和设置定时任务时使用的PendingIntent即可取消定时任务。
Android闹钟服务AlarmManager示例
//设置定时任务 AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(this, AlarmReceiver.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0); alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 10 * 1000, pendingIntent); //取消定时任务 AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(this, AlarmReceiver.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0); alarmManager.cancel(pendingIntent);
Android闹钟服务AlarmManager
Android闹钟服务AlarmManager是Android系统提供的一种定时服务,可以让应用程序在指定时间执行特定的任务,它提供了多种定时服务,使用起来也非常简单,只需要实现一个AlarmReceiver类,实现onReceive()方法,在该方法中实现所需要执行的任务,使用AlarmManager的set()方法设置定时任务,使用AlarmManager的cancel()方法可以取消指定的定时任务。