简体   繁体   中英

How do I keep my Android app continuously connected with my own RESTful API to retrieve data continuously?

Please help me guys ! Please

I am using retrofit to connect with my RESTful API which is running on Express and Node. Now I want to fetch my data from api continuously means there should be a continuous connection of my app with api.

Retrofit enqueues the requests and we need to keep it sending again and again. I've tried by creating a retrofit call inside a services but it reflects the UI constantly which means it makes call continuously.

So how can I do that? DO I need to make my restful service a real-time? or is there any way to make this calls? (Please don't tell me about Firebase or Parse or Anything)

I do not know a lot about your requirements, but if you really need to keep up a connection to your backend continuously, then maybe REST is not a good way to achieve that.

If you do not want to result to some proprietary solutions like you mentioned, there are a lot of ways to achieve what you want to, using Socket Connections with a data format like protobuf and a methodology like RPC to communicate. I have not used it before but after brief googling I found http://www.grpc.io/ which sounds rather promising.

If you want to keep up REST as your API type, then you will need to resort to a poll based approach or maybe a Push (notification) based approach, where you just constantly poll your endpoint, or start polling for new data after a push notification is received.

EDIT:

As mentioned in the comments... In your case you could have a look at https://socket.io/blog/native-socket-io-and-android/ to connect live data from your backend to an app. It will work just fine if your backend can handle the requirements that come with keeping up a lot of connections with your clients.

You can do this by initiating your API call inside a Handler, which will run in a time interval. It will call your API every time when the Handler runs. You can do it like this:

    Handler handler = new Handler();

    final Runnable r = new Runnable() {
        public void run() {
            //Initiate your API here
            handler.postDelayed(this, 5000);
        }
    };

    handler.postDelayed(r, 5000);

It will intiate your API in every 5 seconds(5000 miliseconds).

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