Поиск по сайту:

Уведомление Android, пример PendingIntent


Добро пожаловать в пример уведомлений Android с использованием android PendingIntent. В этом руководстве мы обсудим и реализуем PendingIntent и создадим Notification в нашем приложении.

Android PendingIntent

Android PendingIntent — это объект, обертывающий BroadcastReceiver или Service. Следовательно, PendingIntent использует следующие методы для обработки различных типов намерений:

  1. PendingIntent.getActivity(): получение PendingIntent для запуска действия
  2. PendingIntent.getBroadcast(): получение PendingIntent для выполнения широковещательной рассылки
  3. PendingIntent.getService(): получение PendingIntent для запуска службы

Пример реализации PendingIntent приведен ниже.

Intent intent = new Intent(this, SomeActivity.class);
 
// Creating a pending intent and wrapping our intent
PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
try {
    // Perform the operation associated with our pendingIntent
    pendingIntent.send();
} catch (PendingIntent.CanceledException e) {
    e.printStackTrace();
}

Операция, связанная с pendingIntent, выполняется с помощью метода send(). Параметры внутри метода getActivity() и их использование описаны ниже:

  1. this (context): это контекст, в котором PendingIntent запускает действие
  2. requestCode : \1 — это частный код запроса для отправителя, использованный в приведенном выше примере. Использование его позже с тем же методом снова вернет то же самое ожидающее намерение. Затем мы можем делать различные вещи, например отменять ожидающее намерение. с отменой() и т. д.
  3. intent : Явный объект намерения запускаемой активности.
  4. flag : один из флагов PendingIntent, который мы использовали в приведенном выше примере, — FLAG_UPDATE_CURRENT. В этом говорится, что если предыдущий PendingIntent уже существует, то текущий обновит его последним намерением. Есть много других флагов, таких как FLAG_CANCEL_CURRENT и т. д.

Android-уведомление

Класс Android Toast предоставляет удобный способ отображения предупреждений пользователям, но проблема в том, что эти предупреждения не являются постоянными, что означает, что предупреждение мигает на экране в течение нескольких секунд, а затем исчезает. Уведомление Android заполняет пустоту в таких ситуациях. Уведомление Android — это сообщение, которое мы можем отобразить пользователю за пределами обычного пользовательского интерфейса нашего приложения. Уведомления в Android создаются с использованием библиотеки NotificationCompat.

Создание Android-уведомления

Уведомление создается с использованием класса NotificationManager, как показано ниже:

NotificationManager notificationManager = (NotificationManager) 
  getSystemService(NOTIFICATION_SERVICE); 

Notification.Builder предоставляет интерфейс компоновщика для создания объекта Notification, как показано ниже:

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);

Методы уведомлений Android

Мы можем установить свойства уведомлений для этого объекта построителя. Некоторые из часто используемых методов и их описания приведены ниже.

  1. Notification build() : Combines all of the options that have been set and returns a new Notification object

  2. NotificationCompat.Builder setAutoCancel (boolean autoCancel) : Setting this flag will make it such that the notification is automatically canceled when the user clicks it in the panel

  3. NotificationCompat.Builder setContent (RemoteViews views) : Supplies a custom RemoteViews to use instead of the standard one

  4. NotificationCompat.Builder setContentInfo (CharSequence info) : Sets the large text at the right-hand side of the notification

  5. NotificationCompat.Builder setContentIntent (PendingIntent intent) : Supplies a PendingIntent to send when the notification is clicked

  6. NotificationCompat.Builder setContentText (CharSequence text) : Sets the text (second row) of the notification, in a standard notification

  7. NotificationCompat.Builder setContentTitle (CharSequence title) : Sets the text (first row) of the notification, in a standard notification

  8. NotificationCompat.Builder setDefaults (int defaults) : Sets the default notification options that will be used. An example is;

    mBuilder.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND)
    
  9. NotificationCompat.Builder setLargeIcon (Bitmap icon) : Sets the large icon that is shown in the ticker and notification

  10. NotificationCompat.Builder setNumber (int number) : Sets the large number at the right-hand side of the notification

  11. NotificationCompat.Builder setOngoing (boolean ongoing) : Sets whether this is an ongoing notification

  12. NotificationCompat.Builder setSmallIcon (int icon) : Sets the small icon to use in the notification layouts

  13. NotificationCompat.Builder setStyle (NotificationCompat.Style style) : Adds a rich notification style to be applied at build time

  14. NotificationCompat.Builder setTicker (CharSequence tickerText) : Sets the text that is displayed in the status bar when the notification first arrives

  15. NotificationCompat.Builder setVibrate (long[] pattern) : Sets the vibration pattern to use

  16. NotificationCompat.Builder setWhen (long when) : Sets the time that the event occurred. Notifications in the panel are sorted by this time

Кнопка уведомлений Android и стили

Notification.Builder позволяет добавить к уведомлению до трех кнопок с определяемыми действиями. Android 4.1 и более поздние версии поддерживают расширяемые уведомления, которые показывают увеличенное изображение уведомления, когда оно развернуто. Есть три стиля, которые можно использовать с большим представлением: стиль большого изображения, стиль большого текста, стиль папки «Входящие».

Отмена уведомления Android

Мы также можем вызвать cancel() для определенного идентификатора уведомления в NotificationManager. Вызов метода cancelAll() удаляет все отправленные ранее уведомления. В этом руководстве мы создадим приложение, которое оборачивает намерение, которое будет просматривать веб-страницу, в PendingIntent. Этот PendingIntent будет срабатывать при нажатии на уведомление. Также мы добавим функцию, которая также программно отменяет уведомление.

Структура проекта примера уведомления Android

Пример уведомления Android

Activity_main.xml — это базовый относительный макет с двумя кнопками: одна для создания уведомления, а другая — для его отмены. activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.journaldev.notifications.MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="CREATE NOTIFICATION"
        android:id="@+id/button"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="CANCEL NOTIFICATION"
        android:id="@+id/button2"
        android:layout_below="@+id/button"
        android:layout_alignRight="@+id/button"
        android:layout_alignEnd="@+id/button"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
</RelativeLayout>

MainActivity.java приведен ниже.

package com.journaldev.notifications;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.app.NotificationCompat;
import android.widget.Toast;

import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.inject(this);
    }

    @OnClick(R.id.button)
    public void sendNotification() {

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setSmallIcon(android.R.drawable.ic_dialog_alert);
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.journaldev.com/"));
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
        builder.setContentIntent(pendingIntent);
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
        builder.setContentTitle("Notifications Title");
        builder.setContentText("Your notification content here.");
        builder.setSubText("Tap to view the website.");

        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        // Will display the notification in the notification bar
        notificationManager.notify(1, builder.build());
    }

    @OnClick(R.id.button2)
    public void cancelNotification() {

        String ns = Context.NOTIFICATION_SERVICE;
        NotificationManager nMgr = (NotificationManager) getApplicationContext().getSystemService(ns);
        nMgr.cancel(1);
    }
}

Скачать Android PendingIntent и проект уведомлений

Использованная литература:

  • https://developer.android.com/reference/android/app/PendingIntent.html
  • https://developer.android.com/guide/topics/ui/notifiers/notifications.html