package com.cs.dxm.handlertest2;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
private Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
//post并没有启动新的线程
//handler.post(r);
Thread th = new Thread(r);
th.start();
System.out.println("Activity--->"+Thread.currentThread().getId());
System.out.println("Activity name--->"+Thread.currentThread().getName());
}
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("handler--->"+Thread.currentThread().getId());
System.out.println("handler name--->"+Thread.currentThread().getName());
try{
Thread.sleep(10000);
}catch (InterruptedException e){
e.printStackTrace();
}
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Android-Handler和Thread的关系
最新推荐文章于 2025-09-09 16:03:00 发布
本文深入探讨了Android中Handler的工作原理,包括如何使用Handler进行线程间通信,以及其在UI更新中的作用。通过一个具体的MainActivity实例,展示了Handler与Runnable结合使用的方法,以及它们在后台线程与主线程之间的交互细节。
407

被折叠的 条评论
为什么被折叠?



