【发布时间】:2015-04-08 09:09:27
【问题描述】:
我需要通过 Toast 显示“请稍等...”消息,同时应用程序尝试从 Internet 获取一些数据,这可能需要几秒钟的时间,具体取决于 Internet 连接和服务器上的负载。 http 连接是通过 AsyncTask 建立的。
我正在做的是我通过“Toast.makeText”方法显示消息,然后我进入一个“while”循环,当 AsyncTask 的执行方法完成时中断,然后我在 Activity 上显示一些结果。
问题是 Toast 直到 while 循环中断才出现! 我试图用 setText 在 TextView 中显示消息来替换 Toast ,但同样的事情发生了,在 while 循环中断后显示的消息! 有什么想法吗?我的代码如下所示:
waitToast = Toast.makeText(this,R.string.WaitText, Toast.LENGTH_SHORT);
waitToast.show();
.........
.........
new DownloadFilesTask().execute();
dataRetrieved = false;
while (!dataRetrieved){ }
........
在doInBackground中:
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
InputStream in = null;
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(4000);
in = urlConnection.getInputStream();
in = new BufferedInputStream(urlConnection.getInputStream());
url_input = readStream(in);
........
catch (Exception e) {
e.printStackTrace();
}
finally{
dataRetrieved = true;
urlConnection.disconnect();
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
【问题讨论】:
-
在
onPreExecute()方法中调用。 -
你必须在ui线程中完成操作。在 ui 线程中等待 asyntask 结束是不好的做法。你不会以这种方式获得 asyntask 的任何优势
标签: android android-toast