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

消息机制,Handler

时间:2016-05-17 09:55:02      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:

技术分享
package com.example.lenovo.textapp4;

import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Random;

public class Text6Activity extends AppCompatActivity {

    TextView tv_5,tv_6;
    //定义Handler
    Handler h=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            //处理消息
            if (msg.what==1)
            {
                String m=msg.obj.toString();
                tv_5.setText(tv_5.getText()+"  "+m);
            }
            else if (msg.what==2)
            {
                tv_5.setText(tv_5.getText()+"空消息");
            }

        }
    };

    int i=10;
    Handler hl=new Handler()
    {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what)
            {
                case 1:
                    i++;
                    if (i==20)
                    {
                        return;
                    }
                    tv_6.setText(i+"");
                    //发送
                    hl.sendEmptyMessageDelayed(1,1000);
                    hl.removeMessages(2);

                    break;
                case 2:
                    i--;
                    if (i==1)
                    {
                        return;
                    }
                    tv_6.setText(i+"");
                    hl.sendEmptyMessageDelayed(2,1000);
                    hl.removeMessages(1);
                    break;
                case 3:
                    hl.removeMessages(1);
                    hl.removeMessages(2);
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_text6);

        tv_5=(TextView)findViewById(R.id.tv_5);
        tv_6=(TextView)findViewById(R.id.tv_6);
    }

    //三个按钮
    public void bt2_on(View v)
    {
        switch( v.getId())
        {
            case R.id.bt_3:
                //发送增加消息

                hl.sendEmptyMessage(1);
                break;
            case R.id.bt_4:
                //发送减少消息
                hl.sendEmptyMessage(2);
                break;
            case R.id.bt_5:
                //发送暂停消息
                hl.sendEmptyMessage(3);
                break;
        }
    }
}
View Code

技术分享

消息机制,Handler

标签:

原文地址:http://www.cnblogs.com/1ming/p/5500296.html

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