Abhishek
Abhishek

Reputation: 783

Android: Wait for server to respond

I'm getting an Android server's response in an AsyncTask at Client.

Problem is, how do I force the client to wait for server to respond ? Reson being sometimes it may take a few mins for server to respond.

More specifically, how do I detect if socket.getInputStream.read() doesn't contain anything, and force the client into a wait loop ?

Upvotes: 2

Views: 1049

Answers (3)

Abhishek
Abhishek

Reputation: 783

I have stopped using AsyncTask. Instead, I use Android's ThreadPool executor with a fixed threadpool of 5:

ExecutorService executor = Executors.newFixedThreadPool(5);
        Runnable worker = new ServerThread();
        executor.execute(worker);

This code is at the Client as well as the Server's end. The advantage is that its much more reliable than AsyncTask. The only disadvantage is the fixed size of the threadpool (but AsyncTask is also limited anyway).

Upvotes: 0

AKSH
AKSH

Reputation: 211

I have made a code like this

boolean status;
// isURLReachable is the method to check server is available or not

status = isURLReachable(context);
                        if (status == true) {
                            h.post(new Runnable() {

                                @Override
                                public void run() {
                                    checkLoginDialogue
                                            .setTitle("Authenticating User");

                                }
                            });
                            handlerForLogin.sendMessage(handlerForLogin
                                    .obtainMessage());
                        } else {
                            h.post(new Runnable() {

                                @Override
                                public void run() {
                                    if (checkLoginDialogue.isShowing()) {
                                        checkLoginDialogue.dismiss();
                                    }
                                }
                            });
                            System.out.println("status IS " + status);
                            handler.sendMessage(handler.obtainMessage());

                        }

Hope this help

Upvotes: 4

ColdFaith
ColdFaith

Reputation: 401

You can send a broadcast from your AsyncTask to the client.

  • The client does his work.
  • Then the AsyncTask is getting the data.
  • When the AsyncTask finished getting data, it sends a broadcast.
  • The client receives the broadcast with a broadcast receiver and then continues working. -> Search on the internet for "Android BroadcastReceiver tutorial" there you will find good exampels.

Hope this will help you =).

Upvotes: 0

Related Questions