安卓中多线程间通信方式
背景
安卓开发中多线程间通信是比较常见的操作,现对常用的几种方式先进行一波简单的总结。
一、通过handler方式
Handler handler = new Handler() {
@Override
public void handleMessage(@NonNull Message msg) {
Toast.makeText(MainActivity.this, "handleMessage", Toast.LENGTH_SHORT).show();
Log.d(TAG, "handleMessage" + msg.what);
}
};
new Thread() {
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
Message message = new Message();
message.what = 3;
handler.sendMessage(message);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
二、子线程中使用runOnUiThread方法
TextView tv;
tv = findViewById(R.id.tv);
new Thread() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
tv.setText("子线程设置testView");
}
});
}
}.start();
三、子线程中使用View.post(Runnable r) 方式
TextView tv;
tv = findViewById(R.id.tv);
new Thread() {
@Override
public void run() {
tv.post(new Runnable() {
@Override
public void run() {
tv.setText("子线程设置text");
}
});
}
}.start();
四、通过AsyncTask(Deprecated,不推荐)
TextView tv;
tv = findViewById(R.id.tv);
class MyAsyncTask extends AsyncTask {
@Override
protected Object doInBackground(Object[] objects) {
for (int i = 0; i < 3; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return objects[0].toString();
}
@Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
tv.setText(o.toString());
}
}