灯火互联
管理员
管理员
  • 注册日期2011-07-27
  • 发帖数41778
  • QQ
  • 火币41290枚
  • 粉丝1086
  • 关注100
  • 终身成就奖
  • 最爱沙发
  • 忠实会员
  • 灌水天才奖
  • 贴图大师奖
  • 原创先锋奖
  • 特殊贡献奖
  • 宣传大使奖
  • 优秀斑竹奖
  • 社区明星
阅读:2661回复:0

Android API Demos学习 - Alarm部分

楼主#
更多 发布于:2012-09-06 14:03

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);
停止的方法也一样。


喜欢0 评分0
游客

返回顶部