Thursday, February 20, 2014
android4.0 sub-thread socket problem
android4.0 after the main UI thread can not be used in socket, the use of socket is a problem in the sub-thread. You can establish a connection, while (true) the contents are not implemented, do not know why ah
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_main);
Intent intent = new Intent ();
intent.setClass (MainActivity.this, UsbDongleService.class);
bindService (intent, connection, Context.BIND_AUTO_CREATE);
edt = (EditText) findViewById (R.id.editText1);
Thread th = new Thread (new Runnable () {
@ Override
public void run () {
/ / TODO Auto-generated method stub
try {
socket = new Socket ("192.168.1.55", 4800);
in = new BufferedReader (new InputStreamReader (socket.getInputStream ()));
out = new PrintWriter (new BufferedWriter (new OutputStreamWriter (socket.getOutputStream ())), true);
} Catch (UnknownHostException e1) {
/ / TODO Auto-generated catch block
e1.printStackTrace ();
} Catch (IOException e1) {
/ / TODO Auto-generated catch block
e1.printStackTrace ();
}
while (true) {
Log.d ("socket", "1");
/ / Out.print (tv.getText ());
if (socket.isConnected ()) {
if (! socket.isInputShutdown ()) {
try {
if ((recMSG = in.readLine ())! = null) {
/ / Edt.setText ("\ n");
Log.d ("socket", in.readLine ());
socketHandler.sendMessage (socketHandler.obtainMessage ());
}
} Catch (IOException e) {
/ / TODO Auto-generated catch block
e.printStackTrace ();
if (servicedata) {
Log.d ("socket", "output");
servicedata = false;
out.println (tv.getText ());
}
}
}
}
}
}
});
th.start ();
}<-! Main posts under Banner (D4) -><-! Posts under the main text (D5) ->
Reply:
Did not see what the problem. . .
socketHandler.sendMessage (socketHandler.obtainMessage ());
obtainMessage To parameters?
Reply:
if ((recMSG = in.readLine ())! = null) {
}
Is not this place does not move? If the server does not send the data would not move.
Or you need to send data to the server.
Reply:
Yes, stop here, but the here readLine () after this one commented, app would force close together, causing the error should be
out.println (tv.getText ()); This one, this one does not know why the wrong
Reply:
The problem is resolved, it should be tv.getText () problem here
Reply:
Sub-thread want to update UI, you can use handler to do.
Reply:
Yes, it is doing
Reply:
Asynchronous can also update the UI
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment