Android Thread中读取到的数据,赋值给一个全局变量,再使用全局变量的时候,第一次为空,怎么保证有数据 10
publicclassMainActivity2extendsAppCompatActivityimplementsView.OnClickListener{privat...
public class MainActivity2 extends AppCompatActivity implements View.OnClickListener{ private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case msgKey: tvReceiveData.append(mSb.toString()); tvReceiveData.append("\n"); } } }; private class ReadThread extends Thread { @Override public void run() { // TODO Auto-generated method stub super.run(); while (!isInterrupted()) { int size; try { byte[] buffer = new byte[20]; Log.e(TAG, "----ReadThread start----"); if (mInputStream == null) { Log.e(TAG, "----mInputStream=null----"); return; } Log.e(TAG, "----read(buffer)----"); size = mInputStream.read(buffer); Log.e(TAG, "----size----" + String.valueOf(size)); if (size > 0) { mSb = new StringBuffer(); mSb.append(MyFunc.ByteArrToHex(buffer)); Log.e(TAG, "readresult=" + mSb.toString()); result=mSb.toString(); msg = new Message(); msg.what = msgKey; mHandler.sendMessage(msg); } } catch (IOException e) { Log.e(TAG, "----ReadThread printStackTrace----"); e.printStackTrace(); return; } } } } @Override public void onClick(View view) { switch (view.getId()){ case R.id.btn_open: try { mSerialPort = new SerialPort(new File(etComNumber.getText().toString().trim()), 9600,0); mOutputStream = mSerialPort.getOutputStream(); //写 mInputStream = mSerialPort.getInputStream();//读 mThread = new ReadThread(); mThread.start(); tvReceiveData.append("打开串口"+"\n"); } catch (IOException e) { e.printStackTrace(); } break; private String GetSerialNumber(){ String TX1="0101000000000000000000000000000000007188"; etCommand.setText(TX1); senddata(TX1); if (result!=null){ return result; }else { return "---"; } } }
展开
2个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询