用户在线心跳实现-AlarmManager
来源:互联网 发布:淘宝市场行情分析 编辑:程序博客网 时间:2024/06/04 21:27
在做即时通信或者其他检测是否在线等操作时要用到心跳。比较常用的是AlarmManager全局定时器 去实现。
AlarmManager的使用机制有的称呼为全局定时器,有的称呼为闹钟。其实它的作用和Timer有点相似。都有两种相似的用法:(1)在指定时长后执行某项操作(2)周期性的执行某项操作
AlarmManager对象配合Intent使用,可以定时的开启一个Activity,发送一个BroadCast,或者开启一个Service.
下面的代码详细的介绍了两种定时方式的使用:
(1)在指定时长后执行某项操作
//操作:发送一个广播,广播接收后Toast提示定时操作完成 Intent intent =new Intent(Main.this, alarmreceiver.class); intent.setAction("short"); PendingIntent sender= PendingIntent.getBroadcast(Main.this, 0, intent, 0); //设定一个五秒后的时间 Calendar calendar=Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); calendar.add(Calendar.SECOND, 5); AlarmManager alarm=(AlarmManager)getSystemService(ALARM_SERVICE); alarm.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender); //或者以下面方式简化 //alarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+5*1000, sender); Toast.makeText(Main.this, "五秒后alarm开启", Toast.LENGTH_LONG).show();</span>//注意:receiver记得在manifest.xml注册
<span style="background-color: rgb(255, 255, 255);"> public static class alarmreceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub if(intent.getAction().equals("short")){ Toast.makeText(context, "short alarm", Toast.LENGTH_LONG).show(); }else{ Toast.makeText(context, "repeating alarm", Toast.LENGTH_LONG).show(); } } }(2)周期性的执行某项操作
Intent intent =new Intent(Main.this, alarmreceiver.class); intent.setAction("repeating"); PendingIntent sender=PendingIntent .getBroadcast(Main.this, 0, intent, 0); //开始时间 long firstime=SystemClock.elapsedRealtime(); AlarmManager am=(AlarmManager)getSystemService(ALARM_SERVICE); //5秒一个周期,不停的发送广播 am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP , firstime, 5*1000, sender);
AlarmManager的setRepeating()相当于Timer的Schedule(task,delay,peroid);有点差异的地方时Timer这个方法是指定延迟多长时间
以后开始周期性的执行task;
AlarmManager的取消:(其中需要注意的是取消的Intent必须与启动Intent保持绝对一致才能支持取消AlarmManager)
Intent intent =new Intent(Main.this, alarmreceiver.class); intent.setAction("repeating"); PendingIntent sender=PendingIntent .getBroadcast(Main.this, 0, intent, 0); AlarmManager alarm=(AlarmManager)getSystemService(ALARM_SERVICE); alarm.cancel(sender);
0 0
- 用户在线心跳实现-AlarmManager
- 使用AlarmManager完成应用心跳
- 用户在线统计实现
- AlarmManager定时重复任务,发送心跳
- ajax实现用户在线离线
- php实现在线用户计算
- HttpSessionBindingListener 实现在线用户统计
- Java实现在线用户显示
- Aspx实现在线用户管理
- 通过HttpSessionListener 实现 在线用户 .
- java实现在线用户统计
- Android AlarmManager闹钟实现
- AlarmManager实现定时器、闹钟
- AlarmManager实现闹钟
- 简单的网络心跳包实现(如何确保client在线)
- 用ASP.NET实现在线用户统计
- [原创]jsp实现在线用户列表方法
- 用ASP.NET实现在线用户统计
- 肖鑫铭:非农数据将公布,美国经济或龙或虫
- Android 中ArrayAdapter 的使用
- java 空字符串与null区别
- javascript学习十一:面向对象之prototype
- 黑马程序员_C语言中运算符的总结
- 用户在线心跳实现-AlarmManager
- 优秀的程序员
- MIPS Study Links
- 前端框架-dhtmlx
- Javassist 学习笔记1
- 笔记 疑难整理
- JS页面间数据传递的各种方法和分析
- MySQL学习笔记_5_SQL语言的设计与编写(上)
- VisualStudio 2012中的单元测试