I have a service running in which I am getting location updates. The service returns the location successfully. But after that I am trying to broadcast the location to any activity that might be listening. I have registered the receiver in my activity but for some reason the onReceive
method is not being called.
Here is the code inside my onLocationChanged
method inside my service.
@Override
public void onLocationChanged(Location location) {
Intent intent = new Intent();
intent.setAction("LocationBroadcast");
double lat = location.getLatitude();
double lng = location.getLongitude();
intent.putExtra("lat", lat);
intent.putExtra("lng", lng);
//I am initializing the broadcaster object in onCreate method of my service but I am putting it here for simplicity
broadcaster = LocalBroadcastManager.getInstance(this);
//This Toast successfully shows my coordinates so I know the problem is not with this method
Toast.makeText(GoogleFusedLocationApiService.this, ""+lat+", "+lng+"", Toast.LENGTH_SHORT).show();
broadcaster.sendBroadcast(intent);
}
Inside my activity in my onCreate method, I am registering for the LocationBroadcast
like so.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
...
IntentFilter intentFilter = new IntentFilter("LocationBroadcast");
super.registerReceiver(mMessageReceiver, intentFilter);
startService(new Intent(MyApp.getAppContext(), GoogleFusedLocationApiService.class));
}
I've tried this.registerReceiver(mMessageReceiver, intentFilter);
and LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, intentFilter);
but neither worked.
Here is my mMessageReceiver
defined,
public BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
double lat = intent.getDoubleExtra("lat", 0);
double lng = intent.getDoubleExtra("lng", 0);
// This Toast never shows and neither can I debug this method at all
// so for now the only conclusion is the broadcast is not being received
Toast.makeText(MyApp.getAppContext(), "Cordinates are "+lat+", "+lng+"", Toast.LENGTH_SHORT).show();
}
};
Moreover, some of the details that I might think matter after some research. I haven't declared receiver
in the manifest
because I read that you only do that when you want your application to launch when the broadcast is received but I only want my application to react when it is already running. Not launch whenever the services sends a broadcast.
And I haven't extended the activity to BroadcastReceiver
either since the activity is already extended to FragmentActivity
The app does not crash and onLocationChanged is located inside the service that is being started after the BroadcastReceiver is registered so onLocationChanged is not invoked before the BroadcastReceiver has been registered