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 { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); testAsyncTask(); } private void testAsyncTask() { new YTAsyncTask<String>() { @Override protected void onPreExecute() { Log.e("ytr", "onPreExecute,currentThread=" + Thread.currentThread().getName()); } @Override protected String doInBackground() { Log.e("ytr", "doInBackground,currentThread=" + Thread.currentThread().getName()); return "Hello World"; } @Override protected void onPostExecute(String param) { Log.e("ytr", "onPostExecute,currentThread=" + Thread.currentThread().getName()+"\tparam="+param); } }.execute(); }}

打印結果:



相關文章
相關標籤/搜索