发送的广播是在继承自service的类中写的,现在想在fragment和activity中都收到广播的数据,目前在activity中可以接收到,但是在fragment中没有成功,求大神解答~
service中的广播的代码:
private void broadcastUpdate(final String action,final BluetoothGattCharacteristic characteristic){
final Intent intent = new Intent(action);
if(UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())){
int flag = characteristic.getProperties();
int format = -1;
if((flag & 0x01)!= 0){
format = BluetoothGattCharacteristic.FORMAT_UINT16;
Log.d(TAG,"Heart Rate format UINT16.");
}else{
format = BluetoothGattCharacteristic.FORMAT_UINT8;
Log.d(TAG,"Heart Rate format UINT8.");
}
heartRate = characteristic.getIntValue(format,1);
Log.d(TAG,String.format("Received Heart Rate : %d",heartRate));
intent.putExtra(EXTRA_DATA,String.valueOf(heartRate));
}
...
sendBroadcast(intent);
}
activity中的广播接收器的代码:
private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context,Intent intent){
final String action = intent.getAction();
...
}
}
@Override
protected void onResume(){
super.onResume();
registerReceiver(mGattUpdateReceiver,makeGattUpdateIntentFilter());
}
@Override
protected void onPause(){
super.onPause();
registerReceiver(mGattUpdateReceiver);
}
@Override
protected void onDestroy(){
super.onDestroy();
unbindService(mServiceConnection);
}
我想问的是,在fragment中是怎么对接收器设置啊?查了好多,也不知道怎么去设置,是和activity一样吗?
你可以在activity 接收书,传递给fragment
你在fragment 里面添加set 方法,把actcivity 里面的参数,通过new fragment () ,拿到这个对象的set方法,传过去