android 消息推送时,长连接的使用(websocket)

     首先要说的是在app开发中,消息推送是必不可少的一个功能,方式有多种,现在简单介绍一下我在项目开发中使用的方法,长连接

优点:开发成本低,数据安全,对于服务器压力较小(相对轮询)

缺点:耗电量高,容易被系统kill,需要一定的技术

使用okhttp和封装的websocket包来实现

代码贴出如下:

//长连接的建立
    static OkHttpClient mOkHttpClient;

    private void initWebSocket() {
        mOkHttpClient = new OkHttpClient.Builder()
                .readTimeout(3000, TimeUnit.SECONDS)//设置读取超时时间
                .writeTimeout(3000, TimeUnit.SECONDS)//设置写的超时时间
                .connectTimeout(3000, TimeUnit.SECONDS)//设置连接超时时间
                .build();
        Users users = null;
        try {
            users = MyApplication.db.selector(Users.class).findFirst();
        } catch (DbException e) {
            e.printStackTrace();
        }
        String url = null;
        if (users != null) {
            url = Constant.DB_URL + Constant.PORT + Constant.XHB_DIR + Constant.SEND_PERSONAL_NEWS + "?userId=" + users.getId(); //改成自已服务端的地址
        }


        Request request = new Request.Builder().url(url).build();
        WebSocketCall webSocketCall = WebSocketCall.create(mOkHttpClient, request);
        webSocketCall.enqueue(new WebSocketListener() {
            private final ExecutorService sendExecutor = Executors.newSingleThreadExecutor();
            private WebSocket webSocket;

            @Override
            public void onOpen(WebSocket webSocket, Response response) {
                Log.d("WebSocketCall", "onOpen");
                this.webSocket = webSocket;
            }

            /**
             * 连接失败
             * @param e
             * @param response Present when the failure is a direct result of the response (e.g., failed
             * upgrade, non-101 response code, etc.). {@code null} otherwise.
             */
            @Override
            public void onFailure(IOException e, Response response) {
                Log.d("WebSocketCall", "onFailure");
            }

            /**
             * 接收到消息
             * @param message
             * @throws IOException
             */
            @Override
            public void onMessage(ResponseBody message) throws IOException {
                final RequestBody response;
                Log.d("WebSocketCall", "onMessage:" + message.source().readByteString().utf8());
                String msg = message.source().readByteString().utf8();
                NotificationResponse personalNewses = new Gson().fromJson(msg, NotificationResponse.class);
                updatePersonalNewses(personalNewses);
                //通知栏发送消息
                if (personalNewses != null && personalNewses.getData() != null && personalNewses.getData().size() > 0) {
                    sendNotification(personalNewses.getData().get(0));
                }

                //通知remindFragment个人消息发生了变化
                EventBus.getDefault().post(new MessageEvent("PersonalNewsUpdate"));


                if (message.contentType() == WebSocket.TEXT) {//
                    response = RequestBody.create(WebSocket.TEXT, "你好");//文本格式发送消息
                } else {
                    BufferedSource source = message.source();
                    Log.d("WebSocketCall", "onMessage:" + source.readByteString());
                    response = RequestBody.create(WebSocket.BINARY, source.readByteString());
                }
                message.source().close();
//                sendExecutor.execute(new Runnable() {
//                    @Override
//                    public void run() {
//                        try {
//                            Thread.sleep(1000*60);
//                            webSocket.sendMessage(response);//发送消息
//                        } catch (IOException e) {
//                            e.printStackTrace(System.out);
//                        } catch (InterruptedException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                });
            }

            @Override
            public void onPong(Buffer payload) {
                Log.d("WebSocketCall", "onPong:");
            }


            /**
             * 关闭
             * @param code The <a href="http://tools.ietf.org/html/rfc6455#section-7.4.1">RFC-compliant</a>
             * status code.
             * @param reason Reason for close or an empty string.
             */
            @Override
            public void onClose(int code, String reason) {
                sendExecutor.shutdown();
            }
        });
    }

附上websocket包的链接,解压后可直接使用

http://download.csdn.net/detail/leven_martin/9725814

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不羁的闰土

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值