APP线程连接问题

2020-01-23 19:44栏目:竞技宝app
TAG:

竞技宝app,我自己做了一个手机APP,主要是连接一个物联网模块,但是app一直显示通讯失败,所以把代码贴出来希望大家帮帮小白,可能是线程某个地方的问题。

packagecom.example.afan.one;importandroid.support.v7.app.AppCompatActivity;importandroid.os.Bundle;importandroid.view.View;importandroid.widget.Button;importandroid.widget.EditText;importandroid.widget.Toast;importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.io.PrintStream;importjava.net.Socket;publicclassMainActivityextendsAppCompatActivityimplementsView.OnClickListener{privateEditTextmIp;//IPprivateEditTextmPort;//端口号privateStringmStrIp;//字符串类型ipprivateintmiPort;//字符类型端口privateButtonmBtnConnect;//连接privateButtonmLedON;//按钮LED灯开privateButtonmLedOFF;//按钮LED灯关privateSocketmSocket;//套接字privatePrintStreamout;//打印输出流privateConnectThreadmConnectThread;//TCP连接线protectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mBtnConnect=(Button)findViewById(R.id.bt1);mLedON=(Button)findViewById(R.id.bt2);mLedOFF=(Button)findViewById(R.id.bt3);mIp=(EditText)findViewById(R.id.edit_IP);mPort=(EditText)findViewById(R.id.edit_PORT);mBtnConnect.setOnClickListener(this);mLedON.setOnClickListener(this);mLedOFF.setOnClickListener(this);}@OverridepublicvoidonClick(Viewview){switch(view.getId()){caseR.id.bt1:if(mSocket==null||!mSocket.isConnected()){mStrIp=mIp.getText().toString();miPort=Integer.valueOf(mPort.getText().toString());mConnectThread=newConnectThread(mStrIp,miPort);mConnectThread.start();}if(mSocket!=nullmSocket.isConnected()){try{mSocket.close();mSocket=null;//清空mSocketmBtnConnect.setText("连接");Toast.makeText(MainActivity.this,"连接已关闭",Toast.LENGTH_LONG).show();}catch(IOExceptione){e.printStackTrace();}}break;caseR.id.bt2:if(out!=null){out.print("0");out.flush();}break;caseR.id.bt3:if(out!=null){out.print("1");out.flush();}break;}}privateclassConnectThreadextendsThread{privateStringip;privateintport;publicConnectThread(Stringip,intport){this.ip=ip;this.port=port;}publicvoidrun(){try{mSocket=newSocket(ip,port);out=newPrintStream(mSocket.getOutputStream());runOnUiThread(newRunnable(){@Overridepublicvoidrun(){mBtnConnect.setText("断开");Toast.makeText(MainActivity.this,"连接成功",Toast.LENGTH_LONG).show();}});newHeartBeatThread().start();}catch(IOExceptione){e.printStackTrace();runOnUiThread(newRunnable(){@Overridepublicvoidrun(){Toast.makeText(MainActivity.this,"连接失败",Toast.LENGTH_LONG).show();}});}}}privateclassHeartBeatThreadextendsThread{@Overridepublicvoidrun(){while(true){try{Thread.sleep(3000);if(!mSocket.isConnected()){runOnUiThread(newRunnable(){@Overridepublicvoidrun(){mBtnConnect.setText("连接");Toast.makeText(MainActivity.this,"连接已关闭",Toast.LENGTH_SHORT).show();}});}}catch(InterruptedExceptione){e.printStackTrace();}}}}}

版权声明:本文由龙竞技官网发布于竞技宝app,转载请注明出处:APP线程连接问题