开发者

Android thread won't stop running

I have a basic asynchronous task that performs a web request. The thread is not contained in a loop or anything, it performs the request and returns from run(). When I try to execute another request, using that thread, I get an exception thrown because the thread is already running. I've searched around a lot on this site for answers, but all that seems to come up is stopping threads that are in a loop, basically forcing the thread to return.

Should I just put the request code in the thread into a loop that waits on some kind of flag from the main thread to tell it to go ahead and execute again? like:

public void run()
{
    while ( threadIsStillRunning )
    {
        while ( !threadShouldExecute )
        {
            //Sleep the thread
        }
        //Execute the request

    }
}

EDIT: Ok, well here's the thread (this is contained in one of my class objects-WebServiceHelper):

private Thread executeRequest = new Thread()
{
    public void run()
    {
        //Meat of the code
        isRunning = false;
    }
}

I then have another class method in the same class(WebServiceHelper):

private volatile boolean isRunning = false;
public void Execute(WebServiceHandler handler)
{
    while ( isRunning )
    {
        try 
        {
            Thr开发者_Python百科ead.sleep(1000);
        } 
        catch (InterruptedException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    isRunning = true;
    r = handler;
    executeRequest.start();
}

where r is just an interface object that I use to perform callbacks to the object performing the request.

Then in my main activity (the one that requested the thread execution i have this:

private Runnable getSiteData = new Runnable(){
    public void run(){
        mWebServiceHelper.SetMethod("GetSiteData");
        mWebServiceHelper.Execute(mySiteHelper);
    }
};

public void downloadDidFinish(List<Map<String, String>> data)
{
    // TODO Auto-generated method stub
    TeamList.StoreTeams(data );

    mHandler.post(getSiteData);
}

downloadDidFinish gets called by the thread above upon completion, I then perform another request right after as you can see. The crash is happening when I try to call Execute again on the WebServiceHelper and start the thread again.


Asynctask is very useful to manage your threads.
https://developer.android.com/reference/android/os/AsyncTask.html
https://developer.android.com/resources/articles/painless-threading.html

Here is an example: http://labs.makemachine.net/2010/05/android-asynctask-example/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜