1、websocket Service类
package com.wolong.rtmp.service;
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 androidx.annotation.Nullable;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wolong.rtmp.Constants;
import com.wolong.rtmp.Message;
import org.java_websocket.handshake.ServerHandshake;
import java.net.URI;
/**
* 服务类 JWebSocketClientService
* @author zpn
*/
public class JWebSocketClientService extends Service {
private String TAG = "JWebSocketClientService";
private String mAddress = Constants.SERVER_IP_WEBSOCKET;
private URI uri;
public JWebSocketClient client;
private JWebSocketClientBinder mBinder = new JWebSocketClientBinder();
//用于Activity和service通讯
public class JWebSocketClientBinder extends Binder {
public JWebSocketClientService getService() {
return JWebSocketClientService.this;
}
}
@Nullable
@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);
}
@Override
public void onDestroy() {
closeConnect();
super.onDestroy();
}
public JWebSocketClientService() {
}
/**
* 初始化websocket连接
*/
private void initSocketClient() {
URI uri = URI.create(mAddress);
client = new JWebSocketClient(uri) {
@Override
public void onMessage(String message) {
Log.d("msg", "收到的消息:" + message);
Message msg = (Message) JSONObject.parseObject(message,Message.class);
String opt = msg.getOpt()==null?"":msg.getOpt();
if(opt.equals(URI_NEWLINK)){
onLoginListener.setLoginState(msg.getMessage());
}
}
@Override
public void onOpen(ServerHandshake handshakedata) {
super.onOpen(handshakedata);
Log.d("msg", "websocket连接成功");
}
};
connect();
}
/**
* 连接websocket
*/
private void connect() {
new Thread() {
@Override
public void run() {
try {
//connectBlocking多出一个等待操作,会先连接再发送,否则未连接发送会报错
client.connectBlocking();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
}
/**
* 发送消息
*
* @param msg
*/
public void sendMsg(String msg) {
if (null != client) {
Log.d("msg", "发送的消息:" + msg);
client.send(msg);
}
}
/**
* 断开连接
*/
private void closeConnect() {
try {
if (null != client) {
client.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
client = null;
}
}
// -------------------------------------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.d("msg", "心跳包检测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.d("msg","重新连接");
client.reconnectBlocking();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
}
/**********************************接口回调********************************************/
private static final String URI_NEWLINK = "newLink";
private OnLoginListener onLoginListener;
/**
* 注册回调接口的方法,供外部调用
* @param onLoginListener
*/
public void setOnLoginListener(OnLoginListener onLoginListener) {
this.onLoginListener = onLoginListener;
}
/**
* 建立连接 socket 用户
* @param username
*/
public void setSocketLink(String username){
sendMsg(JSON.toJSONString(new Message(URI_NEWLINK,username,"success")));
}
}
2、第一个Activity
public class OneActivity extends AppCompatActivity {
private Context mContext;
private JWebSocketClientService.JWebSocketClientBinder binder;
private JWebSocketClientService jWebSClientService;
private JServiceConnection serviceConnection;
private class JServiceConnection implements ServiceConnection{
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
Log.d("msg", "OneActivity 服务与活动成功绑定");
binder = (JWebSocketClientService.JWebSocketClientBinder) iBinder;
jWebSClientService = binder.getService();
client = jWebSClientService.client;
jWebSClientService.setOnLoginListener(new OnLoginListener() {
@Override
public void setLoginState(String state) {
Log.d("msg","回传消息==="+state);
if(state.equals("success")){
Intent it = new Intent(OneActivity.this, TwoActivity.class);
Bundle bd = new Bundle();
bd.putString("username", currentUsername);
it.putExtras(bd);
startActivity(it);
}
}
});
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
jWebSClientService = null;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unbindService(serviceConnection);// 解除绑定,断开连接
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = OneActivity.this;
serviceConnection = new JServiceConnection();
bindService();//绑定服务
startJWebSClientService();//启动服务
jWebSClientService.setSocketLink(currentUsername);
}
/**
* 绑定服务
*/
private void bindService() {
Intent bindIntent = new Intent(mContext, JWebSocketClientService.class);
bindService(bindIntent, serviceConnection, BIND_AUTO_CREATE);
}
/**
* 启动服务(websocket客户端服务)
*/
private void startJWebSClientService() {
Intent intent = new Intent(mContext, JWebSocketClientService.class);
startService(intent);
}
}
3、第二个Activity
public class TwoActivity extends AppCompatActivity {
private Handler mHandler = new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
String mm= msg.getData().getString("msg");
tv_mess.setText(mm);//UI显示
}
};
private Context mContext;
private JWebSocketClientService.JWebSocketClientBinder binder;
private JWebSocketClientService jWebSClientService;
private JServiceConnection serviceConnection;
private class JServiceConnection implements ServiceConnection {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
Log.d("msg", "TwoActivity服务与活动成功绑定");
binder = (JWebSocketClientService.JWebSocketClientBinder) iBinder;
jWebSClientService = binder.getService();
jWebSClientService.setOnLiveRoom(username);
jWebSClientService.setOnLiveRoomListener(new OnLiveRoomListener() {
@Override
public void setLiveRoom(String mm) {
Message message = new Message();
Bundle bundle = new Bundle();
bundle.putString("msg",mm);
message.setData(bundle);
mHandler.sendMessage(message);
}
});
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
jWebSClientService = null;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mContext = TwodActivity.this;
serviceConnection = new JServiceConnection();
bindService(new Intent(mContext, JWebSocketClientService.class),
serviceConnection, BIND_AUTO_CREATE);
startService(new Intent(mContext, JWebSocketClientService.class));
}
@Override
protected void onDestroy() {
super.onDestroy();
unbindService(serviceConnection);// 解除绑定,断开连接
}
}
4、OnLoginListener 接口
public interface OnLoginListener {
void setLoginState(String state);
}
5、Message类
import java.io.Serializable;
public class Message implements Serializable {
private static final long serialVersionUID = -6613245021696183230L;
private String date;
private String message;
private String opt; //方法名
private String uname;//当前用户
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getOpt() { return opt; }
public void setOpt(String opt) { this.opt = opt; }
public String getUname() { return uname; }
public void setUname(String uname) { this.uname = uname; }
public Message(){}
public Message(String opt,String msg){
this.opt = opt;
this.message = msg;
}
public Message(String opt,String uname,String msg){
this.opt = opt;
this.uname = uname;
this.message = msg;
}