就是用socket编程,已经能和服务端连上了,主要是服务端发来消息后要在TextView上显示,一开始单独写个类把activity传进去直接改里面的TextView,发现不行,就出现上面的异常,百度后说要用handler,就照上面用了handler,可是发现还是不行,别人说不能传activity,应该把操作都放在activity里面,好吧,接着改(其实也没啥就是挪个地方),后来发现还是不行,还是这个异常,我下面贴代码,大家给看看啊。。
package com.example.chatphone;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView disText = null;
private EditText input = null;
private Button btnSend = null;
private MyHandler myHandler = null;
private BufferedReader BR = null;
private PrintWriter PW = null;
private Socket s = null;
private boolean isConnectioned = false;
private Thread thRecv = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myHandler = new MyHandler();
disText = (TextView) findViewById(R.id.disText);
input = (EditText) findViewById(R.id.input);
btnSend = (Button) findViewById(R.id.btnSend);
connection();
btnSend.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
send("hello");
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/**
* 定义handle提醒ui更新
*/
class MyHandler extends Handler {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Bundle b = msg.getData();
String msgStr = b.getString("msg");
disText.setText(msgStr);
}
}
private class Recv implements Runnable {
@Override
public void run() {
while (true) {
try {
System.out.println("run");
String msgStr = BR.readLine();
Message msg = new Message();
Bundle b = new Bundle();
b.putString("msg", msgStr);
msg.setData(b);
System.out.println(msg + "->>");
MainActivity.this.myHandler.handleMessage(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private void connection() {
try {
isConnectioned = true;
s = new Socket("169.254.66.14", 8888);
BR = new BufferedReader(new InputStreamReader(s.getInputStream()));
PW = new PrintWriter(s.getOutputStream());
thRecv = new Thread(new Recv());
thRecv.start();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 像服务器发送消息
*
* @param msg
* 要发送的消息
*/
private void send(String msg) {
PW.println(msg);
PW.flush();
}
}
------解决方案--------------------
myHandler.handleMessage(msg);不能这么用,
而是myHandler.sendMessage(msg);