Question

I am working with a HTTP rest API and I need to be able to register to receive asynchronous event notifications.

The application first establishes an event channel for event delivery by sending a POST request to the API. The event channel is established as a streaming HTTP connection. This persistent connection is created using Comet semantics.

Is it possible set up a long running HTTP connection with Java/Android?

I believe some sort of Socket is required that allows you to post data too.

EDIT The application I am creating will be on a device that always has a Ethernet connection and also mains power. So power/connectivity issues are not really a problem.

Was it helpful?

Solution

IMO - comet is not suitable for consumption by low power devices on 4g...

This rest api you are consuming is not ready for mobile until it upgrades with an internal proxy/gateway to reach out on PUSH protocol to IOS/Android clients that prefer event notification via another API/ protocol that is more suitable than Comet.

If you must consume the api and reach android at the same time then consider building a proxy for your Android users that will convert the Comet-calls to android push messages.

You might look at something like Parse.com because they have great Native REST and Push for the android side. ie it would not be a big deal to proxy on a Heroko/AWS node and then send native android push to your clients.

--EDIT android code

OTHER TIPS

Yes it is possible, you could e.g. implement such connections in a Service, which runs even if your application is not running. If required, you could also request permissions to prevent the device/CPU from sleeping (e.g. WAKE_LOCk).

What kind of connection you then use (via HttpUrlConnection or Apache HttpClient, GET, POST etc.) is up to you and your needs. However, pay special attention to this warning in the docs:

Caution: A service runs in the main thread of its hosting process—the service does not create its own thread and does not run in a separate process (unless you specify otherwise). This means that, if your service is going to do any CPU intensive work or blocking operations (such as MP3 playback or networking), you should create a new thread within the service to do that work.

If timeouts are an issue, you might need to set those to infinite values, e.g. with setReadTimeout(0) (docs, although connections shouldn't time-out by default) or other timeout-configurations.

Also keep in mind that long running (networking) operations can drain the battery really fast.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top