1. 在Activity中定义Handler并实现handleMessage方法用来处理接收到的消息。
2. 定义一个Runable实例,并在run方法中设置和发送消息(使用Bundle实现)
3. 新建一个Thread并运行步骤2中的Runable。调用Thread.start().
完整代码
public class MainActivity extends AppCompatActivity { Handler handler = new Handler() { @Override public void handleMessage(Message msg) { // Get message from another thread. String msgStr = msg.getData().getString("msg"); Toast.makeText(MainActivity.this, msgStr, Toast.LENGTH_SHORT).show(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void buttonClick(View view) { Runnable runnable = new Runnable() { @Override public void run() { Bundle bundle = new Bundle(); bundle.putString("msg", "Hello, world"); // Send the message to main thread. Message msg = handler.obtainMessage(); msg.setData(bundle); handler.sendMessage(msg); } }; Thread myThread = new Thread(runnable); myThread.start(); } @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; } }
==
时间: 2024-11-15 00:34:51