2Simpel 2Simpel - 3 years ago 83
Android Question

Sending data to a notification

I'm currently working on an app where you can make your own notifications (Just for the fun). You can customize them in (almost) any way.

My problem is: I don't know how to get the data from the main activity to my notification service.

This is how the Intent that I'm using right now is looking like:

Intent startNotificationServiceIntent = new Intent(MainActivity.this, Notification.class);
.putExtra("Title", title)
.putExtra("Text", text)
.putExtra("Millis", millis)
.putExtra("IsImportant", isImportant);


And this is the onStartCommand right now:

public int onStartCommand(Intent intent, int flags, int startId) {
displayNotification(/*Currently empty*/);
return super.onStartCommand(intent, flags, startId);

And this is the method (displayNotification) that I'm using to create the notification:

private void displayNotification(String title, String text, long VibrationLongMillis, boolean isImportant) {
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent notificationPendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

NotificationCompat.Builder notification = new NotificationCompat.Builder(this)
.setVibrate(new long[]{0, VibrationLongMillis, VibrationLongMillis, VibrationLongMillis})
.setStyle(new NotificationCompat.BigTextStyle().bigText(text));

if (isImportant) {

NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, notification.build());


Answer Source

You just need to pass the information in the Intent (as you are already doing it) and then read it in your Service like this:

public int onStartCommand(Intent intent, int flags, int startId) {
    String title = intent.getStringExtra("Title");
    /* Do here the same for the other parameters */
    displayNotification(title, text, vibrationLongMillis, isImportant);
    return super.onStartCommand(intent, flags, startId);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download