Android基于AlarmManager实现用户在线心跳功能示例
本文实例讲述了Android基于AlarmManager实现用户在线心跳功能。分享给大家供大家参考,具体如下:
在做即时通信或者其他检测是否在线等操作时要用到心跳。比较常用的是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();
注意:receiver记得在manifest.xml注册
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);
更多关于Android相关内容感兴趣的读者可查看本站专题:《Android视图View技巧总结》、《Android编程之activity操作技巧总结》、《Android布局layout技巧总结》、《Android开发入门与进阶教程》、《Android资源操作技巧汇总》及《Android控件用法总结》
希望本文所述对大家Android程序设计有所帮助。
- android10 隐藏SystemUI锁屏下的多用户图标的示例代码
- Android 如何拦截用户频繁操作(点击事件)
- Android实现用户圆形头像和模糊背景
- Android实现简单用户注册案例
- Android启动页用户相关政策弹框的实现代码
- 详解Android Studio实现用户登陆界面demo(xml实现)
- android实现记住用户名和密码以及自动登录
- Android权限如何禁止以及友好提示用户开通必要权限详解
- Android百度地图定位、显示用户当前位置
- Android模拟用户点击的实现方法
- Android EditText 监听用户输入完成的实例
- Android 用户Session管理的设计方案
- Android 多用户详情
相关文章
Android RecyclerView下拉刷新和上拉加载更多
这篇文章主要为大家详细介绍了Android RecyclerView下拉刷新和上拉加载更多,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2016-12-12Android 让自定义TextView的drawableLeft与文本一起居中
本文主要介绍Android 自定义控件TextView显示居中问题,在开发过程中经常会遇到控件的重写,这里主要介绍TextView的drawableLeft与文本一起居中的问题2016-07-07
最新评论