Android中关于长连接的使用

来源:互联网 发布:淘宝天猫运营 编辑:程序博客网 时间:2024/06/04 19:23
1.首先在AndroidManifest.xml中静态注册用户解锁行为的广播:android.intent.action.USER_PRESENT.
<!-- APP的广播接收器 --><receiver android:name=".receiver.AppReceiver"><span style="white-space:pre"></span><intent-filter><span style="white-space:pre"></span><action android:name="android.intent.action.USER_PRESENT"/><span style="white-space:pre"></span></intent-filter></receiver>

2.用户锁屏解锁后,系统发送广播android.intent.action.USER_PRESENT,然后在AppReceiver.java中接收广播
public class AppReceiver extends BroadcastReceiver {<span style="white-space:pre"></span>private static final String TAG = "AppReceiver";<span style="white-space:pre"></span>@Override<span style="white-space:pre"></span>public void onReceive(Context context, Intent intent) {<span style="white-space:pre"></span>String action = intent.getAction();<span style="white-space:pre"></span>if (Intent.ACTION_USER_PRESENT.equals(action)) { //手机解锁<span style="white-space:pre"></span>// 检查长连接<span style="white-space:pre"></span>PushService.actionCheck(context);<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}}

3.在PushService.java中执行一系列动作
//启动Serviceprivate static final String ACTION_CHECK = "pushservice.check";public static void actionCheck(Context context) {Intent intent = new Intent(context, PushService.class);intent.setAction(ACTION_CHECK);context.startService(intent);}//对Service做处理@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {if (intent != null) {String action = intent.getAction();if (action  != null) {action.equals(ACTION_CHECK) {checkPushService();//检查PushService是否运行}}}}//检查PushService的几种情况:    //1.用户锁屏解锁后    //2.手机网络情况发生改变    //3.连接断开时    //4.定时检查private void checkPushService() {if (pushClient != null && pushClient.isWorking()) {Log.d(TAG, "长连接正在运行...");} else {Log.d(TAG,"长连接断开,需要重新启动");startPushService();}}//启动长连接//启动PushService,总是重启PushClient,不做状态检查,目前在以下几种情况下会调用该方法://1. 系统重启  2. 用户登录  3. 检查PushService状态不正常时private void startPushService() {Log.d(TAG,"正在启动长连接...");stopKeepPushServiceAlive();startKeepPushServiceAlive();startPushClient(userId);}//停止计时public void stopKeepPushServiceAlive() {Log.d(TAG,"stopKeepPushServiceAlive()");Intent intent = new Intent();intent.setClass(PushService.this, PushService.class);intent.setAction(ACTION_CHECK);PendingIntent pi = PendingIntent.getService(PushService.this, KEEP_ALIVE_ALARM_ID, intent ,PendingIntent.FLAG_UPDATE_CURRENT);AlarmManager alarmMgr = (AlarmManager) PushService.this.getSystemService(ALARM_SERVICE);alarmMgr.cancel(pi);}//重新开始计时public static final int KEEP_ALIVE_ALARM_ID = 2001;private static final long KEEP_ALIVE_INTERVAL = 5 * 60 * 1000;public void startKeepPushServiceAlive() {Intent intent = new Intent();intent.setClass(PushService.this, PushService.class);intent.setAction(ACTION_CHECK);PendingIntent pi = PendingIntent.getService(PushService.this, KEEP_ALIVE_ALARM_ID, intent, PendingIntent.FLAG_UPDATE_CURRENT);AlarmManager alarmMgr = (AlarmManager) PushService.this.getSystemService(ALARM_SERVICE);alarmMgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + KEEP_ALIVE_INTERVAL, KEEP_ALIVE_INTERVAL, pi);}//private startPushClient(String  userId) {if (pushClient != null) {pushClient.stopPushService(true);}if (Utils.isNetworkAvailable(this)) {pushClient = new PushClient(userId, 150);pushClient.asynStartLoop(this);Log.d(TAG, "start push client, userId =" + userId);} else {Log.d(TAG, "network not available when start push client");}}//连接成功的通知@Overridepublic void connectionSuccess() {// 拉取新的消息Log.d(TAG, "connectionSuccess Thread id = " + Thread.currentThread().getId());mHandler.obtainMessage(MSG_CONNECTED_SOCKET).sendToTarget();}//private Callback mPushMessageCallback = new Callback() {@Overridepublic boolean handleMessage(Message msg) {switch (msg.what) {case MSG_CONNECTED_SOCKET:onConnected();break;}}};//当PushClient连接成功后,清空重试次数,加载新消息.private void onConnected() {Log.d(TAG, "push service connected");this.retries.set(0);// 长连接消息的有效时间为5分钟,如果断开时间不到3分钟,不再主动拉取消息long now = System.currentTimeMillis();if (now - lastConnectedTime < TimeUnit.SECONDS.toMillis(180) ||(mLoadingNewMessageTask != null && mLoadingNewMessageTask.getTaskStatus() == Status.RUNNING)) {return;}lastConnectedTime = now;pullNewMessageList();}


0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 手被锤子砸肿了怎么办 拇指突然疼肿了怎么办 手指甲压紫了痛怎么办 砸到手指头肿了怎么办 小婴儿体重不长怎么办 2岁半宝宝不说话怎么办 米兰叶子掉光了怎么办 qq雷霆战机闪退怎么办 微信限额20万怎么办 欧拉方程x<0怎么办 柿子核吃下去了怎么办 橡胶底白色变黄怎么办 20了丁丁还很小怎么办 5角硬币吞进肚子怎么办 孩子吞了5角硬币怎么办 左腿比右腿微粗怎么办 一个腿长一个腿短怎么办 刚买的毛笔很硬怎么办 我哥哥太爱我了怎么办 如果婚姻无法维持该怎么办 捡了一只流浪狗怎么办 微博加载不出来怎么办 我的脾气很暴躁怎么办 歌单恢复已删除怎么办 家里破产了我该怎么办 对付有心计的人怎么办 上嘴唇无故肿了怎么办 下嘴唇肿了一半怎么办 狗狗早上叫不停怎么办 狗在家乱咬东西怎么办 狗狗晚上一直叫怎么办 金毛幼犬晚上叫怎么办 金毛晚上老是叫怎么办 5岁宝宝总尿裤子怎么办 2岁宝宝尿裤子怎么办 2周岁宝宝尿裤子怎么办 5岁宝宝尿裤子怎么办 模拟人生4不怀孕怎么办 狗狗的毛打结怎么办 狗狗生病了不吃东西怎么办 给领导送礼不收怎么办