我有两个简单的类:
public class MainActivity extends Activity {
NetworkTask task;
@Override
protected void onCreate(Bundle savedInstanceState) {
[...]
task = new NetworkTask();
task.execute();
}
public void myClickHandler(View view) {
switch(view.getId()) {
case R.id.button1:
// Why this line crash?
task.connection("127.0.0.1");
break;
}
}
}
和
public class NetworkTask extends AsyncTask<String, Void, String> {
Socket sock;
volatile boolean running = true;
public int connection(String url){
try{
sock = new Socket(url, 4567)
}
catch (IOException ex){
Logger.getLogger(NetworkTask.class.getName()).log(Level.SEVERE, null, ex);
return -1;
}
}
public String doInBackground(String... strings) {
// If I do this, it works well
//connection(127.0.0.1);
while(running)
{
[...]
}
return null;
}
}
正如我在从 AsyncTask 方法外部调用连接方法时评论的那样,应用程序崩溃更特别 « sock = new Socket(...) » 行。但是当在 AsynTask 方法内完成连接调用时,会创建套接字。我不明白为什么。
发生了什么?
谢谢。