Start Async Task within a worker thread

ぐ巨炮叔叔 提交于 2020-01-09 11:00:16

问题


I have two questions:

  • Can we start/execute an Async Task within a worker thread?
  • If yes, the methods onPreExecute(), onProgressUpdate(Progress...) and onPostExecute(Result) are invoked on the UI thread?

I wanna know that because I have a TCP connection running on a worker thread and when a packet is received I wanna start a new thread to make the parse of this packet and after that refresh some data structures on the UI thread.

Thanks in advance!


回答1:


From the Android AsyncTask doc:

"The task instance must be created on the UI thread.", and

"execute(Params...) must be invoked on the UI thread."

So I think the answer to your first question is "no". As far as the second, those methods are all invoked on the UI thread, but it's a bit moot.

EDIT: I'm not sure if those are absolute restrictions, or strong suggestions, but in both cases, I'd recommend following them.




回答2:


Just for the Record: If you start a AsyncTask outside the UI-Thread the onPreExecute will not be executed from the UI-Thread (but from the caller Thread). This will lead to an exception. However the onPostExecute Method will always be executed on the UI-Thread. Hope to help someone :)




回答3:


According to Android doco you must run an AsyncTask from a UI thread, but in reality it depends on who runs this line in AsyncTask.class first:

private static final InternalHandler sHandler = new InternalHandler();

If you have an AsyncTask that is called on from both UI and worker thread, you might get around this restriction with calling it first from UI thread. If you hit it first from your worker thread you're doomed. I'd rather not rely on this as implementation details can change at any time, but this knowledge is useful if you, like me, wondered "why my other AsyncTask works".




回答4:


From the Android AsyncTask doc:

"The task instance must be created on the UI thread.", and

"execute(Params...) must be invoked on the UI thread."

So, the following is legal.

new Thread(new Runnable() {
                @Override
                public void run() {
                    // do some work here

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            new MyAsyncTask(ctx).execute(); 
                        }
                    });
                }
            }).start();



回答5:


In simple, we can start AsyncTask in a worker. You can just execute a AsyncTask in a new Thread, very simple. The reason is in the Android source code: [clike here]

private static class InternalHandler extends Handler {
    public InternalHandler() {
        super(Looper.getMainLooper());
    }
}


来源:https://stackoverflow.com/questions/9763476/start-async-task-within-a-worker-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!