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使用以下方法来处理不同类型的意图:
PendingIntent.getActivity()
: Retrieve a PendingIntent to start an ActivityPendingIntent.getActivity()
:检索PendingIntent以启动活动PendingIntent.getBroadcast()
: Retrieve a PendingIntent to perform a BroadcastPendingIntent.getBroadcast()
:检索要执行广播的PendingIntentPendingIntent.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 pendingIntent
pendingIntent.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()方法内部的参数及其用法:
- this (context) : This is the context in which the PendingIntent starts the activity 这 (上下文):这是PendingIntent在其中启动活动的上下文
- 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()取消待处理的意图等。
- intent : Explicit intent object of the activity to be launched 意图 :要启动的活动的明确意图对象
- 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.
我们可以在此构建器对象上设置通知属性。 下面给出一些常用方法及其说明。
- Notification build() : Combines all of the options that have been set and returns a new Notification object Notification build() :组合所有已设置的选项并返回一个新的Notification对象
- 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 NotificationCompat.Builder setAutoCancel(boolean autoCancel) :设置此标志将使其生效,以便当用户在面板中单击通知时自动取消通知
- NotificationCompat.Builder setContent (RemoteViews views) : Supplies a custom RemoteViews to use instead of the standard one NotificationCompat.Builder setContent(RemoteViews视图) :提供自定义的RemoteView来代替标准视图使用
- NotificationCompat.Builder setContentInfo (CharSequence info) : Sets the large text at the right-hand side of the notification NotificationCompat.Builder setContentInfo(CharSequence info) :在通知的右侧设置大文本
- NotificationCompat.Builder setContentIntent (PendingIntent intent) : Supplies a PendingIntent to send when the notification is clicked NotificationCompat.Builder setContentIntent(PendingIntent intent) :提供单击通知时发送的PendingIntent
- NotificationCompat.Builder setContentText (CharSequence text) : Sets the text (second row) of the notification, in a standard notification NotificationCompat.Builder setContentText(CharSequence文本) :在标准通知中设置通知的文本(第二行)
- NotificationCompat.Builder setContentTitle (CharSequence title) : Sets the text (first row) of the notification, in a standard notification NotificationCompat.Builder setContentTitle(CharSequence标题) :在标准通知中设置通知的文本(第一行)
- NotificationCompat.Builder setDefaults (int defaults) : Sets the default notification options that will be used. An example is;
NotificationCompat.Builder setDefaults(默认值) :设置将使用的默认通知选项。 一个例子是;mBuilder.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND)
- NotificationCompat.Builder setLargeIcon (Bitmap icon) : Sets the large icon that is shown in the ticker and notification NotificationCompat.Builder setLargeIcon(位图图标) :设置在代码和通知中显示的大图标
- NotificationCompat.Builder setNumber (int number) : Sets the large number at the right-hand side of the notification NotificationCompat.Builder setNumber(int number) :在通知的右侧设置大数字
- NotificationCompat.Builder setOngoing (boolean ongoing) : Sets whether this is an ongoing notification NotificationCompat.Builder setOngoing(布尔正在进行) :设置这是否为正在进行的通知
- NotificationCompat.Builder setSmallIcon (int icon) : Sets the small icon to use in the notification layouts NotificationCompat.Builder setSmallIcon(int图标) :设置要在通知布局中使用的小图标
- NotificationCompat.Builder setStyle (NotificationCompat.Style style) : Adds a rich notification style to be applied at build time NotificationCompat.Builder setStyle(NotificationCompat.Style样式) :添加丰富的通知样式以在构建时应用
- NotificationCompat.Builder setTicker (CharSequence tickerText) : Sets the text that is displayed in the status bar when the notification first arrives NotificationCompat.Builder setTicker(CharSequence tickerText) :设置通知首次到达时在状态栏中显示的文本
- NotificationCompat.Builder setVibrate (long[] pattern) : Sets the vibration pattern to use NotificationCompat.Builder setVibrate(long []模式) :设置要使用的振动模式
- NotificationCompat.Builder setWhen (long when) : Sets the time that the event occurred. Notifications in the panel are sorted by this time NotificationCompat.Builder setWhen(较长时间) :设置事件发生的时间。 面板中的通知此时已排序
Android通知按钮和样式 ()
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">
<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>
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 {
@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);
}
}
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 。
References:
参考文献:
- https://developer.android.com/reference/android/app/PendingIntent.html https://developer.android.com/reference/android/app/PendingIntent.html
- https://developer.android.com/guide/topics/ui/notifiers/notifications.html https://developer.android.com/guide/topics/ui/notifiers/notifications.html
翻译自: https://www.journaldev.com/10463/android-notification-pendingintent