我使用 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 按鈕來終止 connection 的連接。
如何在 setOnClickListener 方法中設置呢?
使用urlConnection的disconnect方法,如果想在外部做disconnect操作,就把urlConnection放在外部初始化完傳進來,但是要注意對應關系。