Android API Demos学习 - Alarm部分
3222 点击·0 回帖
![]() | ![]() | |
![]() | 1. Alarm Controller Alarm是Android中的闹铃服务。允许我们定时执行我们的程序,只要设备没有关机或者重启,都会被唤醒执行。 1.1 One Shot Alarm 例子展示了30秒后发送一个广播,接收后弹出一个提示信息。 Intent intent = new Intent(AlarmController.this, OneShotAlarm.class); PendingIntent sender = PendingIntent.getBroadcast(AlarmController.this, 0, intent, 0); // We want the alarm to go off 30 seconds from now. Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); calendar.add(Calendar.SECOND, 30); // Schedule the alarm! AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE); am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender); PendingIntent是intent的一个描述,可以在一段时间后调用它。 使用getSystemService方法获得AlarmManager 。 在OneShotAlarm.java中的onReceive方法可以接收这个intent。 public void onReceive(Context context, Intent intent) { Toast.makeText(context, R.string.one_shot_received, Toast.LENGTH_SHORT).show(); } 1.2 Repeating Alarm 每十五秒发送一个广播,接收后弹出一个提示信息。 long firstTime = SystemClock.elapsedRealtime(); firstTime += 15*1000; AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE); am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, 15*1000, sender); SystemClock.elapsedRealtime()方法取得从开机到现在的毫秒数。 setRepeating (int type, long triggerAtTime, long interval, PendingIntent operation)方法中triggerAtTime是第一次执行的时间,interval是循环的间隔。 am.cancel(sender); 停止循环执行。 灯火电脑 www.atcpu.com 2. Alarm Service 每隔30秒启动一次服务。 mAlarmSender = PendingIntent.getService(AlarmService.this, 0, new Intent(AlarmService.this, AlarmService_Service.class), 0); 其他方法和上面很相似,只是这个例子是启动一个service,通常service用做处理时间比较长的任务。 am.cancel(mAlarmSender); 停止的方法也一样。 | |
![]() | ![]() |