Browse Source

1.创建通信模块websocket

master
wangwanlei 9 months ago
parent
commit
43185b6796

+ 1
- 0
websocket/.gitignore View File

@@ -0,0 +1 @@
1
+/build

+ 46
- 0
websocket/build.gradle.kts View File

@@ -0,0 +1,46 @@
1
+@Suppress("DSL_SCOPE_VIOLATION") // TODO: Remove once KTIJ-19369 is fixed
2
+plugins {
3
+    alias(libs.plugins.androidLibrary)
4
+    alias(libs.plugins.kotlinAndroid)
5
+}
6
+
7
+android {
8
+    namespace = "com.xhly.websocket"
9
+    compileSdk = 33
10
+
11
+    defaultConfig {
12
+        minSdk = 24
13
+
14
+        testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
15
+        consumerProguardFiles("consumer-rules.pro")
16
+    }
17
+
18
+    buildTypes {
19
+        release {
20
+            isMinifyEnabled = false
21
+            proguardFiles(
22
+                getDefaultProguardFile("proguard-android-optimize.txt"),
23
+                "proguard-rules.pro"
24
+            )
25
+        }
26
+    }
27
+    compileOptions {
28
+        sourceCompatibility = JavaVersion.VERSION_1_8
29
+        targetCompatibility = JavaVersion.VERSION_1_8
30
+    }
31
+    kotlinOptions {
32
+        jvmTarget = "1.8"
33
+    }
34
+}
35
+
36
+dependencies {
37
+
38
+    implementation(libs.core.ktx)
39
+    implementation(libs.appcompat)
40
+    implementation(libs.material)
41
+    api(project(mapOf("path" to ":corelib")))
42
+    testImplementation(libs.junit)
43
+    androidTestImplementation(libs.androidx.test.ext.junit)
44
+    androidTestImplementation(libs.espresso.core)
45
+    api("com.neovisionaries:nv-websocket-client:2.2")
46
+}

+ 24
- 0
websocket/src/androidTest/java/com/xhly/websocket/ExampleInstrumentedTest.kt View File

@@ -0,0 +1,24 @@
1
+package com.xhly.websocket
2
+
3
+import androidx.test.platform.app.InstrumentationRegistry
4
+import androidx.test.ext.junit.runners.AndroidJUnit4
5
+
6
+import org.junit.Test
7
+import org.junit.runner.RunWith
8
+
9
+import org.junit.Assert.*
10
+
11
+/**
12
+ * Instrumented test, which will execute on an Android device.
13
+ *
14
+ * See [testing documentation](http://d.android.com/tools/testing).
15
+ */
16
+@RunWith(AndroidJUnit4::class)
17
+class ExampleInstrumentedTest {
18
+    @Test
19
+    fun useAppContext() {
20
+        // Context of the app under test.
21
+        val appContext = InstrumentationRegistry.getInstrumentation().targetContext
22
+        assertEquals("com.xhly.websocket.test", appContext.packageName)
23
+    }
24
+}

+ 15
- 0
websocket/src/main/AndroidManifest.xml View File

@@ -0,0 +1,15 @@
1
+<?xml version="1.0" encoding="utf-8"?>
2
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
3
+    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
4
+    <uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
5
+
6
+
7
+    <application>
8
+        <service android:name="com.xhly.websocket.service.SocketService"
9
+            android:foregroundServiceType="dataSync"
10
+            />
11
+        <service android:name="com.xhly.websocket.service.ManageService"
12
+            android:foregroundServiceType="dataSync"
13
+            />
14
+    </application>
15
+</manifest>

+ 13
- 0
websocket/src/main/java/com/xhly/websocket/bean/HertBean.java View File

@@ -0,0 +1,13 @@
1
+package com.xhly.websocket.bean;
2
+
3
+public class HertBean {
4
+    String type;
5
+
6
+    public String getType() {
7
+        return type;
8
+    }
9
+
10
+    public void setType(String type) {
11
+        this.type = type;
12
+    }
13
+}

+ 6
- 0
websocket/src/main/java/com/xhly/websocket/bean/SocketMsgData.kt View File

@@ -0,0 +1,6 @@
1
+package com.xhly.websocket.bean
2
+
3
+class SocketMsgData() {
4
+    var code = 0
5
+    var body: String? = null
6
+}

+ 14
- 0
websocket/src/main/java/com/xhly/websocket/bean/WebSocketData.kt View File

@@ -0,0 +1,14 @@
1
+package com.xhly.websocket.bean
2
+
3
+class WebSocketData() {
4
+    //发送信息时使用
5
+    var code = 0
6
+    var mid: String? = null
7
+    var timeunix: Long = 0
8
+
9
+    //两次md5加密timeunix
10
+    var sign: String? = null
11
+    var fid: String? = null
12
+    var tids: String? = null
13
+    var body: String? = null
14
+}

+ 27
- 0
websocket/src/main/java/com/xhly/websocket/service/ManageService.kt View File

@@ -0,0 +1,27 @@
1
+package com.xhly.websocket.service
2
+
3
+import android.app.Service
4
+import android.content.Intent
5
+import android.os.IBinder
6
+import com.xhly.corelib.utils.LogShow
7
+import com.xhly.websocket.utils.WebSocketUtils
8
+
9
+class ManageService: Service() {
10
+    override fun onBind(intent: Intent?): IBinder? {
11
+       return null
12
+    }
13
+
14
+    override fun onCreate() {
15
+        super.onCreate()
16
+        LogShow("创建service")
17
+    }
18
+    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
19
+        WebSocketUtils.openWebSocket(this)
20
+        LogShow("执行service")
21
+        return super.onStartCommand(intent, flags, startId)
22
+    }
23
+
24
+    override fun onDestroy() {
25
+        super.onDestroy()
26
+    }
27
+}

+ 112
- 0
websocket/src/main/java/com/xhly/websocket/service/SocketService.kt View File

@@ -0,0 +1,112 @@
1
+package com.xhly.websocket.service
2
+
3
+import android.app.Notification
4
+import android.app.NotificationChannel
5
+import android.app.NotificationManager
6
+import android.app.Service
7
+import android.content.ComponentName
8
+import android.content.Intent
9
+import android.os.Build
10
+import android.widget.Toast
11
+import com.xhly.corelib.Const
12
+import com.xhly.corelib.eventbus.UIEvent
13
+import com.xhly.corelib.utils.LogShow
14
+import com.xhly.corelib.utils.SharedPreferencesUtils
15
+import com.xhly.websocket.utils.SocketPushUtils.dealPushMessage
16
+import org.greenrobot.eventbus.EventBus
17
+import org.greenrobot.eventbus.Subscribe
18
+import org.greenrobot.eventbus.ThreadMode
19
+
20
+open class SocketService : LongConnService() {
21
+    var CHANNEL_ID = "1"
22
+    var CHANNEL_NAME = "通知"
23
+  /*  private var csdkManager: CSDKManager? = null*/
24
+    val spUtils by lazy { SharedPreferencesUtils.getInstance(this) }
25
+    override fun onCreate() {
26
+        super.onCreate()
27
+        EventBus.getDefault().register(this)
28
+        connectUrl = "wss://api.stsotc.com/api/ws"
29
+     /*   csdkManager = CSDKManager(this)*/
30
+        /* startNotification()*/
31
+    }
32
+
33
+    override fun processTextMessage(text: String) {
34
+        //Log.v("websocket收到的消息", text);
35
+        dealPushMessage(text)
36
+    }
37
+
38
+    override fun onConnectedSuccess() {
39
+        super.onConnectedSuccess()
40
+        UIEvent(Const.UPDATE_CONNECTED_SUCCESS).post()
41
+    }
42
+
43
+    @Subscribe(threadMode = ThreadMode.MAIN)
44
+    fun onUiEvent(uiEvent: UIEvent) {
45
+       /* if (csdkManager == null) {
46
+            csdkManager = CSDKManager(this)
47
+        }*/
48
+        when (uiEvent.event) {
49
+            Const.CODE2001.toString() -> {
50
+                Toast.makeText(this, "这就是新消息", Toast.LENGTH_LONG).show()
51
+            }
52
+
53
+            Const.CODE2002.toString() -> {
54
+                Toast.makeText(this, "限制使用", Toast.LENGTH_LONG).show()
55
+                spUtils.setParam(Const.DISABLEAPP, true)
56
+                goMainActivity()
57
+            }
58
+
59
+            Const.CODE2005.toString() -> {
60
+                //csdkManager?.rebootDevice()
61
+            }
62
+
63
+            Const.CODE2006.toString() -> {
64
+                //csdkManager?.launchFactoryReset()
65
+            }
66
+
67
+            "10086" -> {
68
+                Toast.makeText(this, "违规操作,安装未知应用", Toast.LENGTH_LONG).show()
69
+                goMainActivity()
70
+            }
71
+        }
72
+    }
73
+
74
+    private fun goMainActivity() {
75
+        try {
76
+            // 为应用程序的启动Activity 准备Intent
77
+            val launchIntent = Intent()
78
+            launchIntent.setComponent(
79
+                ComponentName(
80
+                    "com.xhly.manageapp",
81
+                    "com.xhly.manageapp.ui.MainActivity"
82
+                )
83
+            )
84
+            launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
85
+            startActivity(launchIntent)
86
+        } catch (e: Exception) {
87
+            LogShow("跳转失败$e")
88
+        }
89
+    }
90
+
91
+    override fun onDestroy() {
92
+        super.onDestroy()
93
+        EventBus.getDefault().unregister(this)
94
+        stopForeground(Service.STOP_FOREGROUND_REMOVE)
95
+        /*  val intent=Intent(this,ManageService::class.java)
96
+          startService(intent)*/
97
+    }
98
+
99
+    private fun startNotification() {
100
+        var channel: NotificationChannel? = null
101
+        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
102
+            channel =
103
+                NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH)
104
+            val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
105
+            manager.createNotificationChannel(channel)
106
+            val notification = Notification.Builder(
107
+                applicationContext, CHANNEL_ID
108
+            ).build()
109
+            startForeground(1, notification)
110
+        }
111
+    }
112
+}

+ 12
- 0
websocket/src/main/java/com/xhly/websocket/service/WsStatus.java View File

@@ -0,0 +1,12 @@
1
+package com.xhly.websocket.service;
2
+
3
+public enum WsStatus {
4
+    //连接成功
5
+    CONNECT_SUCCESS,
6
+    //连接失败
7
+    CONNECT_FAIL,
8
+    // 断开连接
9
+    DISCONNECT,
10
+    //正在连接
11
+    CONNECTING
12
+}

+ 67
- 0
websocket/src/main/java/com/xhly/websocket/utils/SocketPushUtils.kt View File

@@ -0,0 +1,67 @@
1
+package com.xhly.websocket.utils
2
+
3
+import com.xhly.corelib.eventbus.UIEvent
4
+import com.xhly.corelib.utils.GsonUtils
5
+import com.xhly.corelib.utils.LogShow
6
+import com.xhly.websocket.bean.WebSocketData
7
+
8
+object SocketPushUtils {
9
+    fun dealPushMessage(content: String) {
10
+        try {
11
+            //没用泛型是因为如果带有泛型的类型,可能会遇到解析异常的问题。需要使用TypeToken
12
+            var socketData = GsonUtils.parseJsonWithGson(content, WebSocketData::class.java)
13
+            socketData.code.let { code ->
14
+                when (code) {
15
+                    1001 -> {
16
+                        //连接后回发 body{userid,username,usertype(1管理员,2学生)}
17
+                    }
18
+
19
+                    1002 -> {
20
+                        //获取在线用户列表
21
+                    }
22
+
23
+                    1003 -> {
24
+                        //返回在线用户列表 body{userlist(userid,username)}
25
+                    }
26
+
27
+                    2001 -> {
28
+                        //发送消息 body{userid,username,msg}
29
+                        UIEvent("2001").post()
30
+                    }
31
+
32
+                    2002 -> {
33
+                        //限制使用
34
+                    }
35
+
36
+                    2003 -> {
37
+                        //解除限制
38
+
39
+                    }
40
+
41
+                    2004 -> {
42
+                        //更新策略
43
+                    }
44
+
45
+                    2005 -> {
46
+                        //重启设备
47
+                    }
48
+
49
+                    2006 -> {
50
+                        //恢复出厂
51
+                    }
52
+                    666->{
53
+                        //消息确认回发mid 消息id
54
+                    }
55
+                    999->{
56
+                        //错误消息 body msg(错误消息)
57
+                    }
58
+                    else -> {
59
+                        //Log.d("message解析", socketData .message!!)
60
+                    }
61
+                }
62
+            }
63
+        } catch (e: Exception) {
64
+            LogShow("解析问题$e")
65
+        }
66
+    }
67
+}

+ 26
- 0
websocket/src/main/java/com/xhly/websocket/utils/WebSocketUtils.java View File

@@ -0,0 +1,26 @@
1
+package com.xhly.websocket.utils;
2
+
3
+import android.content.Context;
4
+import android.content.Intent;
5
+
6
+import com.neovisionaries.ws.client.WebSocket;
7
+import com.xhly.websocket.service.SocketService;
8
+import com.xhly.websocket.service.WebSocketHelper;
9
+
10
+
11
+public class WebSocketUtils {
12
+    //启动服务
13
+    public static void openWebSocket(Context context) {
14
+        context.startService(new Intent(context, SocketService.class));
15
+    }
16
+
17
+    public static void closeWebSocket(Context context) {
18
+        context.stopService(new Intent(context, SocketService.class));
19
+    }
20
+
21
+    //心跳消息
22
+    public static void hearBeat(WebSocket webSocket) {
23
+        WebSocketHelper.getInstance().hearBeat(webSocket);
24
+    }
25
+
26
+}

+ 17
- 0
websocket/src/test/java/com/xhly/websocket/ExampleUnitTest.kt View File

@@ -0,0 +1,17 @@
1
+package com.xhly.websocket
2
+
3
+import org.junit.Test
4
+
5
+import org.junit.Assert.*
6
+
7
+/**
8
+ * Example local unit test, which will execute on the development machine (host).
9
+ *
10
+ * See [testing documentation](http://d.android.com/tools/testing).
11
+ */
12
+class ExampleUnitTest {
13
+    @Test
14
+    fun addition_isCorrect() {
15
+        assertEquals(4, 2 + 2)
16
+    }
17
+}

Loading…
Cancel
Save