dsb
dsb

Reputation: 2517

Thread.sleep inside IntentService causes ANRs

I have IntentService that I use to upload data to server. When this upload goes wrong (sometimes when the user does not have reception or Internet connection) then I use exponential backoff to try and upload the information again and again. I do this inside the onHandleIntent method, which to my understanding runs in separate thread:

@Override
protected void onHandleIntent(Intent intent) {
    Bundle extras = intent.getExtras();

    if (extras != null) {

        WebPostsRest posts = new WebPostsRest(HTTPVerb.POST, Uri.parse(CONSTS_WEB.URI_POST_NEW_POST), extras, this);

        double backoffMillis = 0;
        int backoffexp = 0;

        int iTries = CONSTS_APP_GENERAL.NO_OF_POST_TRIES;
        while (iTries > 0) {
            mIsSuccess = posts.runRestNoReturnData();
            if (mIsSuccess) {
                iTries = 0;
            } else {
                if (backoffexp < 11) {
                    backoffMillis = Math.pow(2, backoffexp) * 1000;
                    backoffexp++;
                }
                try {
                    Thread.sleep((int) backoffMillis);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                iTries--;
            }
        }

    }
}

For some reason I get ANRs, which I assume come from this Thread.sleep part. Any idea why it happens and how to solve things? thank you.

Upvotes: 0

Views: 897

Answers (1)

Mohammad Haque
Mohammad Haque

Reputation: 565

I had the same problem and in my case it was causing by queue for the IntentService. Make sure you are not calling this intent service multiple times. It seems if first call of IntentService fail and use Thread.sleep() and at the same time more request are in waiting mode to use this IntentService then it throws ANR.

Upvotes: 2

Related Questions