소스 검색

1.将Soekct放在AppLication中使用。

master
wangwanlei 9 달 전
부모
커밋
e2be997e36

+ 30
- 0
app/src/main/java/com/xhly/manageapp/ManageApplication.kt 파일 보기

@@ -5,11 +5,14 @@ import android.app.csdk.CSDKManager
5 5
 import androidx.multidex.MultiDexApplication
6 6
 import com.hjq.toast.Toaster
7 7
 import com.xhly.corelib.utils.ModelNameUtils
8
+import com.xhly.manageapp.service.websocket.AppSocket
8 9
 
9 10
 class ManageApplication : MultiDexApplication() {
10 11
     companion object {
11 12
         private var csdkManager: CSDKManager? = null
12 13
 
14
+        private var apppSocket: AppSocket? = null
15
+
13 16
         /**
14 17
          * 加入可安装应用白名单
15 18
          */
@@ -30,6 +33,26 @@ class ManageApplication : MultiDexApplication() {
30 33
             }
31 34
         }
32 35
 
36
+        /**
37
+         * 安装应用
38
+         */
39
+
40
+        fun installPackage(string: String) {
41
+            if (ModelNameUtils.IS_LianxX505f()) {
42
+                csdkManager?.installPackage(string)
43
+            }
44
+        }
45
+
46
+        /**
47
+         * 卸载应用
48
+         */
49
+
50
+        fun uninstallPackage(pkg: String) {
51
+            if (ModelNameUtils.IS_LianxX505f()) {
52
+                csdkManager?.uninstallPackage(pkg, false)
53
+            }
54
+        }
55
+
33 56
         /**
34 57
          * 禁止安装app,true:禁止安装应用 false:取消禁止安装应用,禁止时静默安装只能安装白名单内的应用,不禁止时静默安装可以安装白名单外的应用
35 58
          */
@@ -218,6 +241,8 @@ class ManageApplication : MultiDexApplication() {
218 241
     override fun onCreate() {
219 242
         super.onCreate()
220 243
         Toaster.init(this)
244
+        apppSocket = AppSocket()
245
+        apppSocket?.startSocket(this)
221 246
         if (ModelNameUtils.IS_LianxX505f()) {
222 247
             //是505f则执行
223 248
             csdkManager = CSDKManager(this)
@@ -226,4 +251,9 @@ class ManageApplication : MultiDexApplication() {
226 251
             setRuntimePermissions(true)
227 252
         }
228 253
     }
254
+
255
+    override fun onTerminate() {
256
+        super.onTerminate()
257
+        apppSocket?.onDestroy()
258
+    }
229 259
 }

+ 231
- 0
app/src/main/java/com/xhly/manageapp/service/websocket/AppSocket.kt 파일 보기

@@ -0,0 +1,231 @@
1
+package com.xhly.manageapp.service.websocket
2
+
3
+import android.content.ComponentName
4
+import android.content.Context
5
+import android.content.Intent
6
+import android.widget.Toast
7
+import com.billbook.lib.downloader.Download
8
+import com.billbook.lib.downloader.Downloader
9
+import com.xhly.corelib.Const
10
+import com.xhly.corelib.bean.AppInfo
11
+import com.xhly.corelib.eventbus.UIEvent
12
+import com.xhly.corelib.network.RetrofitService
13
+import com.xhly.corelib.utils.AppUtils
14
+import com.xhly.corelib.utils.GsonUtils
15
+import com.xhly.corelib.utils.LogShow
16
+import com.xhly.corelib.utils.MD5Utils
17
+import com.xhly.corelib.utils.SharedPreferencesUtils
18
+import com.xhly.manageapp.ManageApplication
19
+import com.xhly.manageapp.bean.EventLog
20
+import com.xhly.manageapp.bean.log.LogAppStartBean
21
+import com.xhly.manageapp.bean.log.LogdOperateBean
22
+import com.xhly.manageapp.network.LogService
23
+import com.xhly.websocket.bean.WebSocketData
24
+import com.xhly.websocket.service.SocketClient
25
+import com.xhly.websocket.service.WebSocketHelper
26
+import com.xhly.websocket.utils.SocketPushUtils
27
+import kotlinx.coroutines.CoroutineScope
28
+import kotlinx.coroutines.Dispatchers
29
+import kotlinx.coroutines.MainScope
30
+import kotlinx.coroutines.cancel
31
+import kotlinx.coroutines.launch
32
+import kotlinx.coroutines.withContext
33
+import org.greenrobot.eventbus.EventBus
34
+import org.greenrobot.eventbus.Subscribe
35
+import org.greenrobot.eventbus.ThreadMode
36
+import java.io.File
37
+import java.util.UUID
38
+
39
+class AppSocket : SocketClient() {
40
+    var logService = RetrofitService.create<LogService>()
41
+    private val serviceScope = CoroutineScope(MainScope().coroutineContext)
42
+    private var appList = arrayListOf<AppInfo>()
43
+
44
+
45
+    val spUtils by lazy { SharedPreferencesUtils.getInstance(context) }
46
+
47
+    companion object {
48
+        //标记上次打开的包名,当连续打开同一包名时,不认为打开多次
49
+        var lastPkgName = ""
50
+    }
51
+
52
+    override fun startSocket(context: Context?) {
53
+        EventBus.getDefault().register(this)
54
+        connectUrl = Const.WSURL
55
+        /* startNotification()*/
56
+        LogShow("已经创建")
57
+        appList = AppUtils.GetAppList(context) as ArrayList<AppInfo>
58
+        //downLoadFile("")
59
+        super.startSocket(context)
60
+    }
61
+
62
+    override fun processTextMessage(text: String) {
63
+        //Log.v("websocket收到的消息", text);
64
+        SocketPushUtils.dealPushMessage(text)
65
+    }
66
+
67
+    override fun onConnectedSuccess() {
68
+        super.onConnectedSuccess()
69
+        UIEvent(Const.UPDATE_CONNECTED_SUCCESS).post()
70
+        val webData = WebSocketData()
71
+        webData.code = 1002
72
+        webData.mid = UUID.randomUUID().toString()
73
+        val currentTimeSeconds = System.currentTimeMillis() / 1000
74
+        webData.timeunix = currentTimeSeconds
75
+        webData.fid = 1
76
+        val jsMD5 =
77
+            MD5Utils.getJsMD5(webData.code.toString() + "_" + webData.mid + "_" + webData.timeunix.toString())
78
+        webData.sign = MD5Utils.getJsMD5(jsMD5)
79
+        WebSocketHelper.getInstance().sendSocketString(GsonUtils.parseClassToJson(webData))
80
+    }
81
+
82
+    @Subscribe(threadMode = ThreadMode.MAIN)
83
+    fun onUiEvent(uiEvent: UIEvent) {
84
+        when (uiEvent.event) {
85
+            Const.CODE2001.toString() -> {
86
+                Toast.makeText(context, "这就是新消息", Toast.LENGTH_LONG).show()
87
+            }
88
+
89
+            Const.CODE2002.toString() -> {
90
+                Toast.makeText(context, "限制使用", Toast.LENGTH_LONG).show()
91
+                spUtils.setParam(Const.DISABLEAPP, true)
92
+                goMainActivity()
93
+            }
94
+
95
+            Const.CODE2005.toString() -> {
96
+                ManageApplication.rebootDevice()
97
+            }
98
+
99
+            Const.CODE2006.toString() -> {
100
+                ManageApplication.launchFactoryReset()
101
+            }
102
+
103
+            Const.LOGAPPSTART -> {
104
+                val message = uiEvent.message
105
+                if (lastPkgName == message) {
106
+                    return
107
+                }
108
+                val filter = appList.filter { it.packageName == message }
109
+                if (filter.isNotEmpty()) {
110
+                    val appInfo = filter[0]
111
+                    lastPkgName = message
112
+                    serviceScope.launch {
113
+                        val logStartBean = LogAppStartBean()
114
+                        ManageApplication.getDeviceInfo()?.let {
115
+                            logStartBean.sn = it
116
+                        }
117
+                        logStartBean.appName = appInfo.name
118
+                        logStartBean.appPackage = appInfo.packageName
119
+                        logStartBean.versionName = appInfo.versionName
120
+                        logStartBean.versionNum = appInfo.versionNum
121
+                        LogShow("当前应用" + logStartBean.appName + "|||" + logStartBean.versionName + "|||" + logStartBean.versionNum)
122
+                        logService.postLogAppStartAdd(logStartBean)
123
+                    }
124
+                    val data = LogdOperateBean()
125
+                    ManageApplication.getDeviceInfo()?.let {
126
+                        data.sn = it
127
+                    }
128
+                    data.appPackage = message
129
+                    data.doEvent = EventLog.STARTAPPEVENT
130
+                    eventLog(data)
131
+                }
132
+            }
133
+
134
+            Const.APPINSTALL -> {
135
+                val message = uiEvent.message
136
+                val data = LogdOperateBean()
137
+                ManageApplication.getDeviceInfo()?.let {
138
+                    data.sn = it
139
+                }
140
+                data.appPackage = message
141
+                data.comm = "应用安装"
142
+                data.doEvent = EventLog.APPINSTALLEVENT
143
+                eventLog(data)
144
+            }
145
+
146
+            Const.APPUNINSTALL -> {
147
+                val message = uiEvent.message
148
+                val data = LogdOperateBean()
149
+                ManageApplication.getDeviceInfo()?.let {
150
+                    data.sn = it
151
+                }
152
+                data.appPackage = message
153
+                data.comm = "应用卸载"
154
+                data.doEvent = EventLog.APPUNINSTALLEVENT
155
+                eventLog(data)
156
+            }
157
+
158
+            "10086" -> {
159
+                serviceScope.launch {
160
+                    logService.postLogdoperateAdd(LogdOperateBean())
161
+                }
162
+                Toast.makeText(context, "违规操作,安装未知应用", Toast.LENGTH_LONG).show()
163
+                goMainActivity()
164
+            }
165
+        }
166
+    }
167
+
168
+    private fun goMainActivity() {
169
+        try {
170
+            // 为应用程序的启动Activity 准备Intent
171
+            val launchIntent = Intent()
172
+            launchIntent.setComponent(
173
+                ComponentName(
174
+                    "com.xhly.manageapp",
175
+                    "com.xhly.manageapp.ui.MainActivity"
176
+                )
177
+            )
178
+            launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
179
+            context.startActivity(launchIntent)
180
+        } catch (e: Exception) {
181
+            LogShow("跳转失败$e")
182
+        }
183
+    }
184
+
185
+    //用来发送事件日志
186
+    private fun eventLog(operateBean: LogdOperateBean) {
187
+        serviceScope.launch {
188
+            logService.postLogdoperateAdd(operateBean)
189
+        }
190
+    }
191
+
192
+    override fun onDestroy() {
193
+        super.onDestroy()
194
+        EventBus.getDefault().unregister(this)
195
+        serviceScope.cancel()
196
+        /* stopForeground(Service.STOP_FOREGROUND_REMOVE)*/
197
+        val intent = Intent()
198
+        intent.setPackage("com.xhly.manageapp")
199
+        intent.setAction("test")
200
+        context.sendBroadcast(intent)
201
+        LogShow("Service被销毁")
202
+    }
203
+
204
+
205
+
206
+    private fun downLoadFile(url: String) {
207
+        serviceScope.launch {
208
+            withContext(Dispatchers.IO) {
209
+                //val file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
210
+                val file = context.getExternalFilesDir(null)
211
+                val name = file.toString()
212
+                val downloader = Downloader.Builder().build()
213
+                val request = Download.Request.Builder()
214
+                    .url("https://dl.hdslb.com/mobile/latest/android64/iBiliPlayer-bili.apk?t=20230728&spm_id_from=333.47.b_646f776e6c6f61642d6c696e6b.1")
215
+                    .into(File(name, "test.apk"))
216
+                    .build()
217
+                LogShow("开始下载")
218
+                val execute = downloader.newCall(request).execute()
219
+                val successful = execute.isSuccessful()
220
+                LogShow("下载结果" + successful)
221
+                if (successful) {
222
+                    withContext(Dispatchers.Main){
223
+                        ManageApplication.installPackage(File(name, "test.apk").toString())
224
+                    }
225
+                }
226
+                LogShow("下载后,开始安装")
227
+            }
228
+        }
229
+    }
230
+
231
+}

+ 16
- 3
app/src/main/java/com/xhly/manageapp/ui/MainActivity.kt 파일 보기

@@ -27,7 +27,10 @@ import com.xhly.corelib.network.RetrofitService
27 27
 import com.xhly.corelib.utils.AppUtils
28 28
 import com.xhly.corelib.utils.LogShow
29 29
 import com.xhly.manageapp.AppAdapter
30
+import com.xhly.manageapp.ManageApplication
30 31
 import com.xhly.manageapp.R
32
+import com.xhly.manageapp.bean.EventLog
33
+import com.xhly.manageapp.bean.log.LogdOperateBean
31 34
 import com.xhly.manageapp.broadcastreceiver.AppInstallReceiver
32 35
 import com.xhly.manageapp.databinding.ActivityMainBinding
33 36
 import com.xhly.manageapp.network.LogService
@@ -94,9 +97,9 @@ class MainActivity : BaseActivity<CommonBaseViewModel, ActivityMainBinding>() {
94 97
         AppSocketService.lastPkgName=""
95 98
         getAppInfo()
96 99
         useStrategy()
97
-        if (!isServiceON(this,AppSocketService::class.java.name)){
100
+    /*    if (!isServiceON(this,AppSocketService::class.java.name)){
98 101
             AppSocketService.openWebSocket(this)
99
-        }
102
+        }*/
100 103
         /*      lifecycleScope.launch(Dispatchers.IO) {
101 104
                   delay(20000)
102 105
                   withContext(Dispatchers.Main) {
@@ -155,6 +158,16 @@ class MainActivity : BaseActivity<CommonBaseViewModel, ActivityMainBinding>() {
155 158
                     LogShow("app包名" + it.packageName)
156 159
                 }
157 160
             }
161
+            Const.APPINSTALL -> {
162
+               try {
163
+                   dataList.clear()
164
+                   val getAppList1 = AppUtils.GetAppList(this)
165
+                   dataList.addAll(getAppList1)
166
+                   adapter.notifyDataSetChanged()
167
+               }catch (e:Exception){
168
+
169
+               }
170
+            }
158 171
 
159 172
             "策略更新" -> {
160 173
 
@@ -333,6 +346,6 @@ class MainActivity : BaseActivity<CommonBaseViewModel, ActivityMainBinding>() {
333 346
         mMyInstallReceiver?.let {
334 347
             unregisterReceiver(it)
335 348
         }
336
-
349
+        LogShow("MainActivity被销毁")
337 350
     }
338 351
 }

+ 370
- 0
websocket/src/main/java/com/xhly/websocket/service/SocketClient.java 파일 보기

@@ -0,0 +1,370 @@
1
+package com.xhly.websocket.service;
2
+
3
+import android.content.Context;
4
+import android.os.Handler;
5
+import android.text.TextUtils;
6
+import android.util.Log;
7
+import android.widget.Toast;
8
+
9
+import com.neovisionaries.ws.client.WebSocket;
10
+import com.neovisionaries.ws.client.WebSocketAdapter;
11
+import com.neovisionaries.ws.client.WebSocketException;
12
+import com.neovisionaries.ws.client.WebSocketFactory;
13
+import com.neovisionaries.ws.client.WebSocketFrame;
14
+import com.xhly.corelib.utils.NetworkUtils;
15
+
16
+import java.io.IOException;
17
+import java.util.List;
18
+import java.util.Map;
19
+import java.util.concurrent.TimeUnit;
20
+
21
+import io.reactivex.Observable;
22
+import io.reactivex.Observer;
23
+import io.reactivex.android.schedulers.AndroidSchedulers;
24
+import io.reactivex.disposables.Disposable;
25
+import io.reactivex.schedulers.Schedulers;
26
+
27
+public abstract class SocketClient {
28
+    /**
29
+     * 聊天
30
+     */
31
+    protected static final int SOCKET_TYPE = 1;
32
+    /**
33
+     * WebSocket config
34
+     */
35
+    private static final int FRAME_QUEUE_SIZE = 5;
36
+    /**
37
+     * 心跳时间间隔单位是s
38
+     */
39
+    private static final long HEART_INTERVAL = 10;
40
+    /**
41
+     * 未收到心跳响应的次数
42
+     */
43
+    public static int HEART_NOT_RECEIVE_TIME = 0;
44
+    /**
45
+     * 是否收到心跳响应
46
+     */
47
+    public static boolean HAS_HEART_RECEIVE = false;
48
+    /**
49
+     * 连接超时时间,单位毫秒
50
+     */
51
+    public static int CONNECT_TIMEOUT = 20000;
52
+    public static boolean closeWebsocket = false;
53
+    public String TAG = LongConnService.class.getSimpleName();
54
+    protected int type = 1;
55
+    protected String connectUrl;
56
+    /**
57
+     * 重连最小时间间隔,单位毫秒
58
+     */
59
+    private long minInterval = 10000;
60
+    /**
61
+     * 重连最大时间间隔,单位毫秒
62
+     */
63
+    private long maxInterval = 60000;
64
+    private Handler mHandler = new Handler();
65
+    /**
66
+     * 重连次数
67
+     */
68
+    private int reconnectCount = 0;
69
+    /**
70
+     * 心跳subscription
71
+     */
72
+    private Disposable heartSubscription;
73
+    /**
74
+     * 是否连接状态
75
+     */
76
+    private boolean connected = false;
77
+    /**
78
+     * 是否允许重连
79
+     */
80
+    private boolean isReConnect = true;
81
+    private WsStatus mStatus;
82
+    private WebSocket webSocket;
83
+    private WsListener mListener;
84
+    //是否使用单项心跳
85
+    private boolean singleheartbeat = true;
86
+
87
+    protected Context context;
88
+    /**
89
+     * 设置已收到心跳
90
+     */
91
+    public static void hasReceiveHeart() {
92
+        HEART_NOT_RECEIVE_TIME = 0;
93
+        HAS_HEART_RECEIVE = true;
94
+    }
95
+
96
+
97
+    public void startSocket(Context context) {
98
+        this.context=context;
99
+        Log.i(TAG, "startSocket............");
100
+        closeWebsocket = false;
101
+        if (mListener == null) {
102
+            mListener = new WsListener();
103
+        }
104
+        startConnect();
105
+    }
106
+
107
+
108
+    public void onDestroy() {
109
+        Log.i(TAG, "onDestroy()............");
110
+        if (heartSubscription != null) {
111
+            heartSubscription.dispose();
112
+        }
113
+        disConnect();
114
+        closeWebsocket = true;
115
+    }
116
+
117
+
118
+    /**
119
+     * 断开连接
120
+     */
121
+    private void disConnect() {
122
+        if (mHandler != null) {
123
+            mHandler.removeCallbacksAndMessages(null);
124
+        }
125
+        isReConnect = false;
126
+        connected = false;
127
+        if (webSocket != null) {
128
+            setStatus(WsStatus.DISCONNECT);
129
+            cancelReconnect();
130
+            webSocket.disconnect();
131
+            webSocket.clearListeners();  // 清除回调,避免多次链接导致上个链接的消息接收问题
132
+            webSocket = null;
133
+        }
134
+    }
135
+
136
+    /**
137
+     * 取消重连
138
+     */
139
+    private void cancelReconnect() {
140
+        reconnectCount = 0;
141
+    }
142
+
143
+
144
+    /**
145
+     * 链接成功,子类可以拓展
146
+     */
147
+    public void onConnectedSuccess() {
148
+
149
+    }
150
+
151
+    /**
152
+     * 连接长链接
153
+     */
154
+    private synchronized void startConnect() {
155
+        if (TextUtils.isEmpty("用户ID")) {
156
+            setStatus(WsStatus.DISCONNECT);
157
+            return;
158
+        }
159
+        if (!NetworkUtils.isAvailable(context)) {
160
+            Toast.makeText(context, "网络不可用", Toast.LENGTH_SHORT);
161
+            return;
162
+        }
163
+
164
+        isReConnect = true;
165
+      /*
166
+      //存在!=null 并且open时断联的情况,所以注释
167
+      if (webSocket != null && webSocket.isOpen()) {
168
+            setStatus(WsStatus.CONNECT_SUCCESS);
169
+            return;
170
+        }*/
171
+        if (getStatus() == WsStatus.CONNECTING) {
172
+            return;
173
+        }
174
+
175
+        if (!connected) {
176
+            if (webSocket != null) {
177
+                webSocket.disconnect();
178
+                webSocket = null;
179
+            }
180
+            try {
181
+                Log.i(TAG, "第一次连接: " + connectUrl);
182
+                // 异步连接
183
+                webSocket = createWebSocket();
184
+                setStatus(WsStatus.CONNECTING);
185
+//                checkConnectState();
186
+            } catch (IOException e) {
187
+                e.printStackTrace();
188
+            }
189
+        }
190
+    }
191
+
192
+    public WsStatus getStatus() {
193
+        return mStatus;
194
+    }
195
+
196
+    private void setStatus(WsStatus status) {
197
+        this.mStatus = status;
198
+    }
199
+
200
+    private WebSocket createWebSocket() throws IOException {
201
+        Log.i(TAG, "创建连接:createWebSocket()");
202
+        return new WebSocketFactory().createSocket(connectUrl, CONNECT_TIMEOUT)
203
+                //设置帧队列最大值为5
204
+                .setFrameQueueSize(FRAME_QUEUE_SIZE)
205
+                //设置不允许服务端关闭连接却未发送关闭帧
206
+                .setMissingCloseFrameAllowed(false)
207
+                //添加回调监听
208
+                .addListener(mListener).connectAsynchronously();
209
+    }
210
+
211
+    /**
212
+     * 重新连接
213
+     */
214
+    private void reConnect() {
215
+        if (!NetworkUtils.isAvailable(context)) {
216
+            reconnectCount = 0;
217
+            isReConnect = false;
218
+            closeWebsocket = true;
219
+            Log.i(TAG, "重连失败网络不可用,当前closeWebsocket==" + closeWebsocket);
220
+            return;
221
+        }
222
+        if (HAS_HEART_RECEIVE) {
223
+            return;
224
+        }
225
+        if (webSocket != null && !webSocket.isOpen() &&//当前连接断开了
226
+                getStatus() != WsStatus.CONNECTING && !connected) { //不是正在重连状态
227
+            setStatus(WsStatus.CONNECTING);
228
+            long reconnectTime = minInterval;
229
+            if (reconnectCount > 3) {
230
+                long temp = minInterval * (reconnectCount - 2);
231
+                reconnectTime = temp > maxInterval ? maxInterval : temp;
232
+            }
233
+            mHandler.postDelayed(new Runnable() {
234
+                @Override
235
+                public void run() {
236
+                    try {
237
+                        if (webSocket.isOpen() && isConnect()) {
238
+                            return;
239
+                        }
240
+                        if (webSocket != null) {
241
+                            webSocket.disconnect();
242
+                            webSocket = null;
243
+                        }
244
+                        webSocket = createWebSocket();
245
+                        reconnectCount++;
246
+                    } catch (IOException e) {
247
+                        e.printStackTrace();
248
+                    }
249
+                }
250
+            }, reconnectTime);
251
+        }
252
+    }
253
+
254
+    /**
255
+     * 是否连接
256
+     */
257
+    private boolean isConnect() {
258
+        return connected;
259
+    }
260
+
261
+    /**
262
+     * 开始socket心跳
263
+     */
264
+    private void startHeartInterval(final WebSocket websocket) {
265
+        if (singleheartbeat) {
266
+            //单向心跳
267
+            WebSocketHelper.getInstance().hearBeat(websocket);
268
+        } else {
269
+            //双向心跳
270
+            if (HEART_NOT_RECEIVE_TIME > 3) {
271
+                // 有3次心跳没有收到服务器响应,则认为是已经断开连接,则重新连接
272
+                connected = false;
273
+                startConnect();
274
+                return;
275
+            }
276
+            // 在客户端上增加重试的逻辑。先发送心跳包,在N秒内若没有收到回复,则再发送一次。重试M次。
277
+            WebSocketHelper.getInstance().hearBeat(websocket);
278
+            HEART_NOT_RECEIVE_TIME++;
279
+            HAS_HEART_RECEIVE = false;
280
+        }
281
+    }
282
+
283
+    /**
284
+     * 处理socket响应消息
285
+     *
286
+     * @param text 要处理的文本
287
+     */
288
+    public abstract void processTextMessage(String text);
289
+
290
+    /**
291
+     * 继承默认的监听空实现WebSocketAdapter,重写我们需要的方法
292
+     * onTextMessage 收到文字信息
293
+     * onConnected 连接成功
294
+     * onConnectError 连接失败
295
+     * onDisconnected 连接关闭
296
+     */
297
+    private class WsListener extends WebSocketAdapter {
298
+        @Override
299
+        public void onConnected(final WebSocket websocket, Map<String, List<String>> headers) throws Exception {
300
+            super.onConnected(websocket, headers);
301
+            Log.i(TAG, "连接成功:" + headers.toString());
302
+            connected = true;
303
+            setStatus(WsStatus.CONNECT_SUCCESS);
304
+            cancelReconnect();// 连接成功的时候取消重连,初始化连接次数
305
+            if (type == SOCKET_TYPE) {
306
+                WebSocketHelper.getInstance().build(websocket);
307
+                //调用成功方法
308
+                onConnectedSuccess();
309
+                Observable.interval(HEART_INTERVAL, TimeUnit.SECONDS).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Long>() {
310
+                    @Override
311
+                    public void onSubscribe(Disposable d) {
312
+                        Log.d(TAG, "订阅开始");
313
+                        heartSubscription = d;
314
+                    }
315
+
316
+                    @Override
317
+                    public void onNext(Long aLong) {
318
+                        Log.v(TAG, "发送心跳");
319
+                        startHeartInterval(websocket);
320
+                    }
321
+
322
+                    @Override
323
+                    public void onError(Throwable e) {
324
+
325
+                    }
326
+
327
+                    @Override
328
+                    public void onComplete() {
329
+
330
+                    }
331
+                });
332
+            }
333
+        }
334
+
335
+        @Override
336
+        public void onConnectError(WebSocket websocket, WebSocketException exception) throws Exception {
337
+            super.onConnectError(websocket, exception);
338
+            exception.printStackTrace();
339
+            Log.i(TAG, "连接错误: " + exception.getMessage());
340
+            HAS_HEART_RECEIVE = false;
341
+            setStatus(WsStatus.CONNECT_FAIL);
342
+            connected = false;
343
+            if (isReConnect) {
344
+                reConnect();//连接断开的时候调用重连方法
345
+            }
346
+        }
347
+
348
+        @Override
349
+        public void onDisconnected(WebSocket websocket, WebSocketFrame serverCloseFrame, WebSocketFrame clientCloseFrame, boolean closedByServer) throws Exception {
350
+            super.onDisconnected(websocket, serverCloseFrame, clientCloseFrame, closedByServer);
351
+            Log.i(TAG, "断开连接,是否重连" + isReConnect + ",当前closeWebsocket==" + closeWebsocket);
352
+            HAS_HEART_RECEIVE = false;
353
+            connected = false;
354
+            if (heartSubscription != null) {
355
+                heartSubscription.dispose();
356
+            }
357
+            setStatus(WsStatus.CONNECT_FAIL);
358
+            if (isReConnect) {
359
+                reConnect();//连接断开的时候调用重连方法
360
+            }
361
+        }
362
+
363
+        @Override
364
+        public void onTextMessage(WebSocket websocket, String text) throws Exception {
365
+            super.onTextMessage(websocket, text);
366
+            hasReceiveHeart();
367
+            processTextMessage(text);
368
+        }
369
+    }
370
+}

Loading…
취소
저장