【发布时间】:2014-01-21 14:34:53
【问题描述】:
这个 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 中。我不知道为什么。这个条目和另一个做的工作的唯一区别是前一个条目实际上是在一个活动中。这是一个片段。我是否在这里遗漏了某些内容,或者我的清单中是否应该有针对此片段或接收器的内容?
更新:
传感器发送广播:
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);
}
}
【问题讨论】:
-
你注册你的接收器了吗?
-
对不起,我编辑了上面的内容以反映 reg。在注册中,我确实看到了 Log.d 条目。并不意味着它被正确注册,只是它通过了那个语句。
-
您还应该包括将
Intent发送给接收者,所以如果一切正常,有人可能会看看。 -
接收者是否注册与代码无关。
-
我仍然缺少注册语句,它应该类似于
LocalBroadcastManager.getInstance(this).registerReceiver(broadcast_receiver);,因为您使用的是LocalBroadcastManager。
标签: android android-fragments broadcastreceiver broadcast