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);
startNotificationServiceIntent
.putExtra("Title", title)
.putExtra("Text", text)
.putExtra("Millis", millis)
.putExtra("IsImportant", isImportant);

startService(startNotificationServiceIntent);


And this is the onStartCommand right now:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
displayNotification(/*Currently empty*/);
stopSelf();
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)
.setContentTitle(title)
.setContentText(text)
.setSmallIcon(R.drawable.attention)
.setColor(getResources().getColor(R.color.colorPrimary))
.setVibrate(new long[]{0, VibrationLongMillis, VibrationLongMillis, VibrationLongMillis})
.setSound(uri)
.setContentIntent(notificationPendingIntent)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setStyle(new NotificationCompat.BigTextStyle().bigText(text));

if (isImportant) {
notification.setPriority(NotificationCompat.PRIORITY_HIGH);
}


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:

@Override
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);
    stopSelf();
    return super.onStartCommand(intent, flags, startId);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download