【问题标题】:Although I use AsyncTask the App doesn't respond虽然我使用 AsyncTask 应用程序没有响应
【发布时间】:2020-03-28 19:35:49
【问题描述】:

我编写了一个算法,它需要很多性能。 我认为这也是我的 android 应用程序在有太多对象需要处理时显示“应用程序无响应”对话框的原因。由于要处理的对象更少,该算法工作得非常好。 所以我开始实现 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);

如您所见,自定义类 GraphicOverlay 扩展了 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
     }
} 

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

方法fillFilteredgraphics mut被UI线程调用,当前推断线程为工作线程

所以我在 doInBackground() 函数的顶部添加了@SuppressLint("WrongThread")

但它也不起作用。 那么,在处理许多对象时,我该怎么做才能获得“应用无响应”对话框。

【问题讨论】:

    标签: java android android-asynctask android-anr-dialog


    【解决方案1】:

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

    因此,在您的情况下,找到您用来在 GraphicOverlay 类中更新它们的任何 UI 对象关系,如果可能的话,也划分您的后台线程。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-17
      • 2017-04-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多