简体   繁体   中英

doInBackground from AsyncTask never called when Service work on background

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM