user1871869 user1871869 - 2 months ago 14
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:

LocationServices.java: This is where my
location
is received and the broadcasted.

@Override
public void onLocationChanged(Location location) {
if (location.hasAccuracy()) {
if (location.getAccuracy() < 30) {
locationUpdateListener.updateLocation(location);
Intent broadcastIntent = new Intent(LocationService.ACTION_LOCATION);
broadcastIntent.putExtra("latitude", location.getLatitude());
broadcastIntent.putExtra("longitude", location.getLongitude());
activity.sendBroadcast(broadcastIntent);
}
}
}


CreatePost.java: Here is where I want to ideally grab the location that was Broadcasted and use it in this file but the
onReceive
is never called. The activity is instantiated when the user clicks on the FAB button.

@Override
public void onResume() {
super.onResume();
locationReceiver = new BroadcastReceiver() {
@Override
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) {
e.printStackTrace();
}

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


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

Answer

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 {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(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());
    startActivity(intent);
}