How can I put a timer in an AsyncTask without creating another thread?

僤鯓⒐⒋嵵緔 提交于 2020-01-03 03:32:26

问题


I have an asynchronous task that I use to connect to a website (Twitter). In certain situations (eg. when Twitter post update fails) I want to wait 10 seconds before trying again. As I am already in an async task I dont want to start another thread for the timer.

Any suggestions would be great :). Code below...

        class SendTwitAsyncTask extends AsyncTask<String, Void, Void> {

    @Override
    protected Void doInBackground(String... params) {



        String tokenTwit = params[0];
        String tokenSecretTwit = params[1];
        String strMessageBody = params[2];

        AccessToken aToken = new AccessToken(tokenTwit, tokenSecretTwit);



        // initialize Twitter4J
        Twitter twitter = new TwitterFactory().getInstance();
        twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
        twitter.setOAuthAccessToken(aToken);
        aToken=null;

        // create a tweet
        Date d = new Date(System.currentTimeMillis());
        String tweet = strMessageBody;

        try {

        status = twitter.updateStatus(tweet);


        // feedback for the user..
        showNotification("Twitter", TWIT_SUCCESS);  

    } catch (TwitterException te) {



        showNotification("Twitter ", TWIT_FAIL);
        te.printStackTrace();

                       //TO DO
                       //POSTING TWEET HAS FAILED.  TRY AGAIN IN 10 SECONDS


    }

        return null;
    }



} //end class SendTwitAsyncTask

回答1:


There are many ways to do this. I'd probably go with Handler.postDelayed in your case.

Create a Handler object marked final at the same scope as your AsyncTask

final Handler handler = new Handler();

Then call postDelayed from inside the AsyncTask to schedule the next run, where necessary:

    handler.postDelayed(new Runnable() {

        public void run() {
            new SmartTwitAsyncTask.execute(param);
        }
    }, 10000);



回答2:


I know it's old thread but for the sake of future readers like me I dont think you should put Thread.sleep(1000*10); in onPostExecute because this will block UI thread and all point of activetask is to keep UIthread free of work.

You can put it here:

protected String doInBackground(String... params) {

where it belongs.




回答3:


 @Override
    protected String doInBackground(String... params) {



        String tokenTwit = params[0];
        String tokenSecretTwit = params[1];
        String strMessageBody = params[2];

        AccessToken aToken = new AccessToken(tokenTwit, tokenSecretTwit);



        // initialize Twitter4J
        Twitter twitter = new TwitterFactory().getInstance();
        twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
        twitter.setOAuthAccessToken(aToken);
        aToken=null;

        // create a tweet
        Date d = new Date(System.currentTimeMillis());
        String tweet = strMessageBody;

        try {

        status = twitter.updateStatus(tweet);


        // feedback for the user..
        showNotification("Twitter", TWIT_SUCCESS);  

    } catch (TwitterException te) {



        showNotification("Twitter ", TWIT_FAIL);
        te.printStackTrace();

                       //TO DO
                       //POSTING TWEET HAS FAILED.  TRY AGAIN IN 10 SECONDS
                       return status;

    }

        return status;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
    if(status.equals("failed"))
    {
    Thrad.sleep(1000*10);
    new SmartTwitAsyncTask.execute(param);

    }
    if(status.equals("success"))
    {
    //proceed
    }

}


来源:https://stackoverflow.com/questions/6921351/how-can-i-put-a-timer-in-an-asynctask-without-creating-another-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!