简体   繁体   中英

Java/Android - How to set timeout external service call with handler

My scenario is an onCreate() activity method which executes the following code (simplified):

dialog.show(); //loading wheel
try {
    remote.sendRequest(myData, new MyHandler());
}
catch (Exception e) {
    dialog.dismiss();
    //log and react    
}

class MyHandler extends SDKSpecificCompiledHandler {

    @Override
    public void failure() {
        dialog.dismiss();
        //do stuff
    }

    @override
    public void success() {
        dialog.dismiss();
        //do stuff
    }

}

//I have read-only access to this handler!
public abstract class SDKSpecificCompiledHandler {
    public abstract void success(JSONObject successData);
    public abstract void failure(JSONObject errorData);
}

Explanation: A remote service is called passing an handler that gets called when he's done. A loading wheel (dialog) is shown to the user until a success, failure or exception happens.

The problem is when the service gets successfully called but no response ever comes. In that case dialog.dismiss() doesn't get called and the loading wheel keeps spinning for ever.

What I need is a sort of timeout which dismisses the dialog (and possibly takes other actions) after some seconds if the server doesn't get back.

My first though would be to create a new thread for the service call, and right after the launch set a timer which dismisses the dialog. Would it be a good idea?

Thank you,

EDIT :

The service is third-party/not editable. I'm using a pre-compiled artifact.

It is better to use time out in service call itself, You can set the time out with service , If you need know how to set the time out then I should know what kind of service you are using ?

One more thing is that if you are using a loader you should make that loader in such a way that it can be cancel by the client.

Still not really sure what you're trying to achieve but if you want to run some code after some time on main thread (ie your code will do stuff to the UI), you can use a android.os.Handler

    mHandler = new Handler(getMainLooper());
    mHandler.postDelayed(new Runnable() {
        @Override
        public void run() {
            // do stuff on UI thread
        }
    },10000);

When your call returned from the server, simply cancel the messages on the queue:

    mHandler.removeCallbacksAndMessages(null);

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