Is a good practice create anonymous AsyncTask for parallel small known freeze process? [closed]

最后都变了- 提交于 2019-12-03 08:37:33

问题


E.g.: you gonna do something that will take a few seconds and don't wanna freeze your UI thred, right? You could use an AsyncTask but you don't wanna create a external (or inner) class to solve a small freeze problem.

So, is a good pratice do it?

package com.example.stackoverflowsandbox;

import android.os.AsyncTask;

public class Foo {
    // E.g. before call foo method you change you Activity to loading state.
    private void foo() {
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground( final Void ... params ) {
                // something you know that will take a few seconds

                return null;
            }

            @Override
            protected void onPostExecute( final Void result ) {
                // continue what you are doing...

                Foo.this.continueSomething();
            }
        }.execute();
    }

    private void continueSomething() {
        // some code...
    }
}

I've faced with that when I compressing Bitmaps and looping big array to update some data inside items.


回答1:


Yes, but not the way you do it.

Remember that starting Honeycomb the default execution model of AsyncTasks is serial:

  new AsyncTask<Void, Void, Void>() {
         ....
         ....
  }.execute(); <------ serial execution


Instead use a thread pool executor:

  new AsyncTask<Void, Void, Void>() {
         ....
         ....
  }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, null); <------ parallel execution


来源:https://stackoverflow.com/questions/24827312/is-a-good-practice-create-anonymous-asynctask-for-parallel-small-known-freeze-pr

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