70.自定义异步任务
1.抽象异步任务类:
public abstract class YTAsyncTask<T> {private static final HandlerThread handlerThread = new HandlerThread(YTAsyncTask.class.getName(), 10);public YTAsyncTask() {}protected abstract void onPreExecute();protected abstract T doInBackground();protected abstract void onPostExecute(T param);public final YTAsyncTask<T> execute() {final Handler mainHandler = new Handler(Looper.getMainLooper());Handler bgHandler = new Handler(handlerThread.getLooper());this.onPreExecute();bgHandler.post(new Runnable() {public void run() {final T param= YTAsyncTask.this.doInBackground();mainHandler.post(new Runnable() {public void run() {YTAsyncTask.this.onPostExecute(param);}});}});return this;}static {handlerThread.start();}}
2.使用用例:
public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);testAsyncTask();}private void testAsyncTask() {new YTAsyncTask<String>() {@Overrideprotected void onPreExecute() {Log.e("ytr", "onPreExecute,currentThread=" + Thread.currentThread().getName());}@Overrideprotected String doInBackground() {Log.e("ytr", "doInBackground,currentThread=" + Thread.currentThread().getName());return "Hello World";}@Overrideprotected void onPostExecute(String param) {Log.e("ytr", "onPostExecute,currentThread=" + Thread.currentThread().getName()+"\tparam="+param);}}.execute();}}
打印结果:


浙公网安备 33010602011771号