我发现post()
和sendMessage()
之间存在一些信息差异
问题:Post()清楚地说明了我们将某些内容从后台线程发布到主线程。但是sendMessage()有何不同
答案 0 :(得分:1)
date area
1 2018/7/7 beijing
2 2018/7/7 shanghai
3 2018/7/7 guangzhou
4 2018/7/8 beijing
5 2018/7/8 shanghai
6 2018/7/8 guangzhou
7 2018/7/9 beijing
8 2018/7/9 shanghai
9 2018/7/9 guangzhou
和post()
在内部的工作方式相同,但是对于sendMessage()
,我们可以传递消息对象
sendMessage()
EXAMPLES
public class MainActivity extends AppCompatActivity {
Handler mHandler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Handler Started", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
initHandler();
}
});
}
private void initHandler() {
new Thread(new Runnable() {
@Override
public void run() {
try{
mHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this,"Executed in background thread",Toast.LENGTH_LONG).show();
}
});
}catch(Exception ex){
ex.printStackTrace();
Toast.makeText(MainActivity.this,ex.getMessage(),Toast.LENGTH_LONG).show();
}
}
}).start();
}
}