我是靠谱客的博主 着急绿茶,最近开发中收集的这篇文章主要介绍Android WebSocket 建立一个长连接(带心跳检测)Activity页面可接发信息,觉得挺不错的,现在分享给大家,希望可以做个参考。
概述
1.导包
implementation "org.java-websocket:Java-WebSocket:1.4.0"
2.创建一个Socket类
import android.util.Log;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;
import java.net.URI;
/**
* Time:2020/5/11
* <p>
* Author:lichao
* <p>
* Description:
*/
public class JWebSocketClient extends WebSocketClient {
public JWebSocketClient(URI serverUri) {
super(serverUri, new Draft_6455());
}
@Override
public void onOpen(ServerHandshake handshakedata) {
Log.e("JWebSocketClient", "onOpen()");
}
@Override
public void onMessage(String message) {
Log.e("JWebSocketClient", "onMessage()");
}
@Override
public void onClose(int code, String reason, boolean remote) {
Log.e("JWebSocketClient", "onClose()");
}
@Override
public void onError(Exception ex) {
Log.e("JWebSocketClient", "onError()");
}
}
3.服务类
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import org.java_websocket.handshake.ServerHandshake;
import java.net.URI;
/**
* Time:2020/5/11
* <p>
* Author:lichao
* <p>
* Description:
*/
public class JWebSocketClientService extends Service {
private String TAG="JWebSocketClientService";
private URI uri;
public JWebSocketClient client;
private JWebSocketClientBinder mBinder = new JWebSocketClientBinder();
//用于Activity和service通讯
public class JWebSocketClientBinder extends Binder {
public JWebSocketClientService getService() {
return JWebSocketClientService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public void onCreate() {
super.onCreate();
//初始化websocket
initSocketClient();
mHandler.postDelayed(heartBeatRunnable, HEART_BEAT_RATE);//开启心跳检测
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
/**
* 初始化websocket连接
*/
private void initSocketClient() {
URI uri = URI.create("ws://121.40.165.18:8800");//测试使用
client = new JWebSocketClient(uri) {
@Override
public void onMessage(String message) {
Log.e("JWebSocketClientService", "收到的消息:" + message);
Intent intent = new Intent();//广播接收到的消息,在Activity接收
intent.setAction("com.xxx.servicecallback.content");
intent.putExtra("message", message);
sendBroadcast(intent);
}
@Override
public void onOpen(ServerHandshake handshakedata) {
super.onOpen(handshakedata);
Log.e("JWebSocketClientService", "websocket连接成功");
}
};
connect();
}
/**
* 连接websocket
*/
private void connect() {
new Thread() {
@Override
public void run() {
try {
//connectBlocking多出一个等待操作,会先连接再发送,否则未连接发送会报错
client.connectBlocking();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
}
// -------------------------------------websocket心跳检测------------------------------------------------
private static final long HEART_BEAT_RATE = 10 * 1000;//每隔10秒进行一次对长连接的心跳检测
private Handler mHandler = new Handler();
private Runnable heartBeatRunnable = new Runnable() {
@Override
public void run() {
Log.e("JWebSocketClientService", "心跳包检测websocket连接状态");
if (client != null) {
if (client.isClosed()) {
reconnectWs();
}else {
//业务逻辑 这里如果服务端需要心跳包为了防止断开 需要不断发送消息给服务端
// client.send("");
}
} else {
//如果client已为空,重新初始化连接
client = null;
initSocketClient();
}
//每隔一定的时间,对长连接进行一次心跳检测
mHandler.postDelayed(this, HEART_BEAT_RATE);
}
};
/**
* 开启重连
*/
private void reconnectWs() {
mHandler.removeCallbacks(heartBeatRunnable);
new Thread() {
@Override
public void run() {
try {
Log.e("JWebSocketClientService", "开启重连");
client.reconnectBlocking();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
}
}
4.Activity
private JWebSocketClientService.JWebSocketClientBinder binder;
private JWebSocketClientService jWebSClientService;
private JWebSocketClient client;
private ChatMessageReceiver chatMessageReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startJWebSClientService();//启动服务
bindService();//绑定服务
doRegisterReceiver();//注册广播
}
/**
* 动态广播接收消息
*/
private class ChatMessageReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String message=intent.getStringExtra("message");
Log.e(TAG, "-----接收服务端数据"+message);
}
}
/**
* 动态注册广播
*/
private void doRegisterReceiver() {
chatMessageReceiver = new ChatMessageReceiver();
IntentFilter filter = new IntentFilter("com.xxx.servicecallback.content");
registerReceiver(chatMessageReceiver, filter);
}
/**
* 注销广播
*/
private void unRegisterReceiver() {
unregisterReceiver(chatMessageReceiver);
}
/**
* 启动服务(websocket客户端服务)
*/
private void startJWebSClientService() {
Intent intent = new Intent(this, JWebSocketClientService.class);
startService(intent);
}
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
//服务与活动成功绑定
Log.e(TAG, "服务与活动成功绑定");
binder = (JWebSocketClientService.JWebSocketClientBinder) iBinder;
jWebSClientService = binder.getService();
client = jWebSClientService.client;
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
//服务与活动断开
Log.e(TAG, "服务与活动成功断开");
}
};
/**
* 绑定服务
*/
private void bindService() {
Intent bindIntent = new Intent(MainActivity.this,
JWebSocketClientService.class);
bindService(bindIntent, serviceConnection, BIND_AUTO_CREATE);
}
@Override
protected void onDestroy() {
super.onDestroy();
unRegisterReceiver();
unbindService(serviceConnection);
}
websocket 测试地址:
http://www.websocket-test.com/
http://ws.douqq.com/
最后
以上就是着急绿茶为你收集整理的Android WebSocket 建立一个长连接(带心跳检测)Activity页面可接发信息的全部内容,希望文章能够帮你解决Android WebSocket 建立一个长连接(带心跳检测)Activity页面可接发信息所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复