我使用 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 方法中设置?