I am working on a project where I need to use gomobile tool to create an Android app. The sample code I have in Go is as below
var broker = "127.0.0.1"
//var broker = "broker.mqttdashboard.com"
var port = 1883
opts := mqtt.NewClientOptions()
opts.AddBroker(fmt.Sprintf("tcp://%s:%d", broker, port))
opts.SetClientID("go_mqtt_client")
opts.SetConnectionLostHandler(connectLostHandler) // define what to do when connection is lost
client := mqtt.NewClient(opts)
tokenClient := client.Connect()
if tokenClient.Wait() && tokenClient.Error() != nil {
panic(tokenClient.Error())
}
...
When I bind this code using "gomobile bind", generating the Golang plugin and calling them inside the android project there is no issue. Connections is satisfied and I can verify the local mqtt broker (mosquitto) and the mqtt client app are communicating as well.
But when I generate the APK file using "gomobile build -target=android", the connect function generates and error. To be able to test the logs i used a public broker instead of the local mqtt broker. I replaced the
var broker = "127.0.0.1"
by the HiveMQ public broker address (I have already validated the public broker functionality)
var broker = "broker.mqttdashboard.com"
It seems like there is an issue with connecting from mqtt client app to mqtt broker. Here is the exact error message I found in logs:
E/Go: panic: network Error : dial tcp: lookup broker.mqttdashboard.com: No address associated with hostname goroutine 11 [running]: E/GoLog: panic: network Error : dial tcp: lookup broker.mqttdashboard.com: No address associated with hostname E/Go: main.starting()
This is generated by "panic(tokenClient.Error())" part in my code.
Any idea why the connection is not settled using "gomobile build", while it is working when I use "gomobile bind" ?
Here is how I could fix the issue.
I added the AndoridManifest.xml file to the same directory that the main go package is.
Added the following line in between the manifest tags (<manifest> )
<uses-permission android:name="android.permission.INTERNET">