Android中Handler的使用一例

来源:互联网 发布:小应变数据分析 编辑:程序博客网 时间:2024/06/08 10:09

1. 继承Handler, 编写自己的Handler类

static class MyHandler extends Handler    {        private WeakReference<MainActivity> mActivity;        public MyHandler(MainActivity activity)        {            mActivity = new WeakReference<MainActivity>(activity);        }        @Override        public void handleMessage(Message msg)        {            switch(msg.what)            {                case 0:                {}break;                case 1:                {                    Bundle bundle = msg.getData();                    mActivity.get().setBtnText(bundle.getString("info"));                }break;                default:                {}break;            }        }    }
    这里使用了弱引用, 可以避免内存泄露, 详细参考:

Android App 内存泄露之Handler

Android之Handler内存泄漏分析及解决


2. 在layout中增加必要的控件来进行操作和显示:

    <TextView        android:id="@+id/helloworld_tv"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Hello World!"        app:layout_constraintBottom_toBottomOf="parent"        app:layout_constraintLeft_toLeftOf="parent"        app:layout_constraintRight_toRightOf="parent"        app:layout_constraintTop_toTopOf="parent" />    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/btn_name"        android:onClick="onHandleMessage"/>

3. string.xml文件中:

<string name="btn_name">Handle it!</string>

4. 主Activity中, 实现onClick:

    TextView mModifyTextView;    MyHandler mHandler;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        mModifyTextView = (TextView)findViewById(R.id.helloworld_tv);        mHandler = new MyHandler(this);    }    public void onHandleMessage(View view)    {        Message msg = new Message();        msg.what = 1;        Bundle bundle = new Bundle();        bundle.putString("info", "modify to hei.");        msg.setData(bundle);        mHandler.sendMessage(msg);    }    private void setBtnText(String str)    {        mModifyTextView.setText(str);    }


5. 当然, 你可能还需要import必要的命名空间:

import android.support.v7.app.AppCompatActivity;import android.view.View;import android.widget.TextView;
import java.lang.ref.WeakReference;

6. 点击按钮就可以看到Handler处理的结果了.


    Handler处理的流程就是: 使用Handler类发送消息, Handler的实例化变量在创建的时候就和当前的线程(也就是主线程)建立了关联, 发送消息就是将消息放入主线程的Looper中, 然后主线程的Looper不断的将消息取出并交给Handler的回调方法onHandleMessage(这个时候消息已经运行在主线程上了, 发送消息的时候未必在主线程).

   这样, 就实现了异步操作.

0 0
原创粉丝点击