Как именно использовать Notification.Builder

98

Я обнаружил, что использую устаревший метод для noficitations (notification.setLatestEventInfo())

Он говорит, что использует Notification.Builder.

  • Как его использовать?

Когда я пытаюсь создать новый экземпляр, он сообщает мне:

Notification.Builder cannot be resolved to a type
Теги:
notifications
deprecated

11 ответов

82
Лучший ответ

Это в API 11, поэтому, если вы разрабатываете что-либо раньше, чем 3.0, вы должны продолжать использовать старый API.

Обновить: класс NotificationCompat.Builder добавлен в пакет поддержки, поэтому мы можем использовать его для поддержки уровня API v4 и выше:

http://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html

  • 0
    Благодарю. Интересно, почему это не упоминает об этом на самих страницах функций
  • 15
    Да, предупреждение об устаревании, на мой взгляд, немного преждевременно, но что я знаю.
158

Notification.Builder API 11 или NotificationCompat.Builder API 1

Это пример использования.

Intent notificationIntent = new Intent(ctx, YourClass.class);
PendingIntent contentIntent = PendingIntent.getActivity(ctx,
        YOUR_PI_REQ_CODE, notificationIntent,
        PendingIntent.FLAG_CANCEL_CURRENT);

NotificationManager nm = (NotificationManager) ctx
        .getSystemService(Context.NOTIFICATION_SERVICE);

Resources res = ctx.getResources();
Notification.Builder builder = new Notification.Builder(ctx);

builder.setContentIntent(contentIntent)
            .setSmallIcon(R.drawable.some_img)
            .setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.some_big_img))
            .setTicker(res.getString(R.string.your_ticker))
            .setWhen(System.currentTimeMillis())
            .setAutoCancel(true)
            .setContentTitle(res.getString(R.string.your_notif_title))
            .setContentText(res.getString(R.string.your_notif_text));
Notification n = builder.build();

nm.notify(YOUR_NOTIF_ID, n);
  • 13
    Я вижу, что есть метод сделать это в пакете поддержки v4: NotificationCompat.Builder
  • 6
    Я думаю, что кто-то должен сказать Google, что у него есть серьезные опечатки на странице документации Notification.Builder . Я делал то, что они говорили, но это не имело никакого смысла. Я прихожу сюда и вижу, что это не так. Я действительно ценю ваш ответ, поскольку он заставил меня осознать ошибку, допущенную в документе.
Показать ещё 10 комментариев
65

в дополнение к выбранному ответу здесь приведен пример кода класса NotificationCompat.Builder из Исходные трюки:

// Add app running notification  

    private void addNotification() {



    NotificationCompat.Builder builder =  
            new NotificationCompat.Builder(this)  
            .setSmallIcon(R.drawable.ic_launcher)  
            .setContentTitle("Notifications Example")  
            .setContentText("This is a test notification");  

    Intent notificationIntent = new Intent(this, MainActivity.class);  
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,   
            PendingIntent.FLAG_UPDATE_CURRENT);  
    builder.setContentIntent(contentIntent);  

    // Add as notification  
    NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);  
    manager.notify(FM_NOTIFICATION_ID, builder.build());  
}  

// Remove notification  
private void removeNotification() {  
    NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);  
    manager.cancel(FM_NOTIFICATION_ID);  
}  
  • 4
    Первый код, использующий новый конструктор Compat, который действительно сработал. Отлично сработано!
  • 0
    У меня тоже хорошо получилось. Два замечания: 1) вам нужно сделать иконку 32x32 для "ic_launcher". Белый рисунок на прозрачном фоне 2) вам нужно определить случайное число для int FM_NOTIFICATION_ID = [yourFavoriteRandom];
Показать ещё 1 комментарий
4

Notification Builder предназначен исключительно для Android API уровня 11 и выше (Android 3.0 и выше).

Следовательно, если вы не нацеливаете на планшеты Honeycomb, вы не должны использовать построитель уведомлений, а скорее следуйте более старым методам создания уведомлений, например следующим example.

  • 4
    Вы можете использовать библиотеку совместимости, чтобы вы могли использовать ее в API 4 или выше.
2

UPDATE android-N (march-2016)

Подробнее см. Уведомления об обновлениях".

  • Прямой ответ
  • Связанные уведомления
  • Пользовательские представления

Android N также позволяет связать похожие уведомления, чтобы они отображались как одно уведомление. Чтобы сделать это возможным, Android N использует существующий метод NotificationCompat.Builder.setGroup(). Пользователи могут расширять каждое из уведомлений и выполнять такие действия, как ответ и отклонять каждое из уведомлений, отдельно от уведомление оттенок.

Это уже существующий образец, который показывает простой сервис, который отправляет уведомления с помощью NotificationCompat. Каждый непрочитанный разговор из пользователь отправляется как отдельное уведомление.

Этот образец обновлен, чтобы воспользоваться новым уведомлением функции доступны в Android N.

пример кода.

  • 0
    Привет, вы можете сказать, как этот метод работает Android 6.0, когда мы используем downloader_library. Я нахожусь на Eclipse SDK - 25.1.7 || ADT 23.0.X к сожалению || Библиотека расширений Google APK и Библиотека лицензирования, оба 1.0
2

У меня возникли проблемы с созданием уведомлений (только для Android 4.0+).  Эта ссылка показала мне, что я делаю неправильно, и говорит следующее:

Required notification contents

A Notification object must contain the following:

A small icon, set by setSmallIcon()
A title, set by setContentTitle()
Detail text, set by setContentText()

В основном я отсутствовал один из них. Как основа для устранения неполадок с этим, убедитесь, что у вас есть все это, по крайней мере. Надеюсь, это спасет кого-то еще головную боль.

  • 0
    Поэтому, если вы подумаете: «Я найду икону позже», вы не получите уведомления-любви. Спасибо за это;)
1

Я использовал

Intent intent = new Intent(this, MainActivity.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);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0, notificationBuilder.build());
1

Он работает даже в API 8 вы можете использовать этот код:

 Notification n = 
   new Notification(R.drawable.yourownpicturehere, getString(R.string.noticeMe), 
System.currentTimeMillis());

PendingIntent i=PendingIntent.getActivity(this, 0,
             new Intent(this, NotifyActivity.class),
                               0);
n.setLatestEventInfo(getApplicationContext(), getString(R.string.title), getString(R.string.message), i);
n.number=++count;
n.flags |= Notification.FLAG_AUTO_CANCEL;
n.flags |= Notification.DEFAULT_SOUND;
n.flags |= Notification.DEFAULT_VIBRATE;
n.ledARGB = 0xff0000ff;
n.flags |= Notification.FLAG_SHOW_LIGHTS;

// Now invoke the Notification Service
String notifService = Context.NOTIFICATION_SERVICE;
NotificationManager mgr = 
   (NotificationManager) getSystemService(notifService);
mgr.notify(NOTIFICATION_ID, n);

Или я предлагаю следовать отличному tutorial об этом

1

В случае, если это помогает кому-то... У меня возникли проблемы с настройкой уведомлений с помощью пакета поддержки при тестировании более старых API. Я смог заставить их работать на более новом устройстве, но получил бы тестирование ошибок на старом устройстве. Что, наконец, заработало для меня, это удалить все импортные функции, связанные с функциями уведомления. В частности, NotificationCompat и TaskStackBuilder. Кажется, что при настройке моего кода вначале импортируются, добавленные из новой сборки, а не из пакета поддержки. Затем, когда я захотел реализовать эти элементы позже в eclipse, мне не было предложено импортировать их снова. Надеюсь, что это имеет смысл, и что это помогает кому-то другому:)

0

Автономный пример

Тот же метод, что и в этом ответе, но:

  • автономный: скопировать вставку, и он будет компилироваться и запускаться
  • с кнопкой, чтобы вы могли создать столько уведомлений, сколько хотите, и играть с идентификаторами намерений и уведомлений.

Источник:

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class Main extends Activity {
    private int i;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final Button button = new Button(this);
        button.setText("click me");
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final Notification notification = new Notification.Builder(Main.this)
                        /* Make app open when you click on the notification. */
                        .setContentIntent(PendingIntent.getActivity(
                                Main.this,
                                Main.this.i,
                                new Intent(Main.this, Main.class),
                                PendingIntent.FLAG_CANCEL_CURRENT))
                        .setContentTitle("title")
                        .setAutoCancel(true)
                        .setContentText(String.format("id = %d", Main.this.i))
                        // Starting on Android 5, only the alpha channel of the image matters.
                        // https://stackoverflow.com/a/35278871/895245
                        // `android.R.drawable` resources all seem suitable.
                        .setSmallIcon(android.R.drawable.star_on)
                        // Color of the background on which the alpha image wil drawn white.
                        .setColor(Color.RED)
                        .build();
                final NotificationManager notificationManager =
                        (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
                notificationManager.notify(Main.this.i, notification);
                // If the same ID were used twice, the second notification would replace the first one. 
                //notificationManager.notify(0, notification);
                Main.this.i++;
            }
        });
        this.setContentView(button);
    }
}

Протестировано в Android 22.

0
          // This is a working Notification
       private static final int NotificID=01;
   b= (Button) findViewById(R.id.btn);
    b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Notification notification=new       Notification.Builder(MainActivity.this)
                    .setContentTitle("Notification Title")
                    .setContentText("Notification Description")
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .build();
            NotificationManager notificationManager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
            notification.flags |=Notification.FLAG_AUTO_CANCEL;
            notificationManager.notify(NotificID,notification);


        }
    });
}

Ещё вопросы

Сообщество Overcoder
Наверх
Меню