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 63 64 65 66
| class MainActivity : AppCompatActivity() { private val coroutineScope = CoroutineScope(Dispatchers.Default)
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main)
val hubConnection = HubConnectionBuilder.create("http://192.168.1.10:8020/chathub") .withTransport(TransportEnum.LONG_POLLING).build() val listview = findViewById<ListView>(R.id.listview) val editText = findViewById<AppCompatEditText>(R.id.edit_text) val messageList: List<String> = ArrayList() val arrayAdapter = ArrayAdapter( this@MainActivity, android.R.layout.simple_list_item_1, messageList ) listview.adapter = arrayAdapter
hubConnection.on("ReceiveMessage", { user: String?, message: String? -> runOnUiThread { arrayAdapter.add("ReceiveMessage:${user}--${message}") arrayAdapter.notifyDataSetChanged() } }, String::class.java, String::class.java)
findViewById<AppCompatButton>(R.id.send).setOnClickListener { val message = editText.text.toString() if (message.isEmpty()) { return@setOnClickListener } editText.setText("") try { hubConnection.send("SendMessage", "Android--", message) arrayAdapter.add("SendMessage:${message}") arrayAdapter.notifyDataSetChanged() } catch (e: Exception) { e.printStackTrace() } } coroutineScope.launch { connect(hubConnection, arrayAdapter) } }
override fun onDestroy() { super.onDestroy() coroutineScope.cancel() }
private suspend fun connect(hubConnection: HubConnection, arrayAdapter: ArrayAdapter<String>) { try { withContext(Dispatchers.Default) { hubConnection.start().blockingAwait() arrayAdapter.add( "connectionState:${hubConnection.connectionState}" + "\nconnectionId:${hubConnection.connectionId}" + "\nkeepAliveInterval:${hubConnection.keepAliveInterval}" + "\nserverTimeout:${hubConnection.serverTimeout}" ) arrayAdapter.notifyDataSetChanged() } } catch (e: Exception) { e.printStackTrace() } } }
|