我在扩展AsyncTask类的对象的doInBackground()方法中打开一个套接字。我在使用后立即关闭此插座。但是,当我使用模拟器上的后退按钮,然后从菜单启动我的应用程序或当我从eclipse启动它而不更改代码时,我得到BindException(即使我在5分钟后执行此操作,为TIME_WAIT提供足够的时间state或2MSL等待状态)。
但是如果我在eclipse中编辑我的代码(比如添加2个随机字符并删除em并保存)并运行我的应用程序,我就不会得到这个例外。要在同一端口上接受多个连接,必须做些什么?我已经尝试过setReuseAddress(true),但这似乎也没有用。
我实现了我的活动的onResume()方法,只需在其中调用super.onResume()。可以使用这种方法导致解决方案,或者究竟要做什么?我对任何想法持开放态度。
有什么建议吗? @Edit:
class LongOperation extends AsyncTask<String, Void, String> {
private String fname;
String aa="";
@Override
protected void onPostExecute(String result) {
ed.setText(result);
}
@Override
protected void onPreExecute() {
}
@Override
protected void onProgressUpdate(Void... values) {
}
@Override
protected String doInBackground(String... arg0) {
ServerSocket ss;
try
{
ss = new ServerSocket(8000);
s=ss.accept();
s.setReuseAddress(true);
BufferedReader get = new BufferedReader(new InputStreamReader(s.getInputStream()));
aa=get.readLine();
s.close();
}
catch(IOException e)
{
//System.out.println(e.toString());
aa=""+e;
}
return aa;
}
}
当我再次运行我的应用程序时,我可以看到我的TextView中的异常说“BindException:Address has in use”。但显然我已经关闭了我的插座。
活动代码:
public class ContactReceiver extends Activity {
TextView ed;Socket s;
public void onCreate(Bundle b){
super.onCreate(b);
setContentView(R.layout.receiver);
ed=(TextView)findViewById(R.id.textView1);
new LongOperation().execute("");
}
public void onPause(){
super.onPause();
}
public void onResume(){
super.onResume();
// new LongOperation().execute("");
}
活动类未关闭。我把我的AsyncTask类作为一个子类旅馆