ActivityとFragmentのリアルタイム通信
1826 ワード
private android.os.Handler handler
を初期化する.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;
}
// 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ライフサイクルの初期化**
//
@Override
public void onAttach(Context context) {
super.onAttach(context);
mainActivity = (MainActivity) context;
mainActivity.setHandler(handler);
}