【问题标题】:Toast message is not displayed at the right time?Toast 消息没有在正确的时间显示?
【发布时间】: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


【解决方案1】:

不要这样做。您正在使用 while 循环阻塞 ui 线程。这就是为什么您的 Toast 不显示的原因。

删除您的 while 并覆盖 AsyncTask 中的 onPostExecute()。此方法在 Ui 线程上运行,与 doInbackground 不同,因此您可以更新 Activity UI。

【讨论】:

    【解决方案2】:

    在异步任务中使用这个方法:

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Show Toast
        Toast.makeText(context,"text",Toast.LENGTH_LONG).show();
    }
    

    记住“onPostExecute”和“onPreExecute”可以改变UI,不要在“doInBackground”改变UI。

    【讨论】:

    • 好的,非常感谢大家,我知道了。 onPostExecute 和 onPreExecute 适用于 UI。我不知道。
    猜你喜欢
    • 1970-01-01
    • 2016-11-20
    • 2015-02-12
    • 1970-01-01
    • 2011-12-09
    • 2014-07-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多