开发者

to cancel a ongoing operation

i have two threads one for downloading and other for displaying data there is a cancel button in layout i want when i click cancel button the downloading thread stops how can i do this

final Thread parseThread=new Thread(new Runnable() {
    public void run() 
    {
        count=1;
        searchResult.clear();
        Log.v("url","++"+"http://wap.vinmonopolet.no/vareutvalg/sok?query="+v.getText());
        Log.v("searchText","searchText  "+ v.getText());
        downloader("http://wap.vinmonopolet.no/vareutvalg/sok?query="+v.getText());

        //if(msearchCancel)
    }
});
parseThread.start();


Thread displayThread = new Thread(new Runnable() {
    public void run() {
        try {
            if(msearchCancel)
                parseThread.interrupt();
            else
                parseThread.join();
        }
        catch (InterruptedException e) 
        {
            e.pri开发者_JS百科ntStackTrace();
        }  
        mHandler.post(new Runnable() {  
            public void run() 
            {
                list_ed=new EfficientAdapter(getApplicationContext());
                searchList.setAdapter(list_ed);
                progress_waiting1.setVisibility(ProgressBar.GONE);
            }
        });
    }
});
displayThread.start(); 


First, use AsyncTask for tasks in own threads, it's much easier and handles some low level stuff for you.

Then, in your thread (or background task in AsyncTask), you need periodically to check that main thread requests cancel. In AsyncTask it is isCancelled method.

If you detect cancel request, you exit thread's function ASAP, so that thread may be closed. Otherwise, in case of AsyncTask.cancel, canceling is blocked until background task (thread) gracefully ends.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜