- Activity(MainActivity.java)页面
1.初始化Handler对象
private android.os.Handler handler
2.创建handler发送的指令
if (handler != null) {
new Thread(new Runnable() {
@Override
public void run() {
/* 更新传递数据到Fragment */
Message message = new Message();
Bundle bundle = new Bundle();
bundle.putInt("customer_count", customer_count);
message.setData(bundle);
handler.sendMessage(message);
}
}).start();
} else {
Log.d("handler", "为空");
}
3.新建公共方法将Fragment中的handler传入Activity中
public void setHandler(android.os.Handler handler) {
this.handler = handler;
}
-
Fragment(PersonFragment.java)页面
1.设置解析接受数据并实现更新效果
//与Activity通信获取实时数据
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Bundle bundle = msg.getData();
//获取传入数据
int customer_count = bundle.getInt("customer_count");
//处理逻辑业务
if (personal_custom_count != null && personal_custom_icon != null) {
if (customer_count != 0) {
//业务一
} else {
//业务二
}
}
Log.d("handler", "" + customer_count);
}
};
2.初始化Fragment生命周期(onAttach)**
//生命周期
@Override
public void onAttach(Context context) {
super.onAttach(context);
mainActivity = (MainActivity) context;
mainActivity.setHandler(handler);
}