【问题标题】:How to force progressbar get visible before a background thread starts its execution如何在后台线程开始执行之前强制进度条可见
【发布时间】:2023-02-09 10:33:51
【问题描述】:

我认为对于这个社区中的许多人来说,这是一个非常简单的问题,但是,经过几次实验,我无法使它起作用;我将不胜感激任何帮助。

JAVA-android平台:当用户点击按钮时,代码需要执行以下步骤:

  1. 使按钮不可见(在主线程中运行)

  2. 使进度条可见(在主线程中运行)

  3. 从 Internet 下载文件(在后台线程中运行)

  4. 等待下载完成

  5. 使进度条不可见

  6. 使按钮再次可见

    就是这样。这似乎不是很困难,但是,它没有按我的需要工作。

    这是问题所在: 第 3 步在第 1 步和第 2 步之前执行,......我已经尝试了几个实验但没有成功。

    private void f1()
    {
        mDataBinding.btnPausePlay.setVisibility(btnVisibility);                    
        mDataBinding.progressPausePlay.setVisibility(progressVisibility);
    }
    
    private void f2()
    {
            Thread xThread = new Thread( new Runnable()
            {   @Override
                public void run()                            // run in background thread
                { httpRequest_noBackgroundThread( urlStr, urlParams, fileStr, itf );  }
            });
            try
            {
                xThread.start();
                xThread.join();     // wait for the thread to finish
            }
               catch( Exception e ){   e.printStackTrace();  }
    }
    
    
    private void f3()
    {
            f1();
            f2();
           // continues execution ...
    }
    

【问题讨论】:

    标签: java android multithreading concurrency


    【解决方案1】:

    为此,您必须在 Java 中使用 Executors。下面的代码将为您完成这项工作-

    btnPausePlay.setOnClickListener(view -> {
            btnPausePlay.setVisibility(View.GONE);
            progressPausePlay.setVisibility(View.VISIBLE);
            ExecutorService executorService =  Executors.newSingleThreadExecutor();
            executorService.execute(() -> {
                // Implement your file download code here i.e.
                // httpRequest_noBackgroundThread( urlStr, urlParams, fileStr, itf );
            handler.post(() -> {
                btnPausePlay.setVisibility(View.VISIBLE);
                progressPausePlay.setVisibility(View.GONE);
            });
        });
    });
    

    当您按下 btnPausePlay 按钮时,它将变得不可见,进度条变得可见。之后,一旦下载完成,反向就会发生。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-08
      相关资源
      最近更新 更多