所以当我尝试使用我的两个平板电脑和外部支持Wifi的设备通过TCP进行通信时,我遇到了一个奇怪的问题。
我会尽力描述这个问题。系统的工作原理如下(所有通信都通过无线网络进行):
activity
并返回上一个,则消息 消耗运行Android 6.0.1的联想YT3平板电脑会发生这种情况
SocketListenerService
private var thread: Thread? = null
private var socketListener: SocketListener? = null
private var broadcastManager: LocalBroadcastManager? = null
val listener = object : SimpleServer.ServerReceivedListener {
override fun onLineReceived(line: String) {
val response = Intent(SOCKET_RESPONSE)
response.putExtra(RESPONSE_MESSAGE, line)
broadcastManager!!.sendBroadcast(response)
}
}
private val incomingServer = SimpleServer(listener)
override fun onCreate() {
super.onCreate()
broadcastManager = LocalBroadcastManager.getInstance(this)
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (intent != null) {
socketListener = SocketListener()
thread = Thread(socketListener)
thread!!.start()
}
return super.onStartCommand(intent, flags, startId)
}
override fun onDestroy() {
super.onDestroy()
socketListener!!.shutDown()
thread!!.interrupt()
incomingServer.closeServer()
}
override fun onBind(intent: Intent): IBinder? {
return null
}
private inner class SocketListener : Runnable {
@Volatile private var done = false
internal fun shutDown() {
done = true
}
override fun run() {
while (!done) {
incomingServer.serve()
}
}
}
companion object {
val SOCKET_RESPONSE = "socket_response"
val RESPONSE_MESSAGE = "response_message"
val port = 9888
}
SimpleServer
interface ServerReceivedListener {
fun onLineReceived(line: String)
}
private var server: ServerSocket? = null
private var client: Socket? = null
private var listener: ServerReceivedListener? = null
init {
try {
server = ServerSocket(SocketListenerService.port)
this.listener = listener
} catch (err: Exception) {
err.printStackTrace()
}
}
fun serve() {
var line: String?
try {
if (!server!!.isClosed) {
client = server?.accept()
val r = BufferedReader(InputStreamReader(client!!.getInputStream(), "UTF-8"))
line = r.readLine()
while (line != null) {
if (line.length >= 4)
listener!!.onLineReceived(line)
else
listener!!.onLineReceived("@")
line = r.readLine()
}
}
} catch (e: IOException) {
if (!e.message!!.contains("Socket closed"))
e.printStackTrace()
}
}
fun closeServer() {
try {
if (client != null)
client!!.close()
server!!.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
BroadcastBeceiver
反过来从意图中获取消息并使用界面将其发送到activity
我似乎无法理解为什么来自 slave 的通信仅在重新启动消耗activity
时被主消耗掉( ?)
答案 0 :(得分:0)
这是一个套接字问题。现在我有两个线程监听两个端口,通信工作正常