如何在Android应用程序上显示通知?

时间:2016-08-14 04:38:55

标签: android android-notifications

当我的服务器返回特定值时,我需要显示通知。我有一个运行在android和taskschedule上的服务,每次向服务器发送请求时运行,当服务器返回正值时,我需要在celular显示器上显示消息,类似接收消息whatsapp(显示图标和显示通知)。有人有样品吗?

我试着这个:

.apply

但我的应用程序是作为服务运行的。

1 个答案:

答案 0 :(得分:0)

请使用Using Service to run background and create notification

private void processStartNotification() {
        // Do something. For example, fetch fresh data from backend to create a rich notification?

        final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setContentTitle("Scheduled Notification")
                .setAutoCancel(true)
                .setColor(getResources().getColor(R.color.colorAccent))
                .setContentText("This notification has been triggered by Notification Service")
                .setSmallIcon(R.drawable.notification_icon);

        PendingIntent pendingIntent = PendingIntent.getActivity(this,
                NOTIFICATION_ID,
                new Intent(this, NotificationActivity.class),
                PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(pendingIntent);
        builder.setDeleteIntent(NotificationEventReceiver.getDeleteIntent(this));

        final NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        manager.notify(NOTIFICATION_ID, builder.build());
    }