我的广播接收器和发件人在这里搞砸了。也许另一组眼睛会很有用。
我有我的lightsensor,它应该广播接收活动的变化。
这是LightSensor.java
public void onSensorChanged(SensorEvent event) {
lightLux = event.values[0]; //Final output of this sensor.
Lux = String.valueOf(lightLux);
sendLuxUpdate();
Log.d("LightSensor", Lux);
TextView tvLightSensorLux = (TextView) findViewById(R.id.tvLightSensorLux);
tvLightSensorLux.setText(Lux);
}
private void sendLuxUpdate() {
Log.d("sender", "Broadcasting message");
Intent intent = new Intent("LuxUpdate");
// You can also include some extra data.
intent.putExtra("Lux", lightLux);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
然后我的Record.java被用来接收勒克斯的那些更新:
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_record);
LocalBroadcastManager.getInstance(this).registerReceiver(mLightReceiver,
new IntentFilter("LuxUpdate"));
}
private BroadcastReceiver mLightReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
String lux = intent.getStringExtra("Lux");
Log.d("Light Lux", "Lux Update: " + lux);
TextView tvSensorLightLux = (TextView) findViewById(R.id.tvSensorLightLux);
tvSensorLightLux.setText(lux);
}
};
@Override
protected void onDestroy() {
// Unregister since the activity is about to be closed.
LocalBroadcastManager.getInstance(this).unregisterReceiver(mLightReceiver);
super.onDestroy();
}
我认为这只是发送和接收ID的问题,但我不完全确定。一旦Record活动收到广播,它应该更新TextView tvSensorLightLux或至少Log.d来自LightSensor.java的Lux值
答案 0 :(得分:0)
你正在传递Float并使用你正在使用的接收器,
String lux = intent.getStringExtra("Lux");
需要"Lux"
为String。
当你传递Float时。在接收器中只需添加getFloatExtra()
lux =intent.getFloatExtra("Lux", defaultValue);
输入您想要的默认值,比如0