简体   繁体   中英

How do you maintain TCP connection with a server when changing activity?

I am kind of desperate. I am working on an application that is supposed to visualize pollution data. The application connects to the sensor via WiFi direct, the sensor is the group host. Then I am supposed to connect to port 5001 and retrieve data every 2 minutes. This data is supposed to be sent to a google maps activity where it will be visualized in an infowindow.

At this moment I have only been able to create a TCP connection that closes down immediately, I followed this Really simple TCP client .

So I need to establish a TCP connection that does not close and also runs when I am in other activities. I do not need to send any messages, only retrieve data.

I looked into this How to keep the android client connected to the server even on activity changes and send data to server? but did not understand how I am to implement that code for my case.

How do you do this? Appreciate any help.

Your android App is a Client, every time you need to get data you can ask it from the Server.

If Server working in Blocking mode you can send a request to the Server and Server sent Response through the opened connection

Here is some examples of Client/Server connection with Socket :

https://examples.javacodegeeks.com/android/core/socket-core/android-socket-example/

https://github.com/codepath/android_guides/wiki/Sending-and-Receiving-Data-with-Sockets

You can find more examples

At this moment I have only been able to create a TCP connection that closes down immediately

It relies on your Server design, Client app will send the request to the Server and if Server send back the response you can get it, but if the Server have no Response to sent your connection will be closed

So I need to establish a TCP connection that does not close and also runs when I am in other activities. I do not need to send any messages, only retrieve data

See the links above, there is no need to create a connection that does not close, you should send your request and get the response from Server every time you need

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM