一、发送广播
<span style="white-space:pre"> </span>/**
* 发送后厨状态广播
* @param context 上下文
* @param status自定义的状态码
*/
public static void sendKitchenPrintStatusBroadcast(Context context,int status) {
Intent intent = new Intent();
intent.setAction(OneLeadPosConstants.SYNCHRONIZE_KITCHEN_PRINT_STATUS_ACTION);//设置action
intent.putExtra(OneLeadPosConstants.SYNCHRONIZE_KITCHEN_PRINT_STATUS_ACTION, status);//放入传输数据
context.sendBroadcast(intent);//有序广播发送
}
二、广播接收者
一定要记得在初始化方法中注册registerBoradcastReceiver();,在onDestroy方法中解除注册this.unregisterReceiver(mBroadcastReceiver);
<span style="white-space:pre"> </span>/**
* 注册后厨状态广播
*
*/
private void registerBoradcastReceiver(){
IntentFilter myIntentFilter = new IntentFilter();//创建意图过滤器
myIntentFilter.addAction(OneLeadPosConstants.SYNCHRONIZE_KITCHEN_PRINT_STATUS_ACTION);//设置过滤器action
//注册广播 广播接收者,广播过滤器
registerReceiver(mBroadcastReceiver, myIntentFilter);
}
<span style="white-space:pre"> </span> /**
* 后厨状态广播接收者
*
*/
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equals(OneLeadPosConstants.SYNCHRONIZE_KITCHEN_PRINT_STATUS_ACTION)){
int status=intent.getIntExtra(OneLeadPosConstants.SYNCHRONIZE_KITCHEN_PRINT_STATUS_ACTION, 80);
if(status==80){//后厨打印机没有启用
Log.d("hainan", "hainan======后厨打印机没有启用");
}else if (status==50) {//连接不上后厨打印机
Log.d("hainan", "hainan======连接不上后厨打印机");
}else if (status==100) {//连接成功
Log.d("hainan", "hainan======连接成功");
}
}
}
};
本文详细介绍了Android中的广播机制,包括如何发送自定义广播以及如何创建和注册广播接收者。通过具体示例展示了发送后厨状态广播的方法,并解释了如何解析接收到的广播数据。
741

被折叠的 条评论
为什么被折叠?



