1、添加依赖 implementation "org.java-websocket:Java-WebSocket:1.4.0"
2、配置三个类
(1)JWebSocketClientpublic 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()");
}
}
复制代码
(2)JWebSocketClientServicepublic class JWebSocketClientService extends Service {
public JWebSocketClient client;
private JWebSocketClientBinder mBinder = new JWebSocketClientBinder();
private final static int GRAY_SERVICE_ID = 1001;
//灰色保活
public static class GrayInnerService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
startForeground(GRAY_SERVICE_ID, new Notification());
stopForeground(true);
stopSelf();
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
PowerManager.WakeLock wakeLock;//锁屏唤醒
//获取电源锁,保持该服务在屏幕熄灭时仍然获取CPU时,保持运行
@SuppressLint("InvalidWakeLockTag")
private void acquireWakeLock()
{
if (null == wakeLock)
{
PowerManager pm = (PowerManager)this.getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK|PowerManager.ON_AFTER_RELEASE, "PostLocationService");
if (null != wakeLock)
{
wakeLock.acquire();
}
}
}
//用于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();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//初始化websocket
initSocketClient();
mHandler.postDelayed(heartBeatRunnable, HEART_BEAT_RATE);//开启心跳检测
//设置service为前台服务,提高优先级
// if (Build.VERSION.SDK_INT < 18) {
// //Android4.3以下 ,隐藏Notification上的图标
// startForeground(GRAY_SERVICE_ID, new Notification());
// } else if(Build.VERSION.SDK_INT>18 && Build.VERSION.SDK_INT<25){
// //Android4.3 - Android7.0,隐藏Notification上的图标
// Intent innerIntent = new Intent(this, GrayInnerService.class);
// startService(innerIntent);
// startForeground(GRAY_SERVICE_ID, new Notification());
// }else{
// //Android7.0以上app启动后通知栏会出现一条"正在运行"的通知
startForeground(GRAY_SERVICE_ID, new Notification());
// }
acquireWakeLock();
return START_STICKY;
}
@Override
public void onDestroy() {
closeConnect();
super.onDestroy();
}
public JWebSocketClientService() {
}
/**
* 初始化websocket连接
*/
private void initSocketClient() {
URI uri = URI.create(WebSocketUtil.ws);
client = new JWebSocketClient(uri) {
@Override
public void onMessage(String message) {
Log.e("onmessage1111111", message);
if(!message.equals("server...Leave...")) {
EventBus.getDefault().post(new MessageEvent(message));
}
// Intent intent = new Intent();
// intent.setAction("com.xch.servicecallback.content");
// intent.putExtra("message", message);
// sendBroadcast(intent);
// checkLockAndShowNotification(message);
}
@Override
public void onOpen(ServerHandshake handshakedata) {
super.onOpen(handshakedata);
Log.e("JWebSocketClientService", "websocket连接成功");
ToastUtils.showShort("websocket连接成功");
}
@Override
public void onError(Exception ex) {
super.onError(ex);
ToastUtils.showShort("websocket连接失败");
Log.e("JWebSocketClientService",ex+"");
}
};
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.e("JWebSocketClientService", "发送的消息:" + msg);
client.send(msg);
}
}
/**
* 断开连接
*/
private void closeConnect() {
try {
if (null != client) {
client.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
client = null;
}
}
// -----------------------------------消息通知--------------------------------------------------------
/**
* 检查锁屏状态,如果锁屏先点亮屏幕
*
* @param content
*/
private void checkLockAndShowNotification(String content) {
//管理锁屏的一个服务
KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
if (km.inKeyguardRestrictedInputMode()) {//锁屏
//获取电源管理器对象
PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
if (!pm.isScreenOn()) {
@SuppressLint("InvalidWakeLockTag") PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP |
PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "bright");
wl.acquire(); //点亮屏幕
wl.release(); //任务结束后释放
}
sendNotification(content);
} else {
sendNotification(content);
}
}
/**
* 发送通知
*
* @param content
*/
private void sendNotification(String content) {
Intent intent = new Intent();
intent.setClass(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager notifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new NotificationCompat.Builder(this)
.setAutoCancel(true)
// 设置该通知优先级
.setPriority(Notification.PRIORITY_MAX)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("服务器")
.setContentText(content)
.setVisibility(VISIBILITY_PUBLIC)
.setWhen(System.currentTimeMillis())
// 向通知添加声音、闪灯和振动效果
.setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_ALL | Notification.DEFAULT_SOUND)
.setContentIntent(pendingIntent)
.build();
notifyManager.notify(1, notification);//id要保证唯一
}
// -------------------------------------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() {
if (client != null) {
if (client.isClosed()) {
reconnectWs();
}else if(client.isOpen()){
Log.e("JWebSocketClientService", "心跳包检测websocket连接状态");
}
} 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();
}
}
复制代码
(3)WebSocketUtilpublic class WebSocketUtil {
public static final String ws = "ws://192.168.43.14:8080";//websocket测试地址
public static void showToast(Context ctx, String msg) {
Toast.makeText(ctx, msg, Toast.LENGTH_LONG).show();
}
}复制代码
3、在androidManifest理注册service
android:name=".util.JWebSocketClientService"
android:enabled="true"
android:exported="true" />
android:name=".util.JWebSocketClientService$GrayInnerService"
android:enabled="true"
android:exported="false"
android:process=":gray" />复制代码