Reputation:
This BroadcastReceiver is inside my fragment:
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);
}
};
The problem is that I do think think that it is listening or receiving. The Log.d never shows in the LogCat. I have no idea why. The only difference in this entry and another the did work, was that the previous entry was actually in an Activity. This one is in a Fragment. Am I missing something here or should there be something in my manifest for this fragment or receiver?
UPDATE:
THe Sensor sends the broadcast with:
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);
}
}
Upvotes: 2
Views: 1318
Reputation: 14710
You are doing at least 2 wrong things:
Context.registerReceiver()
and then you're sending broadcast updates through LocalBroadcastmanager
. You will never get these messages. LocalBroadcastManager
doesn't know about receivers registered through Context
and vice-versa.So try this: register the receiver in onCreate
or onResume
and then unregister the same instance in the complementary method: onDestroy
or onPause
. Also, when registering and sending intents, use the same mechanism - either LocalBroadcastManager
, either the Context
based. The first one has the advantage of sending the messages only in your app.
For example, suppose your fragment is called 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
}
}
Upvotes: 4