user1871869
user1871869

Reputation: 3367

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?

Upvotes: 1

Views: 623

Answers (3)

wrkwrk
wrkwrk

Reputation: 2351

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:

Pass the location details by

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

And receive the Location details on the SecondActivity by

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

Upvotes: 2

reflective_mind
reflective_mind

Reputation: 1515

I'm not sure if I understand your scenario correctly as I can't see the whole structure.

First of all, you can only receive a broadcast intent when you registered the receiver properly. For that you have two options: a static and dynamic way.

You did that correctly in your onResume() method. This should work as long as the application is running, which called/registered the receiver.

If you want a more permanent solution, you should register it in a static way inside your AndroidManifest.xml. By doing that, the Android system knows that your app contains a broadcast receiver for the location data and can deliver the intent. So even after you reboot your device, the receiver is still working. The only thing required is, you already started the app containing the broadcast receiver at least once.

This is what you have to put into your AndroidManifest.xml inside the <application> element (of course, you have to replace the com.your.example.ACTION_LOCATION with your string accordingly).

<receiver android:name=".LocationBroadcastReceiver">
    <intent-filter>
        <action android:name="com.your.example.ACTION_LOCATION" />
    </intent-filter>
</receiver>

Since you explicitly specify LocationBroadcastReceiver in your manifest, you have to create the corresponding class too:

public class LocationBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
               // your code when intent is received
        }
}

If you do it this way, you no longer have to register the receiver in your code and you also don't have to create an instance of LocationBroadcastReceiver manually.

For more details on this, see here.

Upvotes: 0

Saveen
Saveen

Reputation: 4220

no need to call register receiver onResume.You can use also this way.

If you need to use Receiver onResume then need to unregister onPause.

And please check your locationchanged is working properly.

public class YourActivity extends AppCompatActivity {

private Location newLocation;

private BroadcastReceiver coordinateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
    try {
        newLocation.setLatitude(intent.getDoubleExtra("latitude", 0.0));
        newLocation.setLongitude(intent.getDoubleExtra("longitude", 0.0));
    } catch (Exception e) {
        e.printStackTrace();
    }

}

};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_activity);
    registerReceiver(coordinateReceiver, new IntentFilter(LocationService.ACTION_LOCATION));

}


 @Override
 protected void onDestroy() {
    super.onDestroy();

    try {
         unregisterReceiver(coordinateReceiver);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

Upvotes: 0

Related Questions