Socket.isconnected() Make My Android App Force Close
I don't know what happen with my source code about Socket in Android, when I use method .isConnected() My app always force close. And here my source code public class MyActivit
Solution 1:
Change the doInBackground
method as follows...
@OverrideprotectedBooleandoInBackground(Void... params) {
boolean success = true;
try {
socket = newSocket();
socket.connect(newInetSocketAddress(ip, port));
} catch (Exception e) {
success = false;
Log.e("MyActivity", e.getMessage());
}
return success;
}
Then add an onPostExecute
method...
@OverrideprotectedvoidonPostExecute(boolean result) {
if(result) {
text.setText("Connected!");
startActivity(newIntent(MyActivity.this, ListViewText.class));
}
else {
text.setText("Failed to connect!");
}
}
Solution 2:
First thing you are calling UI operation outside of UI thread (that is why AsyncTask was created, to handle background job only in doInBackground
) So problem about displaying text un TextView is solved...
But more important thing:
Never open Socket in AsyncTask. On Android developer site you can find following:
If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent package such as Executor, ThreadPoolExecutor and FutureTask.)
And that is exactly what you want to do. So use Service, Thread or those mentioned above instead.
Post a Comment for "Socket.isconnected() Make My Android App Force Close"