我使用AsyncTask连接URLPath,如下面的代码。
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.left_list);
Button btn = (Button)findViewById(resid);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//how to stop connect
}
});
new Connecting().execute();
}
class Connecting extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
//do something
}
@Override
protected String doInBackground(String... aurl) {
try {
URL url = new URL(URLPath);
connection = (HttpURLConnection)url.openConnection();
connection.setConnectTimeout(30000);
connection.setReadTimeout(30000);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.connect();
is = connection.getInputStream();
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String unused) {
super.onPostExecute(unused);
//access InputStream is
}
}
连接可能会花费很多时间进行连接 当它连接时,我想设置Bbutton btn被按下以停止连接连接 如何在setOnClickListener方法中设置?
答案 0 :(得分:20)
在HttpURLConnection
内包含使用Future
的代码,您可以随意取消。您还可以使用Future
的超时功能,因为HttpURLConnection
中的超时不可靠。
在网络课程中定义执行者和未来:
final ExecutorService executor = Executors.newCachedThreadPool(Executors.defaultThreadFactory());
Future<MyResult> future;
然后将您的网络代码包装在Future
中,如下所示:
future = executor.submit(new Callable<MyResult>() {
@Override
public MyResult call() throws IOException {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
try {
// .. use the connection ...
} finally {
connection.disconnect();
}
}
});
MyResult result = future.get(TIMEOUT, TimeUnit.SECONDS);
如果要取消,可以从任何线程进行此调用:
future.cancel(true);
如果将来超时或取消,连接任务可能会继续阻止HttpURLConnection
方法,但您的应用程序不会被阻止。您仍应在连接上设置适当的超时,以加快线程和网络套接字的释放。
答案 1 :(得分:0)
通过(HttpURLConnection)url.openConnection()保存HttpURLConnection响应;作为班级成员: HttpURLConnection mHttpURLConnection =(HttpURLConnection)url.openConnection();
在您调用future.cancel(true);之后;然后打电话 mHttpURLConnection.disconnect()
因此网络请求将尽快结束