这个BroadcastReceiver在我的片段中:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
...
getActivity().startService(new Intent(getActivity(),LightSensor.class));
Log.d(TAG, "Called the LightSensor Service Class to start");
IntentFilter luxfilter = new IntentFilter("LuxUpdate");
getActivity().getApplicationContext().registerReceiver(mLightReceiver, luxfilter);
...
}
...
// RECEIVE DATA FROM LIGHT SENSOR BROADCAST
public BroadcastReceiver mLightReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String lux = intent.getStringExtra("Lux");
Log.d(TAG, "Recieve Broadcast-Lux Update: " + lux);
//TextView tvSensorLightLux = (TextView) findViewById(R.id.tvSensorLightLux);
mLightValue.setText(lux);
}
};
问题是我确实认为它是在听或接受。 Log.d永远不会显示在LogCat中。我不知道为什么。这个条目和另一个确实有效的唯一区别是前一个条目实际上是在一个Activity中。这是一个片段。我在这里遗漏了什么,或者我的清单中是否有针对此片段或接收器的内容?
更新:
传感器发送广播:
private void sendLuxUpdate() {
if(isLightSensing){
Log.d(TAG, "sender Broadcasting message " + Lux);
Intent intent = new Intent("LuxUpdate");
intent.putExtra("Lux", Lux);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
}
答案 0 :(得分:4)
你至少做了两件错事:
Context.registerReceiver()
注册接收方,然后通过LocalBroadcastmanager
发送广播更新。你永远不会收到这些消息。 LocalBroadcastManager
不了解通过Context
注册的接收者,反之亦然。请尝试此操作:在onCreate
或onResume
中注册接收方,然后在补充方法中取消注册相同的实例:onDestroy
或onPause
。此外,在注册和发送意图时,请使用相同的机制 - LocalBroadcastManager
,基于Context
。第一个优势是只在您的应用中发送消息。
例如,假设您的片段名为DeviceView
:
public class DeviceView extends Fragment{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(your_receiver, intent_filter);
/// other code
}
@Override
public void onDestroy() {
super.onDestroy();
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(your_receiver);
/// other code
}
}