user1871869 user1871869 - 5 months ago 25
Android Question

Receive broadcast for activity not started yet?

I want to have a

Broadcast Receiver
to obtain location information for an activity that is not started yet. Basically I have some location that I obtain in one activity. When I click my FAB button, I want to take the location that I obtained in the first activity and send it over to the activity that the FAB button navigates to so I can use the location in that activity. Here is my attempt: This is where my
is received and the broadcasted.

public void onLocationChanged(Location location) {
if (location.hasAccuracy()) {
if (location.getAccuracy() < 30) {
Intent broadcastIntent = new Intent(LocationService.ACTION_LOCATION);
broadcastIntent.putExtra("latitude", location.getLatitude());
broadcastIntent.putExtra("longitude", location.getLongitude());
} Here is where I want to ideally grab the location that was Broadcasted and use it in this file but the
is never called. The activity is instantiated when the user clicks on the FAB button.

public void onResume() {
locationReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
try {
if(location == null) {
location = new Location("Provider");
location.setLatitude(intent.getDoubleExtra("latitude", 0.0));
location.setLongitude(intent.getDoubleExtra("longitude", 0.0));
} catch (Exception e) {

registerReceiver(locationReceiver, new IntentFilter(LocationService.ACTION_LOCATION));

Is there any way to send the
over when the activity is instantiated? Or am I not understanding the idea of a
Broadcast Receiver


Just put the data in the Intent that starts the second activity. Then in the second activity, get the intent by calling getIntent(), and retrieve data from it. Something like this:

class SecondActivity extends Activity {
    protected void onCreate(Bundle savedInstanceState) {
        Intent intent = getIntent();
        float latitude = intent.getFloatExtra("latitude", 0);
        float longitude = intent.getFloatExtra("longitude", 0);

private void startActivityWithData() {
    Intent intent = new Intent(this, SecondActivity.class);
    intent.putExtra("latitude", location.getLatitude());
    intent.putExtra("longitude", location.getLongitude());