问题描述
- android 中 AsyncTask的使用
-
我使用AsnycTask 来连接URL ,解析和返回 xml:class Connecting extends AsyncTask<String, String, String> { private String URLPath = ""; private HttpURLConnection Connection; private InputStream InputStream; private boolean Return1 = false; private int Return2 = -1; public Connecting (String fn, String u) { FileName = fn; URLPath = u; Connection = null; InputStream = null; Return1 = false; Return2 = -1; execute(); } public boolean getReturn1() { return Return1; } public int getReturn2() { return Return2; } @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected String doInBackground(String... aurl) { try { URL url = new URL(URLPath); Connection = (HttpURLConnection)url.openConnection(); Connection.setConnectTimeout(10000); Connection.setReadTimeout(10000); Connection.setDoInput(true); Connection.setUseCaches(false); Connection.connect(); InputStream = Connection.getInputStream(); } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String unused) { super.onPostExecute(unused); try { InputStreamReader fsr = new InputStreamReader(InputStream); BufferedReader br = new BufferedReader(fsr); String line = ""; while((line = br.readLine()) != null) { //parse Reture1 and Return2 } } catch(Exception e) { e.printStackTrace(); } Connection = null; } }
我使用下面的代码来调用:
Connecting con = new Connecting(Name, URL); System.out.println("Return1 " + con.getReturn1()); System.out.println("Return2 " + con.getReturn2());
返回 false 和 int 值 -1。
打印消息后连接 URL。
我想获取 value 值,这个值是连接成功的,并且时从 xml 中解析的,如何实现?
解决方案
可以写构造方法也可以不写构造方法,不写如下,外部调用new Connecting().execute(String fileName,String urlPath );
class Connecting extends AsyncTask<String, Integer, Integer> {
@Override
protected void onPreExecute() {
super.onPreExecute();
//do something before parse XML
}
@Override
protected Integer doInBackground(String... params) {
String fileName = params[0];
String urlPath = params[1];
//parse XML
return -1;
}
@Override
protected void onPostExecute(Integer result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// result即返回值
}
}
有构造方法的只需在里面加入
private String fileName;
private String urlPath;
public Connecting(String fileName,String urlPath) {
this.fileName = fileName;
this.urlPath = urlPath;
}
时间: 2024-10-03 00:48:30