这是我关于堆栈溢出的第一个问题.通常我可以自己找到答案,但这次我找不到合适的答案.我也是为
Android制作应用程序的新手,所以提前抱歉我的noob’nes.
如果本地IP地址不可用,如何在x miliseconds后取消’android java’中的http请求?
我正在使用AsyncTask请求一个html页面.该类的代码如下.
我现在拥有的是onPreExecute()中定义的一个定时器,它在X毫秒之后将onCancel()设置为true.
doInBackground()打开一个流等,然后将流写入字符串.
问题是当本地ip地址不可用时,url.openStream()函数会一直运行,直到java.net.ConnectException因为timeOut而启动.我不知道如何使用onCancel()来中断此命令(如果这是可能的话).
那么如何中断url.openStream命令呢?或者只是终止AsyncTask线程?
private class htmlToString extends AsyncTask {
public htmlToString asyncObj;
@Override
protected void onPreExecute(){
asyncObj = this;
new CountDownTimer(connectionTimeout, connectionTimeout) {
public void onTick(long millisUntilFinished) {}
public void onFinish() {
// stop async task if not in progress
if (asyncObj.getStatus() == AsyncTask.Status.RUNNING) {
asyncObj.cancel(true); //
Log.i("timer", "...still trying to connect...");
}
}
}.start();
}
@Override
protected Void doInBackground(Void... params) {
try {
URL url = new URL(url_string[button_state]);
final InputStream url_inputstream = url.openStream(); //
InputStreamReader url_inputstreamreader = new InputStreamReader( url_inputstream );
BufferedReader in = new BufferedReader( url_inputstreamreader );
String inputLine;
while ((inputLine = in.readLine()) != null)
page = page.concat(inputLine);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void params){
// some code
}
}
Edit1:这是在Android Studio 1.5.1中完成的
编辑2:我自己解决了.我只是缩短了java设置的时间.我在doInBackground()中做了这个(代码如下).这也意味着我可以完全废弃onPreExecute()中的计时器.
@Override
protected Void doInBackground(Void... params) {
try {
URL url = new URL(url_string[button_state]);
URLConnection url_connection = url.openConnection();
url_connection.setConnectTimeout(connectionTimeout); // timout is set here
final InputStream url_inputstream = url_connection.getInputStream();
InputStreamReader url_inputstreamreader = new InputStreamReader( url_inputstream );
BufferedReader in = new BufferedReader( url_inputstreamreader );
String inputLine;
while ((inputLine = in.readLine()) != null)
page = page.concat(inputLine);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}