hkftwe
hkftwe

Reputation: 65

How to close parent thread on Android

I would like to do step by step upload date to web service. My code:

private Thread WebServiceThread;

public void onCreate(Bundle savedInstanceState) {
    //...
    WebServiceThread = new WebService();
    WebServiceThread.start();
}

private class WebService extends Thread {
    public void run() {
        try {
            new WebServiceUpload().execute("");
        } catch (Exception e) {
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT)
                .show();
        }
    }
} 

private class WebServiceUpload extends AsyncTask<String, Void, String> {
        protected String doInBackground(String... data) {
            // upload part
        }

        protected void onPostExecute(String result) {
            //...
            WebServiceThread = new WebService();
            WebServiceThread.start();
            //<Tab>__what to do here__</Tab>
            //...
        }
}

Now can run, but cause the device slow. Please tell me how to close parent thread or restart parent thread way to solve this problem. (or other practice to same target.)

Upvotes: 0

Views: 190

Answers (2)

Ted Hopp
Ted Hopp

Reputation: 234807

You don't have to chain threads like that. Just create a single AsyncTask extension that uploads the data step by step in doInBackground. If you want to publish progress reports, you can do that by calling publishProgress.

Your method of creating a WebServiceUpload from a worker thread is really bizarre and will most likely not work. AsyncTask is designed to be started from the UI thread. Just call your new WebServiceUpload().execute() from the main thread when you want to start the upload steps.

Upvotes: 1

Serdar Samancıoğlu
Serdar Samancıoğlu

Reputation: 740

In your onPostExecute check if thread is running then force it to stop.

protected void onPostExecute(String result) {
            //...
            **if (WebServiceThread.isAlive())
                 WebServiceThread.stop();**
            WebServiceThread = new WebService();
            WebServiceThread.start();
            //<Tab>__what to do here__</Tab>
            //...
        }

Upvotes: 0

Related Questions