在使用AsyncTask进行搜索的时候,假设由于网络等问题需要搜索很长时间,甚至查不到结果。我现在想做的是规定一个查询时间,例如5秒钟,当这个查询操作超过5秒钟就强行终止AsyncTask方法,并提示用户查询超时,请问这个要怎么实现?非常感谢 !!!!

解决方案 »

  1.   

    给你一个思路把int count=0;
    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...那个方法里面的.
      

  2.   

    建议你使用网络请求控件超时设置来处理吧
    比如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;
    }

    }
      

  3.   

    网络请求不是要通过HttpClient或者HttpUrlConnection类么http协议有响应超时的方法,直接调用就行了,没必要非在AsyncTask类上做文章
      

  4.   

    这个方法我在android2.2上用了,是可以的。但是在android4.0平台上就会报错,请问这是怎么回事,要怎么处理呢? 非常感谢