我正在尝试从onCreate()
的MainActivity
方法向Connection
线程发送消息,然后该线程通过udp socket
将数据发送到服务器。但是该应用程序连续崩溃。请告诉我如何将数据从UI线程发送到非UI线程。
MainActivity的onCreate()方法。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Looper.prepare();
Thread connection = new Thread(new Connection());
connection.start();
Message msg = Message.obtain();
Bundle bundle = new Bundle();
bundle.putString("NAVIGATION", "Message");
msg.setData(bundle);
if(Connection.getHandler() == null){
Connection.getHandler().sendMessage(msg);
}
Looper.loop();
}
连接类别
public class Connection implements Runnable {
private DatagramSocket client_socket = null;
private InetAddress host = null;
private byte[] buffer = null;
private static Handler handler = null;
private String data = null;
@Override
public void run() {
boolean status = this.create();
if(status) {
while (true) {
Looper.prepare();
Connection.handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Connection.handler.obtainMessage();
String data = msg.getData().getString("NAVIGATION");
send(data);
}
};
Looper.loop();
}
}
}
private boolean create(){
try{
this.client_socket = new DatagramSocket();
} catch(Exception e){
Log.e("Connection", e.getMessage());
return false;
}
try{
this.host = InetAddress.getByName("192.168.0.107");
} catch (Exception e){
Log.e("Connection", e.getMessage());
return false;
}
return true;
}
private void send(String nav){
this.buffer = nav.getBytes();
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, this.host, 12345);
try{
this.client_socket.send(packet);
} catch (Exception e){
Log.e("Connection", e.getMessage());
}
}
public static Handler getHandler() {
return Connection.handler;
}
}
if(Connection.getHandler() == null){
Connection.getHandler().sendMessage(msg);
}
这似乎是罪魁祸首-您说“如果为空,请使用它”
也许你打算写Connection.getHandler() != null
还请在onCreate以及您的连接初始化中添加日志消息,以确保在onCreate运行之前已创建连接