(1)简单使用
public class AsyncHandler {
private static final HandlerThread sHandlerThread = new HandlerThread("AsyncHandler");
private static final Handler sHandler;
static {
sHandlerThread.start();
sHandler = new Handler(sHandlerThread.getLooper());
}
public static void post(Runnable r) {
sHandler.post(r);
}
private AsyncHandler() {
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = ((Button) findViewById(R.id.btn));
}
private Runnable runnable = new Runnable() {
@Override
public void run() {
String name = Thread.currentThread().getName();
Log.e(TAG, "start: "+name);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 此处是子线程不能刷新UI控件
// btn.setText("aaaa");
Log.e(TAG, "end: "+name);
}
};
/**
* 同步执行执行顺序
* start: AsyncHandler
* end: AsyncHandler
* start: AsyncHandler
* end: AsyncHandler
* start: AsyncHandler
* end: AsyncHandler
*/
public void go(View view) {
AsyncHandler.post(runnable);
AsyncHandler.post(runnable);
new Thread(new Runnable() {
@Override
public void run() {
AsyncHandler.post(runnable);
}
}).start();
}
}