您的位置:首页 > 移动开发 > Android开发

android的广播发送与接收

2016-07-21 16:35 417 查看

一、发送广播

<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======连接成功");
}
}
}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息