开发者

AsyncTask doesn't run sometimes despite state being RUNNING?

In my application I use an AsyncTask on start up of my Activity to fetch the ringtone of a particular contact.

It works normally but I have noticed that if the application is stopped twice before the AsyncTask gets to the doInBackground method then when the Activity starts again the AsyncTask fails to run properly, only getting to the onPreExecute() method.

Here is my code:

The AsyncTask itself:


private class SelectRingtoneTask extends AsyncTask<String, Void, Void> {

          // can use UI thread here   
          protected void onPreExecute() {
              Log.d("cda", "Into selectRingToneTask - onPreExecute() - " + selectRingtoneFinished);
          }

          // automatically done on worker thread (separate from UI thread)
          protected Void doInBackground(final String... args) {
              Log.d("cda", "Into selectRingToneTask - !!!!!!!!!!!!!!!");
             getRingTone();
             return null;
          }

          // can use UI thread here
          protected void onPostExecute(final Void unused) {
           selectRingtoneFinished = true;
           Log.d("cda", "Into selectRingToneTask - onPostExecute - " + selectRingtoneFinished);
          }
       }

Where I call the AsyncTask on start up:


if(srtt == null){
srtt = new SelectRingtoneTask();
Log.d("cda", "RingTone - " + srtt.getStatus());
}
srtt.execute();

The problem occur's when I start the activity and close the Activity before the AsyncTask finish开发者_如何学运维es, if this happens once, it seems to be fine but after it happens a second time the AsyncTask will only ever get to the onPreExecute() method and will never complete again until the application is force stopped and restarted.

Has anybody got any idea why this would be happening?


You need to cancel the AsyncTask when your Activity is destroyed, and in AsyncTask's methods check for isCancelled flag before attempting to work with the fetched results.

I highly recommend reading the source code of Shelves to see how to persist tasks across configuration changes and how to cancel them properly when the activity is destroyed.


    if(srtt == null){    <--- Not needed
        srtt = new SelectRingtoneTask();
        Log.d("cda", "RingTone - " + srtt.getStatus());
    }
    srtt.execute();

Im not sure what do you meen by close, but I had similar problem with thread. In my opinion problem here is that you fire second time this same activetask, when you are not allowed to do. to sole the problem when you close activity, cancel thread and make sure you set srtt to null. Hope this helps

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜