3

Hello . I have an android app connected to a c++ server using TCP connection. My first activity lets user to write ip address and port to connect with server, then this activity calls another one using an intent. The second activity does the socket connection and run a couple of threads.

Second activity also has a disconnect button; when you press that button, it is supposed to stop all running threads , close socket connection and go back to activity one and let user to connect again if needed.I haven't been able to do so. I have tried with socket.close() but then my threads collapse and does not allow to reconnect . I had also tried with this.onDestroy(); or this.finish(); the activity closes but it is still connected to server.

How can I finished all threads and sockets when finishing an activity and go back to previous activity?

To make it clearer here is my code:

First activity:

public class FirstActivity extends Activity {
 EditText editTextAddress, editTextPort; 
 Button buttonConnect, buttonClear;
 Intent intent;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_ipclient);

      editTextAddress = (EditText)findViewById(R.id.address);
      editTextPort = (EditText)findViewById(R.id.port);
      buttonConnect = (Button)findViewById(R.id.connect);  
 }
 public void onClickConnect(View v){
     String ip=editTextAddress.getText().toString();
     int port=Integer.valueOf(editTextPort.getText().toString());
     intent=new Intent(this,SecondActivity.class);
     Bundle extrasB=new Bundle();
     extrasB.putString("ip",ip);
     extrasB.putInt("port",port);
     intent.putExtras(extrasB);
     startActivity(intent);
 }
}

SecondActivity

public class SecondActivity extends Activity {
....

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_client_late);
    .....
    updateConversationHandler = new Handler();
    new Thread(new ClientThread()).start();
    sendImage=new SendImage();
    sendImage.execute();
 }
    public class SendImage extends AsyncTask<Void,Void,Void>{
    @Override
    protected Void doInBackground(Void... arg0){
        .....
    }
}
class ClientThread implements Runnable {

    @Override
    public void run() {

        thread1=Thread.currentThread();
        try {
            InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
            socket = new Socket(serverAddr, SERVERPORT);

            socketTE = new Socket(serverAddr, SERVERPORT);
            CommunicationThread commThread = new CommunicationThread(socketTE);
            new Thread(commThread).start();
        } catch (UnknownHostException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

}

class CommunicationThread implements Runnable 
{

    private Socket clientSocket;
    private BufferedReader input;
    public CommunicationThread(Socket clientSocket) 
    {
        thread2=Thread.currentThread();
        this.clientSocket = clientSocket;
        ....

    }
    public void run() 
    {
        while (!Thread.currentThread().isInterrupted()) 
        {
            .....                   
        }
    }
}

class updateUIThread implements Runnable 
{
    private String msg;
    public updateUIThread(String str) 
    {
        thread3=Thread.currentThread();
        ...
    }
    @Override
    public void run() 
    {                     
            ....
    }
}

**public void disconnectButtonOnCLick(View v) throws IOException{
    super.onStop();
    super.finish();
}**
@Override
protected void onDestroy() {
    super.onDestroy();
    sendImage.cancel(true);
    thread1.interrupt();        
    thread2.interrupt();
    thread3.interrupt();
    try {
        socket.close();
        socketTE.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

}
Dany19
  • 551
  • 9
  • 26

2 Answers2

1

for the async task:

@Override
    public void onPause(){
        super.onPause();
        if (sendImage!=null) {
            sendImage.cancel(true);
            }
}
Mike
  • 2,547
  • 3
  • 16
  • 30
erik
  • 4,946
  • 13
  • 70
  • 120
  • and where should I call the onPause method? – Dany19 Jul 16 '14 at 16:42
  • you shoudn't explicitly call onPause. it's called automatically. Please take a look: http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle – Mike Jul 16 '14 at 16:48
1

Well, first thing is you shouldn't call this.onDestroy() explicitly. You should call finish() to close the activity. onDestroy() is a callback that is called when acvitity is destroying. so you should override onDestroy like you do with onCreate():

@Override
protected void onDestroy() {
    super.onDestroy();
    // close all your threads
}

Second. to close all threads you can tak a look at this thread - android best and safe way to stop thread. You can also use boolean variable to indicate whether Threads are stopped: public static boolean isStopped; like in answer by Malcolm link above. And how to close socket - How can a socket be both connected and closed?. Hope this helps.

Community
  • 1
  • 1
Mike
  • 2,547
  • 3
  • 16
  • 30