虽然我使用 AsyncTask 应用程序没有响应

Although I use AsyncTask the App doesn't respond

我编写了一个需要大量性能的算法。 我认为这也是为什么我的 android 应用程序在有太多对象要处理时显示 'app not responding' 对话框的原因。由于要处理的对象较少,算法工作得很好。 所以我开始实现 ASyncTask(以前从未这样做过),它应该调用函数以从 doInBackground() 开始算法。 (启动算法的函数是 fillFilteredGraphics(int position)

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

    ProgressDialog progressDialog;

    @SuppressLint("WrongThread")
    @Override
    protected Void doInBackground(Void... voids) {
        //This is the important call
        mGraphicOverlay.fillFilteredGraphics(0);

        return null;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = ProgressDialog.show(RecognizerActivity.this,
                "ProgressDialog",
                "Processing results...");
    }



    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        progressDialog.dismiss();
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
    }
}

并在 onCreate() 中:

AsyncTaskRunner runner = new AsyncTaskRunner();
runner.execute();

但它仍然显示“应用程序没有响应”对话框

对象mGraphicsOverlay定义在onCreate():
GraphicOverlay mGraphicOverlay = findViewById(R.id.graphic_overlay);

如您所见,自定义 class GraphicOverlay extends View

public class GraphicOverlay extends View {

     public GraphicOverlay(Context c, AttributeSet attrs){
          super(c, attrs);
     }

     @Override
     protected void onDraw(Canvas canvas){
          super.onDraw(canvas);
          //do stuff
     }

     public void fillFilteredGraphics(int position){
          //start algorithm
     }
} 

还有一条错误消息,上面写着

Method fillFilteredgraphics mut be called from the UI thread, currently inferred thread is worker thread

所以我在 doInBackground() 函数之上添加了 @SuppressLint("WrongThread")

但是也没用。 那么在处理许多对象时,我该怎么做才能没有 'app not responding' 对话框。

@SuppressLint() 只是删除警告。问题是您正在从工作线程调用 UI 对象视图更新,但您必须仅从主线程调用任何 UI 对象。

所以在你的情况下,找到你用来在 GraphicOverlay class 中更新它们的任何 UI 对象关系,并且如果可能的话也划分你的后台线程。