338 lines
11 KiB
Java
338 lines
11 KiB
Java
package com.fuying.sn.service;
|
||
|
||
/**
|
||
* 作者 mjsheng
|
||
* 日期 2019/4/1 10:57
|
||
* 邮箱 501802639@qq.com
|
||
* 来自:
|
||
*/
|
||
|
||
import android.app.Service;
|
||
import android.content.BroadcastReceiver;
|
||
import android.content.ComponentName;
|
||
import android.content.Context;
|
||
import android.content.Intent;
|
||
import android.content.IntentFilter;
|
||
import android.content.ServiceConnection;
|
||
import android.os.Binder;
|
||
import android.os.Handler;
|
||
import android.os.IBinder;
|
||
import android.os.PowerManager;
|
||
import android.text.TextUtils;
|
||
import android.util.Log;
|
||
|
||
import androidx.annotation.Nullable;
|
||
|
||
import com.blankj.utilcode.util.NetworkUtils;
|
||
import com.fuying.sn.BuildConfig;
|
||
import com.fuying.sn.KeepAliveConnection;
|
||
import com.fuying.sn.utils.JGYUtils;
|
||
import com.fuying.sn.utils.ServiceAliveUtils;
|
||
import com.fuying.sn.utils.Utils;
|
||
import com.fuying.sn.websocket.JWebSocketClient;
|
||
import com.google.gson.JsonObject;
|
||
|
||
import org.java_websocket.handshake.ServerHandshake;
|
||
|
||
import java.net.URI;
|
||
|
||
/**
|
||
* 主进程 双进程通讯
|
||
*
|
||
* @author LiGuangMin
|
||
* @time Created by 2018/8/17 11:26
|
||
*/
|
||
public class StepService extends Service implements NetworkUtils.OnNetworkStatusChangedListener {
|
||
private final static String TAG = StepService.class.getSimpleName();
|
||
|
||
public JWebSocketClient client;
|
||
private JWebSocketClientBinder mBinder = new JWebSocketClientBinder();
|
||
|
||
@Override
|
||
public void onDisconnected() {
|
||
Log.i("JWebSocketClientService", "网络断开连接");
|
||
}
|
||
|
||
@Override
|
||
public void onConnected(NetworkUtils.NetworkType networkType) {
|
||
Log.i("JWebSocketClientService", "网络已连接");
|
||
// connect();
|
||
}
|
||
|
||
//用于Activity和service通讯
|
||
public class JWebSocketClientBinder extends Binder {
|
||
public StepService getService() {
|
||
return StepService.this;
|
||
}
|
||
}
|
||
|
||
private ServiceConnection mServiceConnection = new ServiceConnection() {
|
||
@Override
|
||
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
|
||
Log.w(TAG, "StepService:建立链接");
|
||
boolean isServiceRunning = ServiceAliveUtils.isServiceAlice(StepService.this, GuardService.class.getName());
|
||
if (!isServiceRunning) {
|
||
Intent i = new Intent(StepService.this, GuardService.class);
|
||
startService(i);
|
||
}
|
||
}
|
||
|
||
@Override
|
||
public void onServiceDisconnected(ComponentName componentName) {
|
||
// 断开链接
|
||
startService(new Intent(StepService.this, GuardService.class));
|
||
// 重新绑定
|
||
bindService(new Intent(StepService.this, GuardService.class), mServiceConnection, Context.BIND_IMPORTANT);
|
||
}
|
||
};
|
||
|
||
@Nullable
|
||
@Override
|
||
public IBinder onBind(Intent intent) {
|
||
return new KeepAliveConnection.Stub() {
|
||
};
|
||
}
|
||
|
||
@Override
|
||
public void onCreate() {
|
||
super.onCreate();
|
||
NetworkUtils.registerNetworkStatusChangedListener(this);
|
||
registerScreenLockReceiver();
|
||
//初始化websocket
|
||
initSocketClient();
|
||
mHandler.postDelayed(heartBeatRunnable, HEART_BEAT_RATE);//开启心跳检测
|
||
}
|
||
|
||
@Override
|
||
public int onStartCommand(Intent intent, int flags, int startId) {
|
||
// 绑定建立链接
|
||
Log.e("JWebSocketClientService", "onStartCommand: ");
|
||
bindService(new Intent(this, GuardService.class), mServiceConnection, Context.BIND_IMPORTANT);
|
||
return START_STICKY;
|
||
}
|
||
|
||
private ScreenLockReceiver screenLockReceiver;
|
||
|
||
private void registerScreenLockReceiver() {
|
||
if (null == screenLockReceiver) {
|
||
screenLockReceiver = new ScreenLockReceiver();
|
||
}
|
||
IntentFilter filter = new IntentFilter();
|
||
filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
|
||
filter.addAction(Intent.ACTION_SCREEN_OFF);
|
||
filter.addAction(Intent.ACTION_SCREEN_ON);
|
||
filter.addAction(Intent.ACTION_BOOT_COMPLETED);
|
||
filter.addAction(Intent.ACTION_USER_PRESENT);
|
||
filter.addAction(Intent.ACTION_SHUTDOWN);
|
||
filter.addAction(Intent.ACTION_FACTORY_RESET);
|
||
filter.addAction(Intent.ACTION_MASTER_CLEAR);
|
||
registerReceiver(screenLockReceiver, filter);
|
||
}
|
||
|
||
private class ScreenLockReceiver extends BroadcastReceiver {
|
||
@Override
|
||
public void onReceive(Context context, Intent intent) {
|
||
String action = intent.getAction();
|
||
Log.e(TAG, "onReceive:" + action);
|
||
if (TextUtils.isEmpty(action)) {
|
||
Log.e(TAG, "onReceive: is NULL");
|
||
return;
|
||
}
|
||
switch (action) {
|
||
case Intent.ACTION_BOOT_COMPLETED:
|
||
case Intent.ACTION_USER_PRESENT:
|
||
case Intent.ACTION_SCREEN_ON:
|
||
mHandler.post(heartBeatRunnable);//开启心跳检测
|
||
sendMsg(1);
|
||
break;
|
||
case Intent.ACTION_SCREEN_OFF:
|
||
case Intent.ACTION_SHUTDOWN:
|
||
case Intent.ACTION_FACTORY_RESET:
|
||
case Intent.ACTION_MASTER_CLEAR:
|
||
sendMsg(0);
|
||
break;
|
||
default:
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
|
||
@Override
|
||
public void onDestroy() {
|
||
super.onDestroy();
|
||
NetworkUtils.unregisterNetworkStatusChangedListener(this);
|
||
closeConnect();
|
||
if (screenLockReceiver != null) {
|
||
unregisterReceiver(screenLockReceiver);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 初始化websocket连接
|
||
*/
|
||
private void initSocketClient() {
|
||
URI uri = URI.create(BuildConfig.WEBSOCKET_URL);
|
||
// URI uri = URI.create("ws://echo.websocket.org");
|
||
// URI uri = URI.create("ws://123.207.136.134:9010/ajaxchattest");
|
||
client = new JWebSocketClient(uri) {
|
||
@Override
|
||
public void onMessage(String message) {
|
||
Log.i("JWebSocketClientService", "收到服务器发来的消息:" + message);
|
||
}
|
||
|
||
@Override
|
||
public void onOpen(ServerHandshake handshakedata) {
|
||
super.onOpen(handshakedata);
|
||
Log.i("JWebSocketClientService", "websocket连接成功");
|
||
sendMsg(1);
|
||
}
|
||
|
||
@Override
|
||
public void onClose(int code, String reason, boolean remote) {
|
||
super.onClose(code, reason, remote);
|
||
Log.i("JWebSocketClientService", "websocket连接关闭:" + reason);
|
||
// client.close();
|
||
// initSocketClient();
|
||
if (JGYUtils.getInstance().isScreenOn()) {
|
||
mHandler.postDelayed(heartBeatRunnable, HEART_BEAT_RATE);//开启心跳检测
|
||
}
|
||
}
|
||
|
||
@Override
|
||
public void onError(Exception ex) {
|
||
super.onError(ex);
|
||
Log.i("JWebSocketClientService", "websocket连接错误:" + ex.getMessage());
|
||
// client.close();
|
||
// initSocketClient();
|
||
if (JGYUtils.getInstance().isScreenOn()) {
|
||
mHandler.postDelayed(heartBeatRunnable, HEART_BEAT_RATE);//开启心跳检测
|
||
} else {
|
||
Log.i("JWebSocketClientService", "postDelayed off");
|
||
}
|
||
}
|
||
};
|
||
connect();
|
||
}
|
||
|
||
/**
|
||
* 连接websocket
|
||
*/
|
||
private void connect() {
|
||
new Thread() {
|
||
@Override
|
||
public void run() {
|
||
try {
|
||
//connectBlocking多出一个等待操作,会先连接再发送,否则未连接发送会报错
|
||
Log.i("JWebSocketClientService", "websocket链接中");
|
||
client.connectBlocking();
|
||
} catch (Exception e) {
|
||
Log.i("JWebSocketClientService", e.getMessage());
|
||
// e.printStackTrace();
|
||
}
|
||
}
|
||
}.start();
|
||
|
||
}
|
||
|
||
/**
|
||
* 发送消息
|
||
*/
|
||
public void sendMsg() {
|
||
JsonObject jsonObject = new JsonObject();
|
||
jsonObject.addProperty("sn", Utils.getSerial());
|
||
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
|
||
if (!pm.isScreenOn()) {
|
||
jsonObject.addProperty("online", 0);
|
||
//熄屏状态
|
||
} else {
|
||
jsonObject.addProperty("online", 1);
|
||
}
|
||
if (null != client) {
|
||
Log.i("JWebSocketClientService", "发送的消息:" + jsonObject.toString());
|
||
client.send(jsonObject.toString());
|
||
}
|
||
}
|
||
|
||
public void sendMsg(int state) {
|
||
JsonObject jsonObject = new JsonObject();
|
||
jsonObject.addProperty("sn", Utils.getSerial());
|
||
jsonObject.addProperty("online", state);
|
||
if (null != client) {
|
||
Log.i("JWebSocketClientService", "发送的消息:" + jsonObject.toString());
|
||
try {
|
||
client.send(jsonObject.toString());
|
||
} catch (Exception e) {
|
||
Log.i(TAG, "sendMsg :" + e.getLocalizedMessage());
|
||
}
|
||
} else {
|
||
Log.i("JWebSocketClientService", "未连接");
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 断开连接
|
||
*/
|
||
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 = 30 * 1000;//每隔50秒进行一次对长连接的心跳检测
|
||
private Handler mHandler = new Handler();
|
||
private Runnable heartBeatRunnable = new Runnable() {
|
||
@Override
|
||
public void run() {
|
||
Log.i("JWebSocketClientService", "心跳包检测websocket连接状态");
|
||
if (client != null) {
|
||
if (client.isOpen()) {
|
||
Log.i("JWebSocketClientService", "websocket已连接");
|
||
sendMsg();
|
||
} else if (client.isClosed()) {
|
||
Log.i("JWebSocketClientService", "websocket重连中");
|
||
if (JGYUtils.getInstance().isScreenOn()) {
|
||
reconnectWs();
|
||
} else {
|
||
Log.i("JWebSocketClientService", "reconnectWs off");
|
||
}
|
||
}
|
||
} else {
|
||
//如果client已为空,重新初始化连接
|
||
client = null;
|
||
initSocketClient();
|
||
}
|
||
//每隔一定的时间,对长连接进行一次心跳检测
|
||
if (JGYUtils.getInstance().isScreenOn()) {
|
||
mHandler.postDelayed(this, HEART_BEAT_RATE);
|
||
} else {
|
||
Log.i("JWebSocketClientService", "websocket息屏不重连");
|
||
}
|
||
}
|
||
};
|
||
|
||
/**
|
||
* 开启重连
|
||
*/
|
||
private void reconnectWs() {
|
||
mHandler.removeCallbacks(heartBeatRunnable);
|
||
new Thread() {
|
||
@Override
|
||
public void run() {
|
||
try {
|
||
Log.i("JWebSocketClientService", "开启重连");
|
||
client.reconnectBlocking();
|
||
} catch (InterruptedException e) {
|
||
e.printStackTrace();
|
||
}
|
||
}
|
||
}.start();
|
||
}
|
||
}
|