Handler消息传递机制
子线程不允许操作主线程的U界面
Handler是android中提供的一个消息处理的机制
1.在任意线程中发送消息
2.在主线程中获取并处理消息
一种是handler.sendMessage。发一个消息,再根据消息,执行相关任务代码。
Handler的相关方法:
void handleMessage(Message msg):处理消息的方法,通常是用于被重写!
sendEmptyMessage(int what):发送空消息
sendEmptyMessageDelayed(int what,long delayMillis):指定延时多少毫秒后发送空信息
sendMessage(Message msg):立即发送信息
sendMessageDelayed(Message msg):指定延时多少毫秒后发送信息
final boolean hasMessage(int what):检查消息队列中是否包含what属性为指定值的消息 如果是参数为(int what,Object object):除了判断what属性,还需要判断Object属性是否为指定对象的消息
另一种是handler.post( r )。r是要执行的任务代码。意思就是说r的代码实际是在UI线程执行的。可以写更新UI的代码。
handler.sendMessage。主线程创建Handler
在主线程中,因为系统已经初始化了一个Looper对象,所以我们直接创建Handler对象,就可以进行信息的发送与处理了!
package com.example;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = findViewById(R.id.tv);
Button button = findViewById(R.id.btn);
Handler handler = new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
if (msg.what == 0x123){
textView.setText("你今天的努力是新云的伏;当下的付出,是明日的花开");
}
}
};
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//创建线程
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
handler.sendEmptyMessage(0x123);//发送空消息
// textView.setText("你今天的努力是新云的伏;当下的付出,是明日的花开");
}
});
thread.start();//开启线程
}
});
}
}
handler.post( r )
public void handlerUI(){
handler.post(runnable);
}
//开线程更新UI
Runnable runnable = new Runnable() {
@Override
public void run() {
etContent.setText("size:");
etContent.setSelection(0, etContent.getText().toString().length());
}
};
子线程创建Handler
如果是Handler写在了子线程中的话,我们就需要自己创建一个Looper对象了!创建的流程如下:
1 )直接调用Looper.prepare()方法即可为当前线程创建Looper对象,而它的构造器会创建配套的MessageQueue; 2 )创建Handler对象,重写handleMessage( )方法就可以处理来自于其他线程的信息了! 3 )调用Looper.loop()方法启动Looper
实现代码: main.xml:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="@+id/etNum"
android:inputType="number"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入上限"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="cal"
android:text="计算"/>
</LinearLayout>
MainActivity.java:
public class CalPrime extends Activity
{
static final String UPPER_NUM = "upper";
EditText etNum;
CalThread calThread;
// 定义一个线程类
class CalThread extends Thread
{
public Handler mHandler;
public void run()
{
Looper.prepare();
mHandler = new Handler()
{
// 定义处理消息的方法
@Override
public void handleMessage(Message msg)
{
if(msg.what == 0x123)
{
int upper = msg.getData().getInt(UPPER_NUM);
List<Integer> nums = new ArrayList<Integer>();
// 计算从2开始、到upper的所有质数
outer:
for (int i = 2 ; i <= upper ; i++)
{
// 用i处于从2开始、到i的平方根的所有数
for (int j = 2 ; j <= Math.sqrt(i) ; j++)
{
// 如果可以整除,表明这个数不是质数
if(i != 2 && i % j == 0)
{
continue outer;
}
}
nums.add(i);
}
// 使用Toast显示统计出来的所有质数
Toast.makeText(CalPrime.this , nums.toString()
, Toast.LENGTH_LONG).show();
}
}
};
Looper.loop();
}
}
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
etNum = (EditText)findViewById(R.id.etNum);
calThread = new CalThread();
// 启动新线程
calThread.start();
}
// 为按钮的点击事件提供事件处理函数
public void cal(View source)
{
// 创建消息
Message msg = new Message();
msg.what = 0x123;
Bundle bundle = new Bundle();
bundle.putInt(UPPER_NUM ,
Integer.parseInt(etNum.getText().toString()));
msg.setData(bundle);
// 向新线程中的Handler发送消息
calThread.mHandler.sendMessage(msg);
}
}
Message
Message对象的属性
arg1,arg2 整形
obj Object类型
replyTo 发送到何处
what 自定义的消息代码
创建Message对象
1.Message.obtain()
2.Handler.obtainMessage()
模拟手机淘宝使用Handler和Message实现轮播广告
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/taobao"
tools:context=".MainActivity">
<ViewFlipper
android:id="@+id/vf"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
package com.example;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.ViewFlipper;
public class MainActivity extends AppCompatActivity {
private ViewFlipper flipper;
private int[] images = new int[]{R.drawable.icon1,R.drawable.icon2,R.drawable.left
,R.drawable.like,R.drawable.line};
private Animation[] animation = new Animation[2];
private final int FLAG_MSG = 0x001;
private Message message;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
flipper = findViewById(R.id.vf);
for (int i = 0; i < images.length; i++) {
ImageView imageView = new ImageView(this);
imageView.setImageResource(images[i]);
flipper.addView(imageView);
}
animation[0] = AnimationUtils.loadAnimation(this, R.anim.slide_in_right);
animation[1] = AnimationUtils.loadAnimation(this, R.anim.slide_out_left);
flipper.setInAnimation(animation[0]);
flipper.setOutAnimation(animation[1]);
message = Message.obtain();
message.what = FLAG_MSG;
handler.sendMessage(message);
}
Handler handler = new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
if (msg.what ==FLAG_MSG){
flipper.showPrevious();
message = handler.obtainMessage(FLAG_MSG);
handler.sendMessageDelayed(message,3000);
}
}
};
}
Looper
Looper对象的创建
handler在主线程中创建时,系统自动创建Looper对象
handler在子线程中创建时,手动创建Looper对象
子线程中创建Looper对象的步骤
1.初始化Looper对象prepare()
2.创建Handler对象new Handler()
3.启动Looper loop()
package com.example;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import androidx.annotation.NonNull;
public class LooperThread extends Thread{
private Handler handler;
@Override
public void run() {
super.run();
Looper.prepare();//初始化Looper对象
handler = new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
Log.i("Looper",String.valueOf(msg.what));
}
};
Message message = handler.obtainMessage();
message.what = 0x7;
handler.sendMessage(message);
Looper.loop();//启动Looper
}
}
package com.example;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LooperThread thread = new LooperThread(){};
thread.start();
}
}