GeoCap
GeoCap

Reputation: 515

Change Activity when connected to server (TCP)

After I check if inputs are correct, I bind the activity to service to send it ip, port... and start a new activity. But I want to start the activity only after app successfully connected to the server or else don't.

First activity

btnConnect.setOnClickListener {
    //some checks
    //if checks pass

    //bind to service
    Intent(this, MyService::class.java).also { intent ->
            intent.putExtra("ip1", ip1)
            intent.putExtra("port1", port1)
            bindService(intent, connection, Context.BIND_AUTO_CREATE)
        }

    //++should wait here until connected++

    //open new activity
    val intent = Intent(this, HomeActivity::class.java)
    startActivity(intent)
}

Connection in service

fun startConnection(ip: String, port: Int) {
    try {
        socket = Socket(ip, port)
        //if successful continue below

Upvotes: 0

Views: 52

Answers (1)

eeqk
eeqk

Reputation: 3862

How about passing a callback to the startConnection method? It'd look something like this

btnConnect.setOnClickListener {

    Intent(this, MyService::class.java).also { intent ->
            intent.putExtra("ip1", ip1)
            intent.putExtra("port1", port1)
            bindService(intent, connection, Context.BIND_AUTO_CREATE)
        }


    startConnection("localhost", 8080, onConnectionEstablished = {
        val intent = Intent(this, HomeActivity::class.java)
        startActivity(intent)
    })
}


fun startConnection(ip: String, port: Int, onConnectionEstablished: () -> Unit) {
    try {
        socket = Socket(ip, port)
        onConnectionEstablished()
        //stuff

Upvotes: 1

Related Questions