I\'m trying to send string from service to my main activity with broadcast. I have read in a few forums that there are 2 ways to use broadcast. One is to register the activi
You can use LocalBroadcastManager to achieve what you want. Like in your service call this method when you want to send the data.
private static void sendMessageToActivity(String msg) {
Intent intent = new Intent("intentKey");
// You can also include some extra data.
intent.putExtra("key", msg);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
In your Activity
register a Receiver in onCreate()
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mMessageReceiver, new IntentFilter("intentKey"));
And out of onCreate() this code.
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
String message = intent.getStringExtra("key");
tvStatus.setText(message);
// Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
};