【问题标题】:Bitmap operations in background thread makes UI unresponsive后台线程中的位图操作使 UI 无响应
【发布时间】:2018-06-12 04:35:56
【问题描述】:

我正在后台线程中运行以下操作:

  1. 在本地将字节图像数据存储为 jpeg。
  2. 将该图像作为位图获取。
  3. 运行人脸检测算法并获取人脸点
  4. 根据这些点放置叠加层
  5. 最后再次保存该位图。

在执行这些操作时,我正在显示一个进度条。但是进度条动画卡住了,即在线程完成其工作之前它变得无响应(更新:在后台工作运行时,整个 UI 中似乎没有任何功能)。

这不会使使用后台线程的实际意图过时吗?

我应该采取什么方法来克服这个问题?

我的代码是:

  //Show ProgressBar
  Runnable worker = () -> {

      //My Operations

     runOnUiThread(() -> {

             //Hide ProgressBar

          });
    }

【问题讨论】:

  • 你能贴出你的代码吗
  • 后台进程使用 RxJava。
  • @Jaymin 在所有 Rxjava 也使用线程之后会有什么不同
  • 进度条是从哪里开始的?
  • 你能保证你没有在主 UI 线程中运行后台线程吗?

标签: android performance android-layout android-studio android-progressbar


【解决方案1】:

你可以使用异步方法,它会工作

 private class MyAsyncTask extends AsyncTask<String, Progress, Bitmap> {
 protected void onPreExecute() {
     // Runs on the UI thread before doInBackground

     progressBar.setVisibility(ProgressBar.VISIBLE);
 }

 protected Bitmap doInBackground(String... strings) {
     // Some long-running task like downloading an image.
     // convert your bitmap
     return someBitmap;
 }

 protected void onProgressUpdate(Progress... values) {
  //update progress
 }  

 protected void onPostExecute(Bitmap result) {
     //hide progress bar
 }}

【讨论】:

  • 我以前就是这样做的。但我发现 asyncTask 比普通线程慢。因为普通线程的线程优先级高于异步任务
猜你喜欢
  • 2015-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-18
  • 2022-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多