android Handler消息通信
阅读原文时间:2023年07月08日阅读:3

1 package com.example.testhandler;
2
3 import android.os.Bundle;
4 import android.os.Handler;
5 import android.os.Message;
6 import android.app.Activity;
7 import android.view.Menu;
8 import android.widget.TextView;
9
10 public class MainActivity extends Activity {
11
12 Handler handler = null;
13 String textString = null;
14 TextView textView;
15 @Override
16 protected void onCreate(Bundle savedInstanceState) {
17 super.onCreate(savedInstanceState);
18 setContentView(R.layout.activity_main);
19 textView = (TextView) findViewById(R.id.text);
20 Runnable task = new Runnable() {
21
22 @Override
23 public void run() {
24 textString = "Hello World!";
25 Message msg = new Message();
26 msg.what = 0x123;
27 handler.sendMessage(msg);
28 }
29 };
30 handler = new Handler(){
31
32 @Override
33 public void handleMessage(Message msg) {
34 //super.handleMessage(msg);
35 if (msg.what == 0x123) {
36 textView.setText(textString);
37 }
38 }
39
40 };
41
42 new Thread(task).start();
43
44 }
45
46 @Override
47 public boolean onCreateOptionsMenu(Menu menu) {
48 // Inflate the menu; this adds items to the action bar if it is present.
49 getMenuInflater().inflate(R.menu.main, menu);
50 return true;
51 }
52
53 }

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章