gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 08:49:01 26 4
gpt4 key购买 nike

我编写了一个算法,它需要大量的性能。我认为这也是当有太多对象需要处理时我的 Android 应用程序显示“应用程序未响应”对话框的原因。由于要处理的对象较少,该算法工作得非常好。所以我开始实现ASyncTask(以前从未这样做过),它应该调用函数从doInBackground()启动算法。 (启动算法的函数是fillFilteredGraphics(intposition))

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
}
}

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

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

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

但它也不起作用。那么,在处理许多对象时,我该怎么做才能不出现“应用程序未响应”对话框。

最佳答案

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

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

关于java - 虽然我使用 AsyncTask 但应用程序没有响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60906001/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com