首先谢谢 https://blog.csdn.net/u010257931/article/details/79694911 这位老哥的博客 给我我很大的帮助: 下面是我的,可以复制直接使用 1.新建一个service /** * websocket的心跳连接 的服务 */ public class BackService extends Service { public static final String data = "jsondata";//广播标识 private long sendTime = 0L; // 发送心跳包 private Handler mHandler = new Handler(); private Runnable heartBeatRunnable = new Runnable() { @Override public void run() { if (System.currentTimeMillis() - sendTime >= HEART_BEAT_RATE) { boolean isSuccess = mWebSocket.send("");//发送一个空消息给服务器,通过发送消息的成功失败来判断长连接状态 if (!isSuccess) {//长连接已断开 mHandler.removeCallbacks(heartBeatRunnable); mWebSocket.cancel();//取消掉以前的长连接 new InitSocketThread().start();//创建一个新的连接 Log.e("长链接异常常", "尝试再次接连"); } else { //长连接处于连接状态 Log.e("长链接正常", "1111111"); } sendTime = System.currentTimeMillis(); } mHandler.postDelayed(this, HEART_BEAT_RATE);//每隔一定的时间,对长连接进行一次心跳检测 } }; @Override public void onCreate() { super.onCreate(); //开启一个线程 new InitSocketThread().start(); } @Nullable @Override public IBinder onBind(Intent intent) { return null; } //开启线程 class InitSocketThread extends Thread { @Override public void run() { super.run(); try { initSocket(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } /** * 心跳检测时间 */ private static final long HEART_BEAT_RATE = 15 * 1000;//每隔15秒进行一次对长连接的心跳检测 private WebSocket mWebSocket; // 初始化socket private void initSocket() throws UnknownHostException, IOException { OkHttpClient client = new OkHttpClient.Builder().readTimeout(0, TimeUnit.MILLISECONDS).build(); //建立一个链接,这个ws的主机连接是服务器给出的 Request request = new Request.Builder().url("ws://......).build(); client.newWebSocket(request, new WebSocketListener() { @Override public void onOpen(WebSocket webSocket, Response response) {//开启长连接成功的回调 super.onOpen(webSocket, response); mWebSocket = webSocket; Log.e("长链接连接成功", "00000000000000000000"); } @Override public void onMessage(WebSocket webSocket, String text) {//接收消息的回调 super.onMessage(webSocket, text); //接收信息,发送广播 刷新ui Intent intent = new Intent(); intent.setAction(data); intent.putExtra("json", text); sendBroadcast(intent); } @Override public void onMessage(WebSocket webSocket, ByteString bytes) { super.onMessage(webSocket, bytes); } @Override public void onClosing(WebSocket webSocket, int code, String reason) { super.onClosing(webSocket, code, reason); } @Override public void onClosed(WebSocket webSocket, int code, String reason) { super.onClosed(webSocket, code, reason); } @Override public void onFailure(WebSocket webSocket, Throwable t, @Nullable Response response) {//长连接连接失败的回调 super.onFailure(webSocket, t, response); } }); client.dispatcher().executorService().shutdown(); mHandler.postDelayed(heartBeatRunnable, HEART_BEAT_RATE);//开启心跳检测 } @Override public void onDestroy() { super.onDestroy(); if (mWebSocket != null) { mWebSocket.close(1000, null); } } }
2. 在配置文件内声明
<!-- 后台服务-长连接 --> <service android:name=".service.BackService" />
3. 在activity 内 开启服务
//开启心跳的服务 Intent socketservice = new Intent(Activity_ZhiBoRoom.this, BackService.class); startService(socketservice);
4. 在activity 内 注册广播 接受服务器发送来的内容 并接受数据,刷新数据列表
//注册广播,接受长链接 发送过来的信息 IntentFilter filter4 = new IntentFilter(); filter4.addAction(BackService.data); registerReceiver(updata_chatlist, filter4);
private BroadcastReceiver updata_chatlist = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub //接受到 服务器发送的数据, 刷新聊天历史列表 try { JSONObject jsonObject = new JSONObject(intent.getStringExtra("json")); Entity_Chat_History entity_chat_history; entity_chat_history = new Entity_Chat_History(); entity_chat_history.setName(jsonObject.getString("name")); entity_chat_history.setId(jsonObject.getString("id")); entity_chat_history.setImage(jsonObject.getString("image")); entity_chat_history.setBody(jsonObject.getString("body")); entity_chat_history.setTime(jsonObject.getString("time")); chat_datalist.add(entity_chat_history); //总是只显示50条 if (chat_datalist.size() > 50) { chat_datalist.remove(0); } //开启 Ui 线程刷新界面,让列表总是显示最新一条数据 runOnUiThread(new Runnable() { public void run() { adapter_chatRoom.notifyDataSetChanged(); mListView.setSelection(chat_datalist.size()); } }); } catch (Exception e) { e.printStackTrace(); } } };
5. 注销广播
@Override protected void onDestroy() { unregisterReceiver(updata_chatlist); }