Matwosk
Matwosk

Reputation: 459

Use AsyncTask in multiple activities

I have a problem with proper use AsyncTask. I use AsyncTask to communicate with the server. I run server connection in AsyncTask doInBackground. My app listens in the background and as soon as captured message uses publishProgress. Then I can use message in my App. In my application I am doing login to the server and if it was successful new activity will start. I need to communicate with the server also in the new activity but the connection was created in the background AsyncTask. I don't know how I can communicate through established connection in new activity. Can anyone give me advice? Thank you a lot!

Please take a look on code. I have this code in LoginUser class and after succesful login to the server new Activity starts.

//init
private ConnectionClass mConnectClass; 
private connectTask mTask;

//execute  connectTask
mTask = new connectTask();
mTask.execute("");

    public class connectTask extends AsyncTask<String, String, ConnectionClass> {
    @Override
    protected ConnectionClass doInBackground(String... message) {
        Log.i("Terminal", "doInBackground.");

        mConnectClass = new ConnectionClass(
                new ConnectionClass.OnMessageReceived() {
                    @Override
                    // here the messageReceived method is implemented
                    public void messageReceived(String message) {
                        // this method calls the onProgressUpdate
                        publishProgress(message);
                    }
                });
        Log.i("Terminal", "Starting...");
        mConnectClass.connectServer();
        return null;
    }

    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);
        answerFromServer = Arrays.toString(values);
        // serverMessage.append("S: " + Arrays.toString(values) + "\n");
    }
}

Upvotes: 0

Views: 124

Answers (1)

kabuko
kabuko

Reputation: 36302

Don't use AsyncTask for this. You seem to want to hold your connection open for an extended period of time. AsyncTask is only supposed to be used for tasks that last at most a few seconds. You might consider using a Service instead.

Upvotes: 2

Related Questions