温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

UI线程处理Handle

发布时间:2020-07-12 18:27:17 来源:网络 阅读:661 作者:福州大学G 栏目:移动开发

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

UI线程处理Handle


/*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>

 

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI