private Myhandler myhandler = new Myhandler(this);
private SocketConnectorThread connectorThread;
private SZdialogadpter sZdialogadpter;
Button connect;
TextView text;
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.connect:
sZdialogadpter = new SZdialogadpter(MainActivity.this);
sZdialogadpter.setConnectLister(new SZdialogadpter.ConnectLister() {
@Override
public void connect(String IP, int Post) {
socketinit(IP, Post);
sZdialogadpter.dismiss();
}
});
sZdialogadpter.show();
break;
}
}
class Myhandler extends Handler {
private WeakReference<MainActivity> weekActivity;
private byte[] bytes;
public Myhandler(MainActivity mainActivity) {
this.weekActivity = new WeakReference<>(mainActivity);
}
@Override
public void handleMessage(@NonNull Message msg) {
switch (msg.what) {
case 0:
Log.d("TAGGGGG", "handleMessage: " + "连接失败");
Toast.makeText(MainActivity.this, "连接失败", Toast.LENGTH_SHORT).show();
break;
case 1:
Log.d("TAGGGGG", "handleMessage: " + "连接成功");
Toast.makeText(MainActivity.this, "连接成功", Toast.LENGTH_SHORT).show();
break;
case 2:
bytes = (byte[]) msg.obj;
String s="";
for (int i = 0; i < bytes.length; i++) {
s = s + "" + bytes[i];
}
text.setText("s");
break;
case 3:
Log.d("TAGGGGG", "handleMessage: " + "接收消息断开");
break;
case 4:
Log.d("TAGGGGG", "handleMessage: " + "发送成功");
break;
case 5:
Log.d("TAGGGGG", "handleMessage: " + "发送消息断开");
break;
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connect=findViewById(R.id.connect);
text=findViewById(R.id.text);
}
public void socketinit(String IP, int post) {
connectorThread = new SocketConnectorThread(IP, post, myhandler);
connectorThread.start();
Toast.makeText(MainActivity.this, IP + " " + post, Toast.LENGTH_SHORT).show();
}
Android socket连接硬件 发送和接收消息 这是我从项目里剥离出来的 这里就不展示全部代码 有问题可以私我 附上百度云项目地址 自己去下。。。。
https://pan.baidu.com/s/1r_yvSzAgweLaUb24vJ3_iA 提取码:b50f
|