在使用AsyncTask进行搜索的时候,假设由于网络等问题需要搜索很长时间,甚至查不到结果。我现在想做的是规定一个查询时间,例如5秒钟,当这个查询操作超过5秒钟就强行终止AsyncTask方法,并提示用户查询超时,请问这个要怎么实现?非常感谢 !!!!
解决方案 »
- android xmpp推送,与系统版本的问题
- 急需大家的建议~
- eclipse里如何在OnCreate函数上打断点?
- eclipse 将一个类从一个包拖到另一包,package包名自动更改,该如何设置?
- 谁做过使用nand的android系统的 recovery模式?
- 再论如何从apk文件获取图标文件
- fragment transaction.replace掉之后,原来的fragment为啥还能获取焦点
- ViewPager里启动Activity
- 求助,关于 RecyclerView 的坑
- 用android studio3.2建个helloworld一直错误
- 分享两道经典的面试题,同时求答案。。
- android调用百度地图的问题,如何在第一次显示当前位置
boolean isComplite=false;
new Thread(new Runnable()
{
public void run()
{
在这里调用你搜索的方法,搜索完后
isComplite=true;
}
}).start();while(true)
{ count++; if(isComplite||count==5)
{
break;
}
Thread.sleep(1000);
}if(count==5)
{
//超过时间了
}else if(isCiomplite)
{
//扫描完成
}
大概思路是这样的,具体细节 自己实现.这个写在do...那个方法里面的.
比如HttpURLConnection有setReadTimeOut和setCommandTimeOut; dConn.setReadTimeout(0);
dConn.setConnectTimeout(0);如果必须要用自己程序来控制,我写了一个简单的代码,你可以试试先 Handler handler = new Handler();
Runnable runMonitor = new Runnable() {
public void run() {
mytask.cancel(true);
}
};
public void threadTest(View view){
mytask = new MyTask();
String[] s = null;
mytask.execute(s);
handler.postDelayed(runMonitor, 5 * 1000);
}
public class MyTask extends AsyncTask<String[], Integer, Long>{ @Override
protected void onCancelled() {
TextView tv = (TextView)findViewById(R.id.TextView1);
tv.setText("取消!");
super.onCancelled();
} @Override
protected void onCancelled(Long result) {
TextView tv = (TextView)findViewById(R.id.TextView1);
tv.setText("取消!");
super.onCancelled(result);
} @Override
protected void onPostExecute(Long result) {
TextView tv = (TextView)findViewById(R.id.TextView1);
tv.setText("完成!");
super.onPostExecute(result);
} @Override
protected void onPreExecute() {
TextView tv = (TextView)findViewById(R.id.TextView1);
tv.setText("开始!");
super.onPreExecute();
}
@Override
protected Long doInBackground(String[]... params) { return null;
}
}