Monday 15 February 2010

java - How to use Asynctask establish socket connections? -


In the recent study using the acetcus to establish the socket connection, but faced some situation, now I can use a button to set up a connection, but I do not know the button text is "unconnected" How to "Connect" to There is no problem, but it can not be executed on the simulator, press the button, I "connected" to "unconnected", but the next second closed the AP.

The following is my The code is fragmented:

  The public class increases the MainActivity activity {Public Static Button Btn_wifi, BTN_ Power, BTN_flamm; Public Stable Boolean = Linked; Public Stable Data Output Stream Data Optical Stream = Faucet ; Public Static Data Input Stream Data InputStream = null; Public static socket socket;  

Async Task:

  Fixed square socket task async Expand Tasks & lt; Zero, Zero, Zero & gt; {@Override Safe Voice Doignbackground (Zero ... Pars) {Try {Socket = New Socket ("IP", Port); // DataOutputStream = New Dataoptputstream (socket.getoutputstream ()); // and stream variables ConnectionStatus (true); // Change the connection status} Catch (unknownHostException E) {} Catch (IOE EXPRESS E) {} Finally {try {socket.close ()}} Grip (IOException e) {e.printStackTrace ( ); } Hold (exception e) {e.printStackTrace (); }} Return tap; }};  

button. OnclickList:

  button. Onclick Lester BtnWifiOnClickListener = New button. OnClickListener () {@Override Public Zero Click on (View View) {// SocketTaskSockettask = New Socket Task (); New SocketTask () carry about (); }};  

changeConnectionStatus:

  public static zero conversion connection status (Boolean connected) {connected = isConnected; // change variable if (isConnected) {// if connection established BTN_weepy .set text ("connected"); Btn_Power.setEnabled (true); } Else {Btn_Wifi.setText ("unconnected"); Btn_Power.setText ("power off"); Btn_Power.setEnabled (false); PowerStatus (wrong); }}  

Positive Solutions

  @Override Secure Zero PostExecute (zero result) {changeConnectionStatus (true); }  

You can not touch UI from doInBackground ()

You need to use onPostExecute ()

changeConnectionStatus (true) to doInBackground () As the following:

  @Override Secure Zero at PostExecute () {changeConnectionStatus (true); }  

No comments:

Post a Comment