tags:

views:

42

answers:

2

Is it possible to have broadcastReceiver running inside a thread (just broadcastReceiver)? As far as I know, this can't be done unless there is a way to keep the thread alive (even tough there is no work). Please correct me if I'm wrong.

This is what I want to do: I have a client and a server program that run without knowing when anyone of them will be ready. The client will keep trying to send a request to the server while at the same time monitoring a reply from the server. Upon receiving a reply from the server, that means the server is online.

I have tried to use thread (on the client) to keep sending a request to the server with a periodical sleep. And then have the client main thread to do a while loop with a periodical sleep (hoping to catch a reply when there is a broadcast from the server). Unfortunately, this does not work.

The client extra thread has been verified to send a request, the server has send a reply, but for some reason the client main thread does not receive anything. Implementation of the broadcastreceiver on both server and client have been verified to work, so that's not the issue.

Anyone has a better solution/approach for this problem?

A: 

From what i understood, when the client main thread is in sleep, it cant receive the broadcast from the server. so here it fails..

May be you can do this way.. We can write custom broadcasts so that when ever server is ready then you send a broadcast intent to client.. Then client broadcastReceiver will start the thread you need.. you can send requests to the server, the same way..

Guess it might help.. :)

manidhar mulaparthi
Not sure it's going to work. The server never aware of when the client is ready. That means the broadcast from the server has a chance of not received by the client. Now, this becomes similar to my original problem (in reverse), the client become the server in my original question, and vice versa. I need to have at least two thread on the server: one for receiving and another one for keep broadcasting to the client.
A: 

I solve this problem by using two threads (including main thread) on the client side. Create a new thread (call it thread X) to keep on requesting service from the server (with a sleep). Keep main thread idle, don't put it to sleep or execute thread.join()). Once the main thread intercept the response from the server, signal the thread X to kill itself. This way, we have broadcast receiver still running on the main thread without getting block and we also have a different thread to keep requesting the server. The down side of this approach is that your next commands (after getting a response from server) has to be executed from onReceive().

Anyone has a better solution?