package com.test.outputblog;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
textView.setText(".......");
GetHandlerInstance.getInstance().job(new GetHandlerInstance.CallBack() {
@Override
public boolean doInWorkThread() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
return false;
}
return true;
}
@SuppressLint("SetTextI18n")
@Override
public void runOnUiThread() {
textView.setText("hello 你好");
}
});
}
}
package com.test.outputblog;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.widget.TextView;
import androidx.annotation.MainThread;
import androidx.annotation.UiThread;
import androidx.annotation.WorkerThread;
class GetHandlerInstance {
private volatile static GetHandlerInstance instance;
//双重校验锁 单例模式
public static GetHandlerInstance getInstance() {
if (instance == null) {
synchronized (GetHandlerInstance.class) {
if (instance == null) {
instance = new GetHandlerInstance();
}
}
}
return instance;
}
private static Handler workerHandler;
private static Handler mainHandler;
private GetHandlerInstance(){
HandlerThread handlerThread = new HandlerThread("sub_thread");
handlerThread.start();
// 设置handlerThread 的lopper
workerHandler = new Handler(handlerThread.getLooper());
mainHandler = new Handler(Looper.getMainLooper());
}
public void job(CallBack callBack){
getWorkHandler().post(new Runnable() {
@Override
public void run() {
if (callBack.doInWorkThread()) {
getMainHandler().post(new Runnable() {
@Override
public void run() {
callBack.runOnUiThread();
}
});
}
}
});
}
public static Handler getWorkHandler(){
return workerHandler;
}
public static Handler getMainHandler(){
return mainHandler;
}
public interface CallBack{
// 工作线程
boolean doInWorkThread();
// 主线程
void runOnUiThread();
}
}