android - 使用 AsyncTask 类的简单计数器

标签 android android-studio android-asynctask

这是一个使用 AsyncTask 类的简单计数器:

   static private class AsyncTaskRunner extends AsyncTask<Integer, Integer, Integer> {

    @Override
    protected Integer doInBackground(Integer...prams) {
       while(t){
           i++;
           publishProgress(i);
           try {
               Thread.sleep(200);
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
       }

        return null;
    }


    @Override
    protected void onPostExecute(Integer result) {

    }


    @Override
    protected void onPreExecute() {

    }


    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        Textview.setText(String.valueOf(values[0]));  
    }
}

i 是一个整数女巫,每 0.2 秒上升一次,它的值显示在 Textview 中。因此,当我运行我的应用程序时,i 的值显示在 textview 中,并使用 asynctask 类快速增加和更新。 这是我的问题: 为什么有时我的 TextView 显示较小的 i 值,例如在 54 之后它显示 53 然后再次上升!

最佳答案

onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.

无法保证 UI 线程上的更新时间,因此您可能会看到事件按照您描述的顺序出现。您可能希望为您的进度添加逻辑,以根本不减少该值而只增加该值,如果该值小于您上次看到的值,则基本上跳过该值。

关于android - 使用 AsyncTask 类的简单计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51886046/

相关文章:

安装时出现 Android Studio 问题

android - 获取 java.lang.IllegalStateException : attempt to re-open an already-closed object: when using cursor in Android

Java:尝试 block 在结束之前停止,没有任何异常

android - 如何在android中调试plus client(google+) "internal error"toast?

android - 在 XMPP 中获取离线消息

android - 通过移动数据的 Firebase 匿名身份验证失败

android - 如何关闭 ASyncTask 的 Activity ?

java - 项目未在项目中使用 Kotlin 进行编译

java - 如何在 Android 中获取表格布局的内容

日志猫中的Android Studio "Clear All",更改日志级别过滤器时日志仍然返回