Android通知,PendingIntent示例

本文详细介绍了如何在Android中使用PendingIntent创建和管理通知。PendingIntent是一个对象,用于封装Intent,允许其他应用以相同权限执行该Intent。文章涵盖了创建PendingIntent的方法,包括启动Activity、广播和Service。同时,讲解了Android通知的创建、方法和常用属性,如setAutoCancel、setContentIntent等。此外,还展示了如何添加通知按钮和风格,以及如何取消通知。最后,提供了一个包含创建和取消通知功能的示例项目结构和代码。
摘要由CSDN通过智能技术生成

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 Activity

    PendingIntent.getActivity() :检索PendingIntent以启动活动
  2. PendingIntent.getBroadcast() : Retrieve a PendingIntent to perform a Broadcast

    PendingIntent.getBroadcast() :检索要执行广播的PendingIntent
  3. PendingIntent.getService() : Retrieve a PendingIntent to start a Service

    PendingIntent.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()方法内部的参数及其用法:

  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 object

    Notification 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 panel

    NotificationCompat.Builder setAutoCancel(boolean autoCancel) :设置此标志将使其生效,以便当用户在面板中单击通知时自动取消通知
  3. NotificationCompat.Builder setContent (RemoteViews views) : Supplies a custom RemoteViews to use instead of the standard one

    NotificationCompat.Builder setContent(RemoteViews视图) :提供自定义的RemoteView来代替标准视图使用
  4. NotificationCompat.Builder setContentInfo (CharSequence info) : Sets the large text at the right-hand side of the notification

    NotificationCompat.Builder setContentInfo(CharSequence info) :在通知的右侧设置大文本
  5. NotificationCompat.Builder setContentIntent (PendingIntent intent) : Supplies a PendingIntent to send when the notification is clicked

    NotificationCompat.Builder setContentIntent(PendingIntent intent) :提供单击通知时发送的PendingIntent
  6. NotificationCompat.Builder setContentText (CharSequence text) : Sets the text (second row) of the notification, in a standard notification

    NotificationCompat.Builder setContentText(CharSequence文本) :在标准通知中设置通知的文本(第二行)
  7. NotificationCompat.Builder setContentTitle (CharSequence title) : Sets the text (first row) of the notification, in a standard notification

    NotificationCompat.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 notification

    NotificationCompat.Builder setLargeIcon(位图图标) :设置在代码和通知中显示的大图标
  10. NotificationCompat.Builder setNumber (int number) : Sets the large number at the right-hand side of the notification

    NotificationCompat.Builder setNumber(int number) :在通知的右侧设置大数字
  11. NotificationCompat.Builder setOngoing (boolean ongoing) : Sets whether this is an ongoing notification

    NotificationCompat.Builder setOngoing(布尔正在进行) :设置这是否为正在进行的通知
  12. NotificationCompat.Builder setSmallIcon (int icon) : Sets the small icon to use in the notification layouts

    NotificationCompat.Builder setSmallIcon(int图标) :设置要在通知布局中使用的小图标
  13. NotificationCompat.Builder setStyle (NotificationCompat.Style style) : Adds a rich notification style to be applied at build time

    NotificationCompat.Builder setStyle(NotificationCompat.Style样式) :添加丰富的通知样式以在构建时应用
  14. 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) :设置通知首次到达时在状态栏中显示的文本
  15. NotificationCompat.Builder setVibrate (long[] pattern) : Sets the vibration pattern to use

    NotificationCompat.Builder setVibrate(long []模式) :设置要使用的振动模式
  16. 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通知按钮和样式 (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">

    <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.

android notification example, android pendingintent example

实际应用的输出如下。

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://www.journaldev.com/10463/android-notification-pendingintent

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值