当前位置: 代码迷 >> Android >> AsyncTask用法
  详细解决方案

AsyncTask用法

热度:82   发布时间:2016-05-01 15:10:34.0
AsyncTask用法求助
在使用AsyncTask进行搜索的时候,假设由于网络等问题需要搜索很长时间,甚至查不到结果。我现在想做的是规定一个查询时间,例如5秒钟,当这个查询操作超过5秒钟就强行终止AsyncTask方法,并提示用户查询超时,请问这个要怎么实现?

非常感谢 !!!!



------解决方案--------------------
给你一个思路把

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...那个方法里面的.
------解决方案--------------------
建议你使用网络请求控件超时设置来处理吧
比如HttpURLConnection有setReadTimeOut和setCommandTimeOut;

dConn.setReadTimeout(0);
dConn.setConnectTimeout(0);

如果必须要用自己程序来控制,我写了一个简单的代码,你可以试试先

Java code
    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;        }            }