码迷,mamicode.com
首页 > 编程语言 > 详细

UI线程处理Handle

时间:2015-06-21 23:52:21      阅读:235      评论:0      收藏:0      [点我收藏+]

标签:android   handler   

android的UI是不可以在子线程中更新,因为子线程涉及到UI更新,,Android主线程是线程不安全的,也就是说更新UI只能在主线程中更新,但是在主线程中更新如果更新超过5秒钟,android系统就会收到android系统的一个错误提示"强制关闭",这个时候Handle就出来了,由于Handler运行在主线程中(UI线程中),  它与子线程可以通过Message对象来传递数据, 这个时候,Handler就承担着接受子线程传过来的(子线程用sedMessage()方法传弟)Message对象,(里面包含数据)  , 把这些消息放入主线程队列中,配合主线程进行更新UI。

技术分享


/*MainActivity 文件*/
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.logging.LogRecord;


public class MainActivity extends ActionBarActivity implements View.OnClickListener{
public Button button_1;
    public TextView text;
    private static final int UPDATE=1;
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what==UPDATE)
            {
                Log.d("msg.obj:",String.valueOf(msg.obj));
               text.setText(String.valueOf(msg.obj));
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button_1=(Button)findViewById(R.id.button_1);
        text=(TextView)findViewById(R.id.text_1);
        button_1.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message message=new Message();
                message.what=UPDATE;
                message.obj="handler处理有效果";
                handler.sendMessage(message);
            }
        }).start();
    }
}
/*布局文件activity_main*/
<LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"
     tools:context=".MainActivity"
    android:orientation="vertical">

    <TextView android:id="@+id/text_1"
        android:text="没处理过的handler" android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
<Button android:id="@+id/button_1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="OnClick"
    />
</LinearLayout>

 

本文出自 “自定义Adapter” 博客,请务必保留此出处http://10268696.blog.51cto.com/10258696/1664060

UI线程处理Handle

标签:android   handler   

原文地址:http://10268696.blog.51cto.com/10258696/1664060

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