cloudroam
2025-04-15 3466799c94227c5ebba9fb201621e745058867ee
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package com.example.firstapp.service
 
import android.app.Service
import android.content.Intent
import android.os.IBinder
import com.example.firstapp.utils.Log
import com.example.firstapp.utils.HTTP_SERVER_PORT
import com.example.firstapp.utils.HTTP_SERVER_TIME_OUT
import com.example.firstapp.utils.SettingUtils
import com.yanzhenjie.andserver.AndServer
import com.yanzhenjie.andserver.Server
import java.util.concurrent.TimeUnit
 
@Suppress("PrivatePropertyName")
class HttpServerService : Service(), Server.ServerListener {
 
    private val TAG: String = HttpServerService::class.java.simpleName
    private val server by lazy {
        AndServer.webServer(this).port(HTTP_SERVER_PORT).listener(this).timeout(HTTP_SERVER_TIME_OUT, TimeUnit.SECONDS).build()
    }
 
    override fun onBind(p0: Intent?): IBinder? {
        return null
    }
 
    override fun onCreate() {
        super.onCreate()
 
        //纯客户端模式
        if (SettingUtils.enablePureClientMode) return
 
        Log.i(TAG, "onCreate: ")
        server.startup()
    }
 
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.i(TAG, "onStartCommand: ")
        return super.onStartCommand(intent, flags, startId)
    }
 
    override fun onDestroy() {
        super.onDestroy()
 
        //纯客户端模式
        if (SettingUtils.enablePureClientMode) return
 
        Log.i(TAG, "onDestroy: ")
        server.shutdown()
    }
 
    override fun onException(e: Exception?) {
        Log.i(TAG, "onException: ")
    }
 
    override fun onStarted() {
        Log.i(TAG, "onStarted: ")
    }
 
    override fun onStopped() {
        Log.i(TAG, "onStopped: ")
    }
}