AsyncTask的块团结(UI)线程问题 [英] AsyncTask block Unity(UI) thread issue
问题描述
下面是我的主要活动的OnCreate
:
mUnityPlayer = new UnityPlayer(this);
setContentView(mUnityPlayer);
mUnityPlayer.requestFocus();
new SimuDownloadTask(this).execute();
以下code是源$ C $ C SimuDownloadTask
:
public class SimuDownloadTask extends AsyncTask<Void, Integer, Boolean> {
private ProgressDialog progressDialog;
private int count=0;
private Context mainActivityContext;
public SimuDownloadTask(Context context) {
mainActivityContext=context;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog=new ProgressDialog(mainActivityContext,R.style.XMNewDialog);
progressDialog.show();
}
@Override
protected Boolean doInBackground(Void... arg0) {
while(true)
{
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int downloadPercent=doDownload();
publishProgress(downloadPercent);
if(downloadPercent>=500)
break;
}
return true;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressDialog.setMessage("current progress:"+values[0]+"%");
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
progressDialog.dismiss();
if(result)
{
Toast.makeText(mainActivityContext, "success", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(mainActivityContext, "fail", Toast.LENGTH_SHORT).show();
}
}
private int doDownload()
{
count+=1;
return count;
}
}
下面是问题所在。当我启动应用程序,进度条块UI线程。
进度条完成后,统一启动。
Here is the problem. When I start the app, the progressbar blocks the UI thread. After the progressbar finished, the Unity starts.
当我用下面的code替换 SimuDownloadTask
在OnCreate中:
When I replace the SimuDownloadTask
in OnCreate with the following code:
new Thread(){
@Override
public void run() {
super.run();
Looper.prepare();
progressDialog=new ProgressDialog(UnityPlayerActivity.this,R.style.XMNewDialog);
progressDialog.setTitle("test");
progressDialog.setCancelable(true);
progressDialog.show();
Looper.loop();
}
}.start();
团结线程正在正常运行(不会阻止进度)。所以我觉得这个问题是不相关的统一。
The unity thread is running properly(not blocked by the progressbar). So I think the problem is not relevant to Unity.
我已经查了相关链接,如:
非UI线程的AsyncTask
但仍不能找出问题。
任何线索将是有益的。
I have already checked the relevant links such as: Asynctask from non ui thread But still can't figure out the issues. Any clues will be helpful.
推荐答案
而不是使用的AsyncTask您可以使用一个工作线程计数器逻辑和处理程序来更新进度条。
请参阅本更新的答案<一个href=\"http://stackoverflow.com/questions/25094330/example-communicating-with-handlerthread\">link
Instead of using an AsyncTask you may use a worker thread for the counter logic and a handler to update the progress bar. See the updated answer in this link
这篇关于AsyncTask的块团结(UI)线程问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!