在活动之间切换时处理/销毁线程

时间:2014-05-07 19:18:13

标签: android thread-safety

我的申请中有两项活动。 MainActivity有一个与服务器建立连接的线程,如下所示: -

public class MainActivity extends Activity implements OnItemSelectedListener {

private Socket socket;
private static final int SERVERPORT = 8020;
private static final String SERVER_IP = "192.168.1.36";
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main); 
            new Thread(new ServerThread()).start();
    }
    public void onClickon(View view) {
    try{

    PrintWriter out = new PrintWriter(new BufferedWriter(
            new OutputStreamWriter(socket.getOutputStream())),
            true);
    out.println("0"); 
    }
    catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
     private void newActivity(View view) {
     Intent intent = new Intent(MainActivity.this, LockActivity.class);
     startActivity(intent);
     }
     class ServerThread implements Runnable {

    @Override
    public void run() {

        try {
            InetAddress serverAddr = InetAddress.getByName(SERVER_IP);

            socket = new Socket(serverAddr, SERVERPORT);

        } catch (UnknownHostException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }

    }

}
    }

当用户点击按钮向服务器发送消息时,将调用onClickOn()函数。 现在,当用户想要转到新活动时,将调用newActivity()函数。

新活动的代码如下。

public class NewActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_lock);

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();
    }
}
public void buttonOKclicked(View v)
    {
        String msg=Integer.toString(foo);
        Intent intent = new Intent(LockActivity.this, MainActivity.class);
        intent.putExtra("keyMessage", msg);
        startActivity(intent);

    }
    }

当用户在NewActivity时,他点击了调用buttonOkclicked()的按钮,该按钮返回MainActivity

当用户返回MainActivity时,应用程序无法连接回服务器。

我该如何解决这个问题?

我可以在创建ServerThread MainActivity`之前杀死NewActivity, so that when the user gets back to the,是否可以启动新线程?

0 个答案:

没有答案