使用AlarmManager完成应用心跳

在开发互联网应用时候,我们常常要使用心跳来保证客户端与服务器的连接。怎么完成心跳很关键,前几天看了下某推送公司的架构介绍,在说道客户端心跳功能时,说道如果使用Timer或者专门开起一个线程来做心跳的工作,会浪费CPU工作时间,而且也会更多的消耗电量。相对来说使用AlarmManager来处理心跳的话,使用的是系统全局的定时服务,会一定成都减少CPU的消耗,耗电量也会少很多。正好这段时间也要做推送,就顺便学习了一下怎么做心跳,写了一个demo,分享给大家,也和大家讨论一下这么做的利弊。
关闭AlarmManager的介绍,参考这篇文章:http://jinguo.iteye.com/blog/799778

AlarmManager处理心跳间隔的相关代码如下:
?
代码片段,双击复制
01
02
03
04
05
06
07
08
09
10
11
12
13
14
private AlarmManager mAlarmManager;
        private PendingIntent mPendingIntent;
         
        mAlarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        mPendingIntent = PendingIntent.getBroadcast( this , 0 , new Intent(
                        Const.ACTION_HEARTBEAT), PendingIntent.FLAG_UPDATE_CURRENT);
                                 
        // 启动心跳定时器
        long triggerAtTime = SystemClock.elapsedRealtime() + HEARTBEAT_INTERVAL;
        mAlarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME,
triggerAtTime, HEARTBEAT_INTERVAL, mPendingIntent);
                         
//取消心跳定时器
                mAlarmManager.cancel(mPendingIntent);

定义一个广播接收器,在接收器中处理与服务器的连接等操作:
?
代码片段,双击复制
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
public class HeartReceiver extends BroadcastReceiver {
 
        private static final String TAG = "HeartReceiver" ;
 
        @Override
        public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                Log.d(TAG, "action" + action);
                if (Const.ACTION_START_HEART.equals(action)) {
                        Log.d(TAG, "Start heart" );
                } else if (Const.ACTION_HEARTBEAT.equals(action)) {
                        Log.d(TAG, "Heartbeat" );
                        //在此完成心跳需要完成的工作,比如请求远程服务器……
                } else if (Const.ACTION_STOP_HEART.equals(action)) {
                        Log.d(TAG, "Stop heart" );
                }
        }
 
}


具体代码见附件吧,再次还有两个疑问,不是很明白。AlarmManager.ELAPSED_REALTIME和AlarmManager.ELAPSED_REALTIME_WAKEUP分别是在系统睡眠状态时不唤醒和唤醒系统。首先不是很明白系统睡眠状态到底是什么时候才会进入,其次作为心跳要不要唤醒系统。这两个疑问希望有高手能够指点。

HeartbeatDemo.rar

1.29 MB, 下载次数: 6, 下载积分: e币 -2 元

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值