Search code examples
javaandroidsocketsandroid-asynctask

android AysncTask doInbackground


I am new in android, I am trying to implement socket in android it is a simple client-server app. where I have created 2 buttons ("connect", "disconnect"), and using AysncTask doInBackground i am connecting to the server and disconnecting from the server but it's working for connection only, when I am trying to disconnect my app close unfortunately. Below there is my mainactivity code. Thanks for helping

package com.example.sockettest;

import androidx.appcompat.app.AppCompatActivity;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import java.io.*;
import java.util.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.lang.String;
class conn extends AsyncTask<String, Void, Void>{


    Socket operator_socket;
    @Override
    protected Void doInBackground(String... voids)  {
        String str;
        str = voids[0];
        if (str.equals("conn")) {
            try {
                operator_socket = new Socket("192.168.0.103", 6666);

            }catch (UnsupportedEncodingException e) { e.printStackTrace(); }
             catch (UnknownHostException e) { e.printStackTrace(); }
             catch (IOException e) { e.printStackTrace(); }
        } else if (str.equals("CC")){
            try {
                operator_socket.getOutputStream().write("EX".getBytes("US-ASCII"));
                operator_socket.close();
            } catch (UnsupportedEncodingException e) { e.printStackTrace(); }
              catch (UnknownHostException e) { e.printStackTrace(); }
              catch (IOException e) { e.printStackTrace(); }
        } else {

        }
    return null;
    }
}

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    conn new_conn = new conn();
    public void connect_operator(View v){
            new_conn.execute("conn");
    }
    public void close_conn(View v){ new_conn.execute("CC"); }
}


Solution

  • You can call execute only once on one instance of an AsyncTask. new_conn is being initialised only once. Now if you try to create a new object every time to call execute, you won't be able to use operator_socket Socket variable as a member variable of AsyncTask class. You are getting exception when calling execute more than once on a single instance of AsyncTask

    Read these docs