将数据发送到通知

时间:2017-07-25 20:12:04

标签: android android-notifications

我正在开发一个应用程序,您可以在其中制作自己的通知(仅为了好玩)。您可以(几乎)以任何方式自定义它们。

我的问题是:我不知道如何将主要活动中的数据提供给我的通知服务。

这就是我现在使用的Intent的样子:

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

            startService(startNotificationServiceIntent);

现在这是onStartCommand:

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

这是我用来创建通知的方法(displayNotification):

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

}

1 个答案:

答案 0 :(得分:0)

您只需要传递Intent中的信息(正如您已经在做的那样),然后在您的服务中阅读,如下所示:

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