Reputation: 64
I am implementing FCM(Firebase cloud messaging) for push notifications. I could get push notification from the server using my service class successfully. But, how do I send data(messages) from the service class to the activity?
Service.java
public class Service extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
sendNotification(remoteMessage.getNotification().getBody());
}
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, FCMActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri =RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new
NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Firebase Push Notification")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
notificationBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
notificationBuilder.setLights(Color.RED, 1000, 300);
NotificationManager notificationManager =
(NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}
FCMActivity.java
public class FCMActivity extends AppCompatActivity {
private TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fcm);
mTextView = (TextView) findViewById(R.id.txt);
}
}
Upvotes: 1
Views: 618
Reputation: 4775
There are several options, among those are:
Register a BroadcastReceiver
inside your Activity with an IntentFilter
for your custom action (action is just a String
identifier for a broadcast message type), and send the broadcast from service using LocalBroadcastManager.getInstance().sendBroadcast(Intent intent)
method
Use an event bus, for example the very popular GreenRobot EventBus library. See https://github.com/greenrobot/EventBus#eventbus-in-3-steps for explanation.
Both of these options require registering and unregistering a listener / receiver inside your Activity, which is best done in onResume
/onPause
for events that should trigger UI changes.
Additionally, you can bind to the service from your Activity.
Upvotes: 3
Reputation: 759
You should use IBinder
in your service and ServiceConnection
in your Activity
Upvotes: 0