public class Readtask extends Thread{
@Override
public void run() {
byte[] buffer = new byte[1024];
int bytes;
InputStream inputStream;
while(true){
try{
inputStream = socket.getInputStream();
if((bytes = inputStream.read(buffer)) > 0){
byte[] buf_data = new byte[bytes];
for(int i = 0;i < bytes;i++){
buf_data[i] = buffer[i];
}
String s = new String(buf_data);
//TODO
//读取的数据进行处理
Message msg = mhandler.obtainMessage();
msg.what = DATA;
msg.obj = s;
mhandler.sendMessage(msg);
}
}catch (IOException e){
setState(READ_FAILED);
Log.d("TAG", e.toString());
break;
}
}
if(socket!= null){
try{
socket.close();
}catch (IOException e){
Log.d("TAG", e.toString());
}
}
}
}
private final Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
Bundle bundle = new Bundle();
bundle = msg.getData();
String str = bundle.getString("string");
textView.setText(str);
switch (msg.what){
case BlueToothTool.CONNECT_FAILED:
Toast.makeText(MainActivity.this,"连接失败",Toast.LENGTH_SHORT).show();
break;
case BlueToothTool.CONNECT_SUCCESS:
Toast.makeText(MainActivity.this,"连接成功",Toast.LENGTH_SHORT).show();
listView.setVisibility(View.GONE); //连接成功后移除listview 设置其他布局可见
status.setText("已连接");
address.setText(client.getAddress());
relativeLayout.setVisibility(View.VISIBLE);
break;
case BlueToothTool.READ_FAILED:
Toast.makeText(MainActivity.this,"读取失败",Toast.LENGTH_SHORT).show();
break;
case BlueToothTool.WRITE_FAILED:
Toast.makeText(MainActivity.this,"发送失败",Toast.LENGTH_SHORT).show();
break;
case BlueToothTool.PIPEI_SUCCESS:
Toast.makeText(MainActivity.this,"正在连接",Toast.LENGTH_SHORT).show();
break;
case BlueToothTool.PIPEI_FAILED:
Toast.makeText(MainActivity.this,"连接失败",Toast.LENGTH_SHORT).show();
break;
case BlueToothTool.DATA:
Toast.makeText(MainActivity.this,"接收成功",Toast.LENGTH_SHORT).show();
break;
}
}
};