开发者

problem in starting a background thread

I have a backgorund thread that extends AsyncTask and which I use in activity to read some data from a DB.

I use this background thread in order for not to get my app blocked because of the big amount of data that needs to be retrieved.

Usually I start the thread this way:

public void onResume(){

init_task.execute(db);

}



 public class InitTask extends AsyncTask<DBAdapter, GeoPoint, Void> {

...some code here....


}



    protected void onPause() {
        init_task.cancel(true);
        super.onPause();
    }

The point is that I start the thread in onResume() and cancel it in onPause()

But now I have a different problem.

I have an autocomplete that displays a dropdown list and when I click on one of these entries I wanna start the backround thread(the data that I retrieve now from DB depends on the item that I click on).

Well for that I've implemented a listener and I start the thread there....The problem is that the listener is onCreate() so I can't use onResume() inside onCReate() ....

Now my problem is that I don't know how to stop the thread cause once开发者_Python百科 I leave the activity it still retrieves data from my DB...and I want it to stop.

Here is a diagram of my code:

public void onCreate(Bundle savedInstanceState){

    textView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {


                init_task = new InitTask();
                init_task.execute(db);

            }

        });


}

public class InitTask extends AsyncTask<DBAdapter, GeoPoint, Void> {


}

Question: Where should I stop my thread so as soon as I leave the activity it stops retrieving data from the DB......and after I come back it starts again!!?


You can assign the task to instance field and check it for null before calling cancel.

In your activity class (not onCreate() method)

InitTask initTask=null;

in onPause()

if (initTask!=null) {
    initTask.cancel(true);
    initTask=null;
 }

Rest is the same.


Why are you can't still access your init_task? In your scheme there are no any visible restrictions on cancelling AsyncTask instance you have created in a listener.

To deal with restarting you can save some flag and continue fetching after activity is resumed.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜