android.os.NetworkOnMainThreadException -> execution error
correct source(after)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
package oh.my.girl; import java.io.IOException; import java.io.ObjectOutputStream; import java.net.Socket; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.text.Editable; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; public class NetworkActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.control); ConnectThread(); } void ConnectThread() { new ConnectTask().execute(null,null,null); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
package oh.my.girl; import java.io.IOException; import android.os.AsyncTask; public class ConnectTask extends AsyncTask<Void, Void, Void> { String ip = "192.168.0.2"; int port = 8080; @Override protected Void doInBackground(Void... arg0) { // TODO Auto-generated method stub try { SocketClient sc = new SocketClient(ip, port); sc.createClientSocket(); } catch (IOException e) { } return null; } } |
wrong source (before)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public class NetworkActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.control); try { SocketClient sc = new SocketClient(ip, port); sc.createClientSocket(); } catch (IOException e) { } } } |
impossible to connet network in main UI thread after Android 3.0 version
so you must create other thread
cite from -> http://ironheel.tistory.com/48
사실 위 코드에는 문제가 전혀 없다.
문제는 android가 변했다는 점이다.
결론부터 말하자면 honeycomb에서는 main thread(UI)에서 네트워크 호출을 하면 무조건 error로 간주한다.
앱 전체의 thread와 컨트롤을 관리하는 main에서 네트워크 호출로 대기중인 시간이 길어지면
사용자는 안드로이드앱의 문제로 인식하게 된다. 이를 방지하자는 것이 목적이다.
다음 링크를 참조하자 : painless threading 번역글