Pergunta

I have goofed something up here with my Broadcast Receivers and my Sender. perhaps another set of eyes would be useful.

I have my lightsensor which is supposed to broadcast changes to the receiving activity.

Here is the 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);
    }

Then my Record.java is suposed to receive those updates to the lux:

@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();
}

I think it is just a matter of the sending and receiving id, but am not totally sure. Once the Record activity receives the broadcast, it should update the TextView tvSensorLightLux or at least Log.d the Lux value from LightSensor.java

Foi útil?

Solução

You are passing Float and in receiver you are using,

String lux = intent.getStringExtra("Lux");

which requires "Lux" to be String.

As you are passing Float. In receiver Just add getFloatExtra()

lux =intent.getFloatExtra("Lux", defaultValue); 

put default value you want, say 0

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top