doInBackground from AsyncTask never called when Service work on background

做~自己de王妃 提交于 2019-12-08 08:45:13

问题


private class Test extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            Log.d("test", "called1");
        }

        @Override
        protected Void doInBackground(Void... params) {
            Log.d("test", "called2");
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            Log.d("test", "called3");
        }
    }

and output:

test:called1

Why other methods never don't called when Service work on background? If service stop, then all method calls and output:

test:called1

test:called2

test:called3


回答1:


I guess you are testing on android 3.x or newer and you are simply affected by the change made to the way AsyncTask is executed.

This is how I handle this in my code to always work the same fully parallel:

if( Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ) {
    new Test().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
    new Test().execute();
}

Basically change in AsyncTask appeared in Honeycomb (see Android SDK docs here in "Order of execution" section), so before that, you launch it as usual, for HC and up, use executeOnExecutor() if you do not like new behaviour (noone does, I think)



来源:https://stackoverflow.com/questions/13670080/doinbackground-from-asynctask-never-called-when-service-work-on-background

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