码迷,mamicode.com
首页 > 其他好文 > 详细

使用Handler的步骤

时间:2015-07-27 18:13:10      阅读:93      评论:0      收藏:0      [点我收藏+]

标签:

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;
    }
}

 

==

使用Handler的步骤

标签:

原文地址:http://www.cnblogs.com/graphics/p/4680540.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!