Welcome to Android Notification Example using android PendingIntent. In this tutorial we’re going to discuss and implement PendingIntent and build Notification in our application.

欢迎使用Android PendingIntent的Android通知示例。 在本教程中,我们将讨论和实现PendingIntent并在应用程序中构建Notification

Android PendingIntent (Android PendingIntent)

Android PendingIntent is an object that wraps up an intent object and it specifies an action to be taken place in future. In other words, PendingIntent lets us pass a future Intent to another application and allow that application to execute that Intent as if it had the same permissions as our application, whether or not our application is still around when the Intent is eventually invoked.

Android PendingIntent是包装intent对象的对象,它指定将来要执行的操作。 换句话说, PendingIntent允许我们将将来的Intent传递给另一个应用程序,并允许该应用程序执行该Intent,就好像它具有与我们的应用程序相同的权限一样,无论最终调用该Intent时我们的应用程序是否还在。

A PendingIntent is generally used in cases were an AlarmManager needs to be executed or for Notification (that we’ll implement later in this tutorial). A PendingIntent provides a means for applications to work, even after their process exits.

PendingIntent通常用于需要执行AlarmManager或用于Notification的情况 (我们将在本教程的稍后部分实现)。 PendingIntent提供了一种使应用程序工作的方法,即使它们退出了进程也是如此。

For security reasons, the base Intent that is supplied to the PendingIntent must have the component name explicitly set to ensure it is ultimately sent there and nowhere else. Each explicit intent is supposed to be handled by a specific app component like Activity, BroadcastReceiver or a Service. Hence PendingIntent uses the following methods to handle the different types of intents:

出于安全原因,提供给PendingIntent的基本Intent必须具有明确设置的组件名称,以确保最终将其发送到该地址。 每个明确的意图都应该由特定的应用程序组件(例如Activity, BroadcastReceiver或Service)处理。 因此,PendingIntent使用以下方法来处理不同类型的意图:

  1. PendingIntent.getActivity() : Retrieve a PendingIntent to start an ActivityPendingIntent.getActivity() :检索PendingIntent以启动活动
  2. PendingIntent.getBroadcast() : Retrieve a PendingIntent to perform a BroadcastPendingIntent.getBroadcast() :检索要执行广播的PendingIntent
  3. PendingIntent.getService() : Retrieve a PendingIntent to start a ServicePendingIntent.getService() :检索PendingIntent以启动服务

An example implementation of PendingIntent is given below.

下面给出了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 pendingIntentpendingIntent.send();
} catch (PendingIntent.CanceledException e) {e.printStackTrace();
}

The operation associated with the pendingIntent is executed using the send() method.

使用send()方法执行与未决Intent相关的操作。

The parameters inside the getActivity() method and there usages are described below :

下面介绍了getActivity()方法内部的参数及其用法:

  1. this (context) : This is the context in which the PendingIntent starts the activity (上下文):这是PendingIntent在其中启动活动的上下文
  2. requestCode : “1” is the private request code for the sender used in the above example. Using it later with the same method again will get back the same pending intent. Then we can do various things like cancelling the pending intent with cancel(), etc.requestCode :“ 1”是在以上示例中使用的发件人的私有请求代码。 以后再次以相同的方法使用它会返回相同的未决意图。 然后,我们可以执行各种操作,例如使用cancel()取消待处理的意图等。
  3. intent : Explicit intent object of the activity to be launched意图 :要启动的活动的明确意图对象
  4. flag : One of the PendingIntent flag that we’ve used in the above example is FLAG_UPDATE_CURRENT. This one states that if a previous PendingIntent already exists, then the current one will update it with the latest intent. There are many other flags like FLAG_CANCEL_CURRENT etc.flag :在上面的示例中使用的PendingIntent标志之一是FLAG_UPDATE_CURRENT 。 这说明如果先前的PendingIntent已经存在,那么当前的PendingIntent将使用最新的Intent更新它。 还有许多其他标志,例如FLAG_CANCEL_CURRENT等。

Android通知 (Android Notification)

Android Toast class provides a handy way to show users alerts but problem is that these alerts are not persistent which means alert flashes on the screen for a few seconds and then disappears.

Android Toast类提供了一种方便的方式来向用户显示警报,但问题是这些警报不是持久性的,这意味着警报在屏幕上闪烁几秒钟然后消失。

Android notification message fills up the void in such situations. Android notification is a message that we can display to the user outside of our application’s normal UI. Notifications in android are built using NotificationCompat library.

在这种情况下,Android通知消息会填补空白。 Android通知是一条消息,我们可以在应用程序的常规UI之外向用户显示。 android中的NotificationCompat是使用NotificationCompat库构建的。

创建Android通知 (Creating Android Notification)

A Notification is created using the NotificationManager class as shown below:

使用NotificationManager类创建一个NotificationManager ,如下所示:

NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

The Notification.Builder provides an builder interface to create an Notification object as shown below:

Notification.Builder提供了一个构建器接口来创建Notification对象,如下所示:

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

Android通知方法 (Android Notification Methods)

We can set the notification properties on this builder object. Some of the frequently used methods and there descriptions are given below.

我们可以在此构建器对象上设置通知属性。 下面给出一些常用方法及其说明。

  1. Notification build() : Combines all of the options that have been set and returns a new Notification objectNotification build() :组合所有已设置的选项并返回一个新的Notification对象
  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 panelNotificationCompat.Builder setAutoCancel(boolean autoCancel) :设置此标志将使其生效,以便当用户在面板中单击通知时自动取消通知
  3. NotificationCompat.Builder setContent (RemoteViews views) : Supplies a custom RemoteViews to use instead of the standard oneNotificationCompat.Builder setContent(RemoteViews视图) :提供自定义的RemoteView来代替标准视图使用
  4. NotificationCompat.Builder setContentInfo (CharSequence info) : Sets the large text at the right-hand side of the notificationNotificationCompat.Builder setContentInfo(CharSequence info) :在通知的右侧设置大文本
  5. NotificationCompat.Builder setContentIntent (PendingIntent intent) : Supplies a PendingIntent to send when the notification is clickedNotificationCompat.Builder setContentIntent(PendingIntent intent) :提供单击通知时发送的PendingIntent
  6. NotificationCompat.Builder setContentText (CharSequence text) : Sets the text (second row) of the notification, in a standard notificationNotificationCompat.Builder setContentText(CharSequence文本) :在标准通知中设置通知的文本(第二行)
  7. NotificationCompat.Builder setContentTitle (CharSequence title) : Sets the text (first row) of the notification, in a standard notificationNotificationCompat.Builder setContentTitle(CharSequence标题) :在标准通知中设置通知的文本(第一行)
  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)

    NotificationCompat.Builder setDefaults(默认值) :设置将使用的默认通知选项。 一个例子是;

  9. NotificationCompat.Builder setLargeIcon (Bitmap icon) : Sets the large icon that is shown in the ticker and notificationNotificationCompat.Builder setLargeIcon(位图图标) :设置在代码和通知中显示的大图标
  10. NotificationCompat.Builder setNumber (int number) : Sets the large number at the right-hand side of the notificationNotificationCompat.Builder setNumber(int number) :在通知的右侧设置大数字
  11. NotificationCompat.Builder setOngoing (boolean ongoing) : Sets whether this is an ongoing notificationNotificationCompat.Builder setOngoing(布尔正在进行) :设置这是否为正在进行的通知
  12. NotificationCompat.Builder setSmallIcon (int icon) : Sets the small icon to use in the notification layoutsNotificationCompat.Builder setSmallIcon(int图标) :设置要在通知布局中使用的小图标
  13. NotificationCompat.Builder setStyle (NotificationCompat.Style style) : Adds a rich notification style to be applied at build timeNotificationCompat.Builder setStyle(NotificationCompat.Style样式) :添加丰富的通知样式以在构建时应用
  14. NotificationCompat.Builder setTicker (CharSequence tickerText) : Sets the text that is displayed in the status bar when the notification first arrivesNotificationCompat.Builder setTicker(CharSequence tickerText) :设置通知首次到达时在状态栏中显示的文本
  15. NotificationCompat.Builder setVibrate (long[] pattern) : Sets the vibration pattern to useNotificationCompat.Builder setVibrate(long []模式) :设置要使用的振动模式
  16. NotificationCompat.Builder setWhen (long when) : Sets the time that the event occurred. Notifications in the panel are sorted by this timeNotificationCompat.Builder setWhen(较长时间) :设置事件发生的时间。 面板中的通知此时已排序

Android通知按钮和样式 (Android Notification Button and Styles)

The Notification.Builder allows you to add up to three buttons with definable actions to the notification.
Android 4.1 and above support expandable notifications which shows a big view of the notification when it is expanded. There are three styles that can be used with the big view: big picture style, big text style, Inbox style.

Notification.Builder允许您最多添加三个带有可定义通知操作的按钮。
Android 4.1及更高版本支持可扩展通知,该通知可在扩展时显示较大的通知。 大视图可以使用三种样式: 大图片样式大文本样式收件箱样式

取消Android通知 (Cancelling Android Notification)

We can also call the cancel() for a specific notification ID on the NotificationManager. The cancelAll() method call removes all of the notifications you previously issued.

我们还可以在NotificationManager上为特定的通知ID调用cancel()cancelAll()方法调用将删除您先前发出的所有通知。

In this tutorial we’ll create an application that wraps an intent that would view a webpage, into a PendingIntent. That PendingIntent would fire when the notification is tapped upon. Also we’ll add the feature that cancels the notification programmatically too.

在本教程中,我们将创建一个将将查看网页的意图包装到PendingIntent中的应用程序。 当点击通知时,该PendingIntent将触发。 此外,我们还将添加以编程方式取消通知的功能。

Android通知示例项目结构 (Android Notification Example Project Structure)

Android通知示例 (Android Notification Example)

The activity_main.xml is a basic relative layout with two buttons : One to create a notification and the other to cancel it.

activity_main.xml是具有两个按钮的基本相对布局:一个用于创建通知,另一个用于取消通知。

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"><Buttonandroid: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" /><Buttonandroid: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>

The MainActivity.java is given below.

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 {@Overrideprotected 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 barnotificationManager.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);}
}

In the above code we’ve passed an intent of this website into the PendingIntent. The notificationId is set to 1 and it’s used to build the notification and cancel it.

在上面的代码中,我们已经将该网站的意图传递给了PendingIntent。 notificationId设置为1,用于构建通知并取消通知。

The output of the app in action is given below.

实际应用的输出如下。

This brings an end to android notification using PendingIntent tutorial. You can download the Android Notification Project from the link below.

使用PendingIntent教程结束了Android通知。 您可以从下面的链接下载Android Notification Project

Download Android PendingIntent and Notifications Project下载Android PendingIntent和Notifications项目

References:

参考文献:

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

翻译自: https://www.journaldev.com/10463/android-notification-pendingintent

Android通知,PendingIntent示例相关推荐

  1. android Intent PendingIntent的区别

    含义:intent英文意思是意图,pending表示即将发生或来临的事情.  PendingIntent这个类用于处理即将发生的事情.比如在通知Notification中用于跳转页面,但不是马上跳转. ...

  2. android activity 被notification启动,Android通知Notification全面剖析

    原标题:Android通知Notification全面剖析 通知 通知是您可以在应用的常规 UI 外部向用户显示的消息.当您告知系统发出通知时,它将先以图标的形式显示在通知区域中.用户可以打开抽屉式通 ...

  3. Android通知频道,通知点

    In this tutorial, we'll be looking into how the introduction of Android Oreo has brought a drastic c ...

  4. Android通知怎么实现?Android开发如何操作相机和相册?

    Android通知怎么实现?Android开发如何操作相机和相册? 前言 八.Android通知怎么实现?Android开发如何操作相机和相册? 8.1 通知介绍 8.2 通知的基本用法 8.3 An ...

  5. 20_Android中apk安装器,通过WebView来load进一个页面,Android通知,程序退出自动杀死进程,通过输入包名的方式杀死进程

     场景:实现安装一个apk应用程序的过程.界面如下: 编写如下应用,应用结构如下: <RelativeLayout xmlns:android="http://schemas.an ...

  6. xamarin android 通知,在 Xamarin.Android 中使用 Notification.Builder 构建通知

    0 背景 在 Android 4.0 以后,系统支持一种更先进的 Notification.Builder 类来发送通知.但 Xamarin 文档含糊其辞,多方搜索无果,遂决定自己摸索. 之前的代码: ...

  7. android通知悬浮通知_Android通知直接回覆

    android通知悬浮通知 Android Notification Direct Reply action lets us reply to the notification message, it ...

  8. Android通知——Notification

    Android通知--Notification 创建通道 在显示通知之前必须先设置通道,这是必须前提. 可以在此对此通道的通知进行基本的设置,例如是否显示呼吸灯.是否震动.优先级等. 代码大概长这样: ...

  9. Android通知系统源码解析

    Android通知系统源码解析 1. 概述 2. 流程图 2.1. 发送通知流程图 3. 源码解析 3.1. 使用通知--APP进程 3.1.1. 创建通知: 3.1.2. 发送(更新)通知: 3.1 ...

最新文章

  1. Entity Framework教程
  2. PyTorch随笔-0
  3. 经典C语言程序100例之九九
  4. android 监听屏幕是否锁屏
  5. SQLAlchemy 一些基本操作
  6. Linux进程间通信方式--本地socket
  7. c51编程语言基础习题,《单片机基础》练习题及答案
  8. 使用 XML Schema 定义元素的基本知识--1
  9. jsp过滤器一点小结
  10. Apollo 6.0 QP(二次规划)算法解析
  11. adguard home上网慢_如何正确使用smartdns搭配adguardhome, 优选dns并去除广告
  12. 如何在电脑上开启2个微信(如何进行应用分身)
  13. Mac连局域网打印机
  14. android学习code3 布局上
  15. 想当年我拿着两把西瓜刀……
  16. 备份恢复Lesson 10. Restore and Recovery Concepts
  17. B/S文件上传下载解决方案
  18. 墙裂推荐--几个Jupyter Notebook 超实用插件(一)
  19. 安装好office套件以后,右键新建中没有Word、Excel、PPT等怎么办
  20. 工业革命的秋之涟漪(三):飞桨,划行在智能经济之海

热门文章

  1. Delphi学习之函数 ⑨汉字拼音功能函数
  2. 狼来了!中国房地产的实质--比喻太生动了
  3. [转载] Python字典中items()和iteritems()区别
  4. FPGA芯片手册阅读技巧
  5. 面向对象及os模块、socket模块
  6. oracle误删除记录或者表的处理方法
  7. DrawerLayout和NavigationView的简单实用
  8. Unity3D AssetBundle相关
  9. ios开发-Object-C可变参数函数
  10. 通过 powershell 配置 IIS