android 通知栏样式

We’ve discussed and implemented basic Notifications in this post. In this tutorial, we’ll be looking into more advanced features of android notification and styling our notifications in different ways.

我们已经讨论并实现基本声明此文章。 在本教程中,我们将研究android通知的更高级功能,并以不同方式设置通知样式。

Android通知样式 (Android Notification Styling)

Android Notification have plenty of powerful features that when used correctly would significantly improve the UX and user engagement. Some noteworthy features that we’ll be covering in this Android Notification tutorial are listed below.

Android Notification具有许多强大的功能,如果正确使用它们,将大大提高用户体验和用户参与度。 下面列出了我们将在本Android Notification教程中介绍的一些值得注意的功能。

  1. Notification Actions通知动作
  2. Heads Up Notification抬头通知
  3. Big Text Style Notification大文字样式通知
  4. Big Picture Style Notification大图样式通知
  5. Inbox Style Notification收件箱样式通知
  6. Message Style Notification邮件样式通知

Android notification consists of three major components:

Android通知包含三个主要组件:

  1. Small Icon (often our app logo)小图标(通常是我们的应用徽标)
  2. Title标题
  3. Content Text内容文字

The introduction of Android Nougat (API 24) has given a new look to notifications as shown below.

Android Nougat(API 24)的引入使通知有了新外观,如下所示。

The large icon now appears on the right. There’s an arrow besides the notification title that lets us expand, collapse the notification.

现在,大图标出现在右侧。 通知标题旁边有一个箭头,可让我们展开,折叠通知。

In this tutorial, we’ll be styling our notifications using some pre-defined awesome styles that Android has in store for us. We’ll be covering the following features at length.

在本教程中,我们将使用Android为我们提供的一些预定义超赞样式来设置通知的样式。 我们将详细介绍以下功能。

  1. Android Notification ActionsAndroid通知动作
  2. Heads Up Notifications抬头通知
  3. Rich Notifications丰富的通知

Android通知动作 (Android Notification Actions)

Android Notification actions are basically buttons placed below the body of the notification. A Notification action must include an icon, a label, and a PendingIntent to be fired when the action is selected by the user.

Android Notification动作基本上是位于通知主体下方的按钮。 通知动作必须包含一个图标,一个标签以及一个当用户选择该动作时要触发的PendingIntent

With the Introduction of Android N, the icons are omitted from the action buttons to give space to other components.

随着Android N的介绍,操作按钮中的图标被省略,以留出空间给其他组件。

An example of notification actions in Pre Nougat devices is given below.

牛轧糖前设备中的通知操作示例如下。

Pre-Nougat Notification Action Design

牛轧糖前通知动作设计

An example of Notification Actions in Android N and above is given below.

以下是Android N及更高版本中的通知操作示例。

Notification Action in Android Nougat

Android Nougat中的通知动作

抬头通知 (Heads Up Notifications)

With the introduction of Android Lollipop (API level 21), notifications can appear in a small floating window (also called a heads-up notification) when the device is active (that is, the device is unlocked and its screen is on).

随着Android Lollipop(API级别21)的引入,当设备处于活动状态(即设备已解锁且屏幕处于打开状态)时,通知可以显示在一个小的浮动窗口中(也称为平视通知)。

Such type of notifications are commonly seen when you’re using an application and you get a call. A small floating notification known as heads up notifications pops up with the notification actions to accept or decline a call.

当您使用应用程序并接到电话时,通常会看到此类通知。 一个小的浮动通知(称为抬头通知)随通知动作弹出,以接听或拒绝呼叫。

丰富的通知 (Rich Notifications)

Android allows us to add rich styles to our application with the introduction of Android L. Using these styles would make the notification look more appealing than ever. Some of the known styles that are used in many applications are listed below and are self-explanatory.

Android允许我们通过引入Android L向我们的应用程序添加丰富的样式。使用这些样式将使通知看起来比以往更具吸引力。 下面列出了许多应用程序中使用的一些已知样式,这些样式是不言自明的。

  • BigTextStyleBigTextStyle
  • BigPictureStyleBigPictureStyle
  • InboxStyleInboxStyle
  • MessageStyleMessageStyle

We know that notifications on Android N can be expanded using the arrows. To expand notifications on pre-Nougat versions, you can swipe down over the notification using two fingers.

我们知道可以使用箭头扩展Android N上的通知。 要扩展牛轧糖之前版本的通知,您可以用两根手指在通知上向下滑动。

Not all Android versions would support the above styles. In case an Android OS doesn’t support the rich style, that style would simply be ignored.

并非所有的Android版本都支持上述样式。 如果Android操作系统不支持丰富样式,则该样式将被忽略。

Now let’s jump into the business end of this tutorial and develop an application that’ll have all the above features.

现在,让我们进入本教程的业务范围,并开发一个具有上述所有功能的应用程序。

Android Notification Tutorial项目结构 (Android Notification Tutorial Project Structure)

Android通知教程代码 (Android Notification Tutorial Code)

The code for the activity_main.xml is given below:

下面给出了activity_main.xml的代码:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="https://schemas.android.com/apk/res/android"xmlns:app="https://schemas.android.com/apk/res-auto"xmlns:tools="https://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context="com.journaldev.stylingnotifications.MainActivity"><Buttonandroid:id="@+id/btnNotificationActions"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="NOTIFICATION ACTIONS"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintLeft_toLeftOf="parent"app:layout_constraintRight_toRightOf="parent"app:layout_constraintTop_toTopOf="parent"app:layout_constraintVertical_bias="0.196" /><Buttonandroid:id="@+id/btnHeadsUp"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="8dp"android:layout_marginRight="8dp"android:layout_marginTop="8dp"android:text="HEADS UP NOTIFICATION"app:layout_constraintLeft_toLeftOf="parent"app:layout_constraintRight_toRightOf="parent"app:layout_constraintTop_toBottomOf="@+id/btnNotificationActions" /><Buttonandroid:id="@+id/btnBigTextStyle"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="BIG TEXT STYLE"app:layout_constraintLeft_toLeftOf="parent"app:layout_constraintRight_toRightOf="parent"android:layout_marginTop="8dp"app:layout_constraintTop_toBottomOf="@+id/btnHeadsUp" /><Buttonandroid:id="@+id/btnBigPictureStyle"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="BIG PICTURE STYLE"app:layout_constraintLeft_toLeftOf="parent"app:layout_constraintRight_toRightOf="parent"android:layout_marginTop="8dp"app:layout_constraintTop_toBottomOf="@+id/btnBigTextStyle" /><Buttonandroid:id="@+id/btnInboxStyle"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="INBOX STYLE"app:layout_constraintLeft_toLeftOf="parent"app:layout_constraintRight_toRightOf="parent"android:layout_marginTop="8dp"app:layout_constraintTop_toBottomOf="@+id/btnBigPictureStyle" /><Buttonandroid:id="@+id/btnMessageStyle"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="MESSAGE STYLE"app:layout_constraintLeft_toLeftOf="parent"app:layout_constraintRight_toRightOf="parent"android:layout_marginTop="8dp"app:layout_constraintTop_toBottomOf="@+id/btnInboxStyle" /></android.support.constraint.ConstraintLayout>

We’ve added a button for each type of notification that we’ll be discussing.

我们为将要讨论的每种通知类型添加了一个按钮。

The skeleton code for the MainActivity.java is given below.

MainActivity.java的框架代码如下。

public class MainActivity extends AppCompatActivity implements View.OnClickListener {Button btnNotificationActions, btnHeadsUpNotification, btnBigTextStyle, btnBigPictureStyle,btnInboxStyle, btnMessageStyle;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);clearNotification();btnNotificationActions = (Button) findViewById(R.id.btnNotificationActions);btnHeadsUpNotification = (Button) findViewById(R.id.btnHeadsUp);btnBigTextStyle = (Button) findViewById(R.id.btnBigTextStyle);btnBigPictureStyle = (Button) findViewById(R.id.btnBigPictureStyle);btnInboxStyle = (Button) findViewById(R.id.btnInboxStyle);btnMessageStyle = (Button) findViewById(R.id.btnMessageStyle);btnNotificationActions.setOnClickListener(this);btnHeadsUpNotification.setOnClickListener(this);btnBigTextStyle.setOnClickListener(this);btnBigPictureStyle.setOnClickListener(this);btnInboxStyle.setOnClickListener(this);btnMessageStyle.setOnClickListener(this);}@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.btnNotificationActions:notificationActions();break;case R.id.btnHeadsUp:headsUpNotification();break;case R.id.btnBigTextStyle:bigTextStyleNotification();break;case R.id.btnBigPictureStyle:bigPictureStyleNotification();break;case R.id.btnInboxStyle:inboxStyleNotification();break;case R.id.btnMessageStyle:messageStyleNotification();break;}}public PendingIntent getLaunchIntent(int notificationId, Context context) {Intent intent = new Intent(context, MainActivity.class);intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);intent.putExtra("notificationId", notificationId);return PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);}private void clearNotification() {int notificationId = getIntent().getIntExtra("notificationId", 0);NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);manager.cancel(notificationId);}private void notificationActions(){//Logic goes here.}private void headsUpNotification(){//Logic goes here.}private void bigTextStyleNotification(){//Logic goes here.}private void bigPictureStyleNotification();{//Logic goes here.}private void inboxStyleNotification(){//Logic goes here.}private void messageStyleNotification(){//Logic goes here.}
}

The method clearNotification() is used to clear any existing notifications from the notification bar.
The method getLaunchIntent() returns an instance of PendingIntent which when triggered from the notification, will relaunch the application.

方法clearNotification()用于清除通知栏中的所有现有通知。
方法getLaunchIntent()返回PendingIntent的实例,当从通知中触发该实例时,它将重新启动应用程序。

Before we delve into the implementation of each type of notification, let’s define the BroadcastReceiver as shown below.

在深入研究每种通知的实现之前,让我们定义如下的BroadcastReceiver 。

package com.journaldev.stylingnotifications;import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;public class NotificationReceiver extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {int notificationId = intent.getIntExtra("notificationId", 0);NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);manager.cancel(notificationId);}
}

Update the AndroidManifest.xml file with the receiver defined as shown below.

使用定义如下的接收器更新AndroidManifest.xml文件。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"package="com.journaldev.stylingnotifications"><applicationandroid:allowBackup="true"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:roundIcon="@mipmap/ic_launcher_round"android:supportsRtl="true"android:theme="@style/AppTheme"><receiver android:name=".NotificationReceiver"android:exported="false"/><activity android:name=".MainActivity"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity></application></manifest>

在通知中添加动作 (Adding actions inside a notification)

private void notificationActions() {int NOTIFICATION_ID = 1;NotificationCompat.Builder builder = new NotificationCompat.Builder(this);builder.setSmallIcon(R.drawable.jd);builder.setColor(ContextCompat.getColor(this, R.color.colorPrimaryDark));builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.jd));builder.setContentTitle("Notification Actions");builder.setContentText("Tap View to launch our website");builder.setAutoCancel(true);PendingIntent launchIntent = getLaunchIntent(NOTIFICATION_ID, getBaseContext());Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.journaldev.com"));PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);Intent buttonIntent = new Intent(getBaseContext(), NotificationReceiver.class);buttonIntent.putExtra("notificationId", NOTIFICATION_ID);PendingIntent dismissIntent = PendingIntent.getBroadcast(getBaseContext(), 0, buttonIntent, 0);builder.setContentIntent(launchIntent);builder.addAction(android.R.drawable.ic_menu_view, "VIEW", pendingIntent);builder.addAction(android.R.drawable.ic_delete, "DISMISS", dismissIntent);NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);// Will display the notification in the notification barnotificationManager.notify(NOTIFICATION_ID, builder.build());}

In the above code, we set the various styles on the instance builder.

在上面的代码中,我们在实例builder上设置了各种样式。

setColor() sets the custom color for the notification icon, title and action button texts.

setColor()设置通知图标,标题和操作按钮文本的自定义颜色。

addAction() is used to set the action buttons beneath the notification content. It expects three params: icon, text and the instance of PendingIntent.

addAction()用于在通知内容下方设置操作按钮。 它需要三个参数:图标,文本和PendingIntent实例。

setContentIntent() sets the PendingIntent that’ll be triggered when the body of the notification is clicked. In the above code we’ve simply added the PendingIntent to relaunch the application.

setContentIntent()设置单击通知正文时将触发的PendingIntent。 在上面的代码中,我们仅添加了PendingIntent以重新启动该应用程序。

setAutoCancel(true) is used to dismiss the notification when its clicked.

setAutoCancel(true)用于在单击通知时关闭该通知。

NotificationManager class is used to display the notification.

NotificationManager类用于显示通知。

The output of the application when the above type of notification is triggered is given below.

下面给出了触发上述类型的通知时应用程序的输出。

Note:

注意事项

  • When the VIEW button is clicked, the url is launched in the browser but the notification isn’t dismissed.单击“查看”按钮时,URL将在浏览器中启动,但不会关闭通知。
  • When the DISMISS button is clicked the notification is cleared but the notification tray stays open.单击“ DISMISS”按钮时,通知已清除,但通知托盘保持打开状态。
  • When the Notification content is clicked, the notification is dismissed as well as the activity is re-launched. This is where getLaunchIntent() and clearNotification() methods are invoked.单击通知内容后,该通知将被取消,并且该活动将重新启动。 这是调用getLaunchIntent()clearNotification()方法的地方。

实施抬头通知 (Implementing Heads Up Notification)

private void headsUpNotification() {int NOTIFICATION_ID = 1;NotificationCompat.Builder builder =new NotificationCompat.Builder(this).setSmallIcon(R.drawable.jd).setContentTitle("Heads Up Notification").setContentText("View the latest Swift Tutorial").setAutoCancel(true).setDefaults(NotificationCompat.DEFAULT_ALL).setPriority(NotificationCompat.PRIORITY_HIGH);Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.journaldev.com/15126/swift-function"));PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);Intent buttonIntent = new Intent(getBaseContext(), NotificationReceiver.class);buttonIntent.putExtra("notificationId", NOTIFICATION_ID);PendingIntent dismissIntent = PendingIntent.getBroadcast(getBaseContext(), 0, buttonIntent, 0);builder.addAction(android.R.drawable.ic_menu_view, "VIEW", pendingIntent);builder.addAction(android.R.drawable.ic_delete, "DISMISS", dismissIntent);NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);notificationManager.notify(NOTIFICATION_ID, builder.build());}

To set a notification as heads up notification, two properties need to set on the builder instance.

要将通知设置为抬头通知,需要在构建器实例上设置两个属性。

setDefaults(NotificationCompat.DEFAULT_ALL)
setPriority(NotificationCompat.PRIORITY_HIGH)

Swiping a heads up notification would dismiss it. If it’s not dismissed, the heads-up notifications will fade away and change into a standard notification in the status bar.

刷单向通知会取消该通知。 如果未取消,则抬头通知将消失,并在状态栏中变为标准通知。

The output of heads up notification is given below.

抬头通知的输出如下。

BigTextStyle通知 (BigTextStyle Notification)

private void bigTextStyleNotification() {int NOTIFICATION_ID = 1;PendingIntent launchIntent = getLaunchIntent(NOTIFICATION_ID, getBaseContext());Intent buttonIntent = new Intent(getBaseContext(), NotificationReceiver.class);buttonIntent.putExtra("notificationId", NOTIFICATION_ID);PendingIntent dismissIntent = PendingIntent.getBroadcast(getBaseContext(), 0, buttonIntent, 0);NotificationCompat.Builder builder = new NotificationCompat.Builder(this);builder.setSmallIcon(R.drawable.jd);builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.jd));builder.setContentTitle("Big Text Style");builder.setStyle(new NotificationCompat.BigTextStyle().bigText(getResources().getString(R.string.lorem_ipsum)));builder.setAutoCancel(true);builder.setContentIntent(launchIntent);builder.addAction(android.R.drawable.ic_delete, "DISMISS", dismissIntent);builder.addAction(android.R.drawable.ic_menu_send, "OPEN APP", launchIntent);NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);// Will display the notification in the notification barnotificationManager.notify(NOTIFICATION_ID, builder.build());}

A notification can be customised into a big text style notification by setting the style as
NotificationCompat.BigTextStyle(). The string to be displayed is entered inside the method bigText().

通过将样式设置为,可以将通知定制为大文本样式通知
NotificationCompat.BigTextStyle() 。 要显示的字符串在方法bigText()中输入。

The output of above type of notification is given below.

上述通知的输出如下。

BigPictureStyle通知 (BigPictureStyle Notification)

private void bigPictureStyleNotification() {int NOTIFICATION_ID = 1;Bitmap pic = BitmapFactory.decodeResource(getResources(), R.drawable.bg);Intent buttonIntent = new Intent(getBaseContext(), NotificationReceiver.class);buttonIntent.putExtra("notificationId", NOTIFICATION_ID);PendingIntent dismissIntent = PendingIntent.getBroadcast(getBaseContext(), 0, buttonIntent, 0);PendingIntent launchIntent = getLaunchIntent(NOTIFICATION_ID, getBaseContext());NotificationCompat.Builder builder = new NotificationCompat.Builder(this);builder.setSmallIcon(R.drawable.jd);builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.jd));builder.setContentTitle("Big Picture Style");builder.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(pic));builder.setAutoCancel(true);builder.setContentIntent(launchIntent);builder.addAction(android.R.drawable.ic_delete, "DISMISS", dismissIntent);NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);// Will display the notification in the notification barnotificationManager.notify(NOTIFICATION_ID, builder.build());}

For BigPicture to be displayed inside a notification the style is set as NotificationCompat.BigPictureStyle().bigPicture(bitmap)).

为了使BigPicture显示在通知中,样式设置为NotificationCompat.BigPictureStyle().bigPicture(bitmap))

The output with the above type of notification is given below.

具有上述通知类型的输出如下。

InboxStyle通知 (InboxStyle Notification)

private void inboxStyleNotification() {int NOTIFICATION_ID = 1;PendingIntent launchIntent = getLaunchIntent(NOTIFICATION_ID, getBaseContext());NotificationCompat.Builder builder = new NotificationCompat.Builder(this);builder.setSmallIcon(R.drawable.jd);builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.jd));builder.setStyle(new NotificationCompat.InboxStyle().addLine("Hello").addLine("Are you there?").addLine("How's your day?").setBigContentTitle("3 New Messages for you").setSummaryText("Inbox"));builder.setAutoCancel(true);builder.setContentIntent(launchIntent);NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);// Will display the notification in the notification barnotificationManager.notify(NOTIFICATION_ID, builder.build());}

An inbox style notification is set by using the style new NotificationCompat.InboxStyle().
Each message is placed inside the method addLine(). The summary text of all the messages is placed inside the method setSummaryText().
setContentTitle() is replaced with setBigContentTitle() in this style

收件箱样式通知是通过使用样式new NotificationCompat.InboxStyle()
每个消息都放在方法addLine() 。 所有消息的摘要文本都放在方法setSummaryText()
setContentTitle()以此样式替换为setBigContentTitle()

The output of the above type of notification is given below

上述通知的输出如下

邮件样式通知 (Message Style Notification)

Message Style is introduced with Android N. Typically used for chats.

消息样式是Android N引入的。通常用于聊天。

private void messageStyleNotification() {int NOTIFICATION_ID = 1;PendingIntent launchIntent = getLaunchIntent(NOTIFICATION_ID, getBaseContext());NotificationCompat.Builder builder = new NotificationCompat.Builder(this);builder.setSmallIcon(R.drawable.jd);builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.jd));builder.setContentTitle("Messages");builder.setStyle(new NotificationCompat.MessagingStyle("Teacher").setConversationTitle("Q&A Group").addMessage("This type of notification was introduced in Android N. Right?",0,"Student 1").addMessage("Yes",0,null).addMessage("The constructor is passed with the name of the current user. Right?",0,"Student 2").addMessage("True",0,null));builder.setAutoCancel(true);builder.setContentIntent(launchIntent);NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);// Will display the notification in the notification barnotificationManager.notify(NOTIFICATION_ID, builder.build());}

In the above code NotificationCompat.MessagingStyle(String) contains a string that represents the current user(Typically in a chat its you!).
Each message is added in the method addMessage() with the timestamp as well as sender name.
If the sender name is set to null it signifies that the message is from the current user(you) and the name is taken from the constructor.

在上面的代码中, NotificationCompat.MessagingStyle(String)包含一个表示当前用户的字符串(通常在聊天中是您!)。
每条消息都将在方法addMessage()中添加时间戳和发件人名称。
如果发件人名称设置为null,则表示该消息来自当前用户(您),并且该名称来自构造函数。

The output of the above type of notification is given below.

上述通知的输出如下。

Adding all the above methods in the MainActivity.java would give us the below code.

MainActivity.java添加上述所有方法将为我们提供以下代码。

package com.journaldev.stylingnotifications;import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.view.View;
import android.widget.Button;public class MainActivity extends AppCompatActivity implements View.OnClickListener {Button btnNotificationActions, btnHeadsUpNotification, btnBigTextStyle, btnBigPictureStyle,btnInboxStyle, btnMessageStyle;NotificationCompat.Builder builder;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);clearNotification();btnNotificationActions = (Button) findViewById(R.id.btnNotificationActions);btnHeadsUpNotification = (Button) findViewById(R.id.btnHeadsUp);btnBigTextStyle = (Button) findViewById(R.id.btnBigTextStyle);btnBigPictureStyle = (Button) findViewById(R.id.btnBigPictureStyle);btnInboxStyle = (Button) findViewById(R.id.btnInboxStyle);btnMessageStyle = (Button) findViewById(R.id.btnMessageStyle);btnNotificationActions.setOnClickListener(this);btnHeadsUpNotification.setOnClickListener(this);btnBigTextStyle.setOnClickListener(this);btnBigPictureStyle.setOnClickListener(this);btnInboxStyle.setOnClickListener(this);btnMessageStyle.setOnClickListener(this);}@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.btnNotificationActions:notificationActions();break;case R.id.btnHeadsUp:headsUpNotification();break;case R.id.btnBigTextStyle:bigTextStyleNotification();break;case R.id.btnBigPictureStyle:bigPictureStyleNotification();break;case R.id.btnInboxStyle:inboxStyleNotification();break;case R.id.btnMessageStyle:messageStyleNotification();break;}}private void notificationActions() {int NOTIFICATION_ID = 1;builder = new NotificationCompat.Builder(this);builder.setSmallIcon(R.drawable.jd);builder.setColor(ContextCompat.getColor(this, R.color.colorPrimaryDark));builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.jd));builder.setContentTitle("Notification Actions");builder.setContentText("Tap View to launch our website");builder.setAutoCancel(true);PendingIntent launchIntent = getLaunchIntent(NOTIFICATION_ID, getBaseContext());Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.journaldev.com"));PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);Intent buttonIntent = new Intent(getBaseContext(), NotificationReceiver.class);buttonIntent.putExtra("notificationId", NOTIFICATION_ID);PendingIntent dismissIntent = PendingIntent.getBroadcast(getBaseContext(), 0, buttonIntent, 0);builder.setContentIntent(launchIntent);builder.addAction(android.R.drawable.ic_menu_view, "VIEW", pendingIntent);builder.addAction(android.R.drawable.ic_delete, "DISMISS", dismissIntent);buildNotification(NOTIFICATION_ID);}public PendingIntent getLaunchIntent(int notificationId, Context context) {Intent intent = new Intent(context, MainActivity.class);intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);intent.putExtra("notificationId", notificationId);return PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);}private void clearNotification() {int notificationId = getIntent().getIntExtra("notificationId", 0);NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);manager.cancel(notificationId);}private void headsUpNotification() {int NOTIFICATION_ID = 1;builder =new NotificationCompat.Builder(this).setSmallIcon(R.drawable.jd).setContentTitle("Heads Up Notification").setContentText("View the latest Swift Tutorial").setAutoCancel(true).setDefaults(NotificationCompat.DEFAULT_ALL).setPriority(NotificationCompat.PRIORITY_HIGH);Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.journaldev.com/15126/swift-function"));PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);Intent buttonIntent = new Intent(getBaseContext(), NotificationReceiver.class);buttonIntent.putExtra("notificationId", NOTIFICATION_ID);PendingIntent dismissIntent = PendingIntent.getBroadcast(getBaseContext(), 0, buttonIntent, 0);builder.addAction(android.R.drawable.ic_menu_view, "VIEW", pendingIntent);builder.addAction(android.R.drawable.ic_delete, "DISMISS", dismissIntent);buildNotification(NOTIFICATION_ID);}private void bigTextStyleNotification() {int NOTIFICATION_ID = 1;PendingIntent launchIntent = getLaunchIntent(NOTIFICATION_ID, getBaseContext());Intent buttonIntent = new Intent(getBaseContext(), NotificationReceiver.class);buttonIntent.putExtra("notificationId", NOTIFICATION_ID);PendingIntent dismissIntent = PendingIntent.getBroadcast(getBaseContext(), 0, buttonIntent, 0);builder = new NotificationCompat.Builder(this);builder.setSmallIcon(R.drawable.jd);builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.jd));builder.setContentTitle("Big Text Style");builder.setStyle(new NotificationCompat.BigTextStyle().bigText(getResources().getString(R.string.lorem_ipsum)));builder.setAutoCancel(true);builder.setContentIntent(launchIntent);builder.addAction(android.R.drawable.ic_delete, "DISMISS", dismissIntent);builder.addAction(android.R.drawable.ic_menu_send, "OPEN APP", launchIntent);buildNotification(NOTIFICATION_ID);}private void bigPictureStyleNotification() {int NOTIFICATION_ID = 1;Bitmap pic = BitmapFactory.decodeResource(getResources(), R.drawable.bg);Intent buttonIntent = new Intent(getBaseContext(), NotificationReceiver.class);buttonIntent.putExtra("notificationId", NOTIFICATION_ID);PendingIntent dismissIntent = PendingIntent.getBroadcast(getBaseContext(), 0, buttonIntent, 0);PendingIntent launchIntent = getLaunchIntent(NOTIFICATION_ID, getBaseContext());builder = new NotificationCompat.Builder(this);builder.setSmallIcon(R.drawable.jd);builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.jd));builder.setContentTitle("Big Picture Style");builder.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(pic));builder.setAutoCancel(true);builder.setContentIntent(launchIntent);builder.addAction(android.R.drawable.ic_delete, "DISMISS", dismissIntent);buildNotification(NOTIFICATION_ID);}private void inboxStyleNotification() {int NOTIFICATION_ID = 1;PendingIntent launchIntent = getLaunchIntent(NOTIFICATION_ID, getBaseContext());builder = new NotificationCompat.Builder(this);builder.setSmallIcon(R.drawable.jd);builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.jd));builder.setContentTitle("Messages");builder.setStyle(new NotificationCompat.InboxStyle().addLine("Hello").addLine("Are you there?").addLine("How's your day?").setBigContentTitle("3 New Messages for you").setSummaryText("Inbox"));builder.setAutoCancel(true);builder.setContentIntent(launchIntent);buildNotification(NOTIFICATION_ID);}private void messageStyleNotification() {int NOTIFICATION_ID = 1;PendingIntent launchIntent = getLaunchIntent(NOTIFICATION_ID, getBaseContext());builder = new NotificationCompat.Builder(this);builder.setSmallIcon(R.drawable.jd);builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.jd));builder.setContentTitle("Messages");builder.setStyle(new NotificationCompat.MessagingStyle("Teacher").setConversationTitle("Q&A Group").addMessage("This type of notification was introduced in Android N. Right?", 0, "Student 1").addMessage("Yes", 0, null).addMessage("The constructor is passed with the name of the current user. Right?", 0, "Student 2").addMessage("True", 0, null));builder.setAutoCancel(true);builder.setContentIntent(launchIntent);buildNotification(NOTIFICATION_ID);}private void buildNotification(int NOTIFICATION_ID) {NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);// Will display the notification in the notification barnotificationManager.notify(NOTIFICATION_ID, builder.build());}
}

This brings an end to android notification tutorial. We’ve styled our notifications in some interesting ways. You can download the final Android notification example project from the link below.

这结束了android通知教程。 我们以一些有趣的方式设置了通知的样式。 您可以从下面的链接下载最终的Android通知示例项目

Download Android Notification Styling Project下载Android通知样式项目

Reference: Official Doc

参考: 官方文件

翻译自: https://www.journaldev.com/15468/android-notification-styling

android 通知栏样式

android 通知栏样式_Android通知样式相关推荐

  1. android 通知栏进度_Android改造下载图片进度通知

    android 通知栏进度 In this tutorial, we'll be using the Retrofit library in order to download an image fr ...

  2. java发送通知栏样式_Android 通知栏Notification详解

    在android的应用层中,涉及到很多应用框架,例如:Service框架,Activity管理机制,Broadcast机制,对话框框架,标题栏框架,状态栏框架,通知机制,ActionBar框架等等. ...

  3. android notification设置不同字体颜色,Android Notification自定义通知样式你要知道的事...

    本文将根据个人经验对Notification做个总结,以供参考! 什么是通知(Notification) 通知是一个可以在应用程序正常的用户界面之外显示给用户的消息. 通知发出时,它首先出现在状态栏的 ...

  4. android自定义通知栏样式,Android 通知栏自定义样式

    8.0系统的通知栏适配 在8.0之前我们通知栏的使用:notification = new NotificationCompat.Builder(mContext) .setWhen(System.c ...

  5. android toast样式 最新,7个最好的Android本机Toast通知替换库

    本文概述 尽管大多数Toast通知库都已过时, 但已改用包含Toast的新设计支持库.由于这个原因, 不再积极维护许多库的开发, 但是它们的工作相当不错(还有其他项目仍在维护中)!如果你正在寻找建议使 ...

  6. 【黑马Android】(11)音乐播放器/视频播放器/照相机/常见对话框/notification通知/样式和主题/帧动画/传感器/应用程序反编译与安装

    音乐播放器api <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns: ...

  7. 【Android 应用开发】 ActionBar 样式详解 -- 样式 主题 简介 Actionbar 的 icon logo 标题 菜单样式修改

    作者 : 万境绝尘 (octopus_truth@163.com) 转载请著名出处 : http://blog.csdn.net/shulianghan/article/details/3926916 ...

  8. Android中使用Notification在通知栏中显示通知

    场景 App在接收到后台推送的消息后,需要在系统通知栏中显示通知消息,并且点击通知消息跳转到新的页面,并将消息内容传递过去. 效果如下 注: 博客: https://blog.csdn.net/bad ...

  9. Android 自定义Button按钮显示样式(正常、按下、获取焦点)

    2019独角兽企业重金招聘Python工程师标准>>> 现在的用户对APP的外观看得很重要,如果APP内所有元件都用Android默认样式写,估计下面评论里就有一堆在骂UI丑的.今天 ...

最新文章

  1. 本地windows上传大文件到Linux服务器工具的选择以及使用方法
  2. vue ts 监听路由改变
  3. serv-u 自定义html,Serv-U架设教程_Serv-U使用教程图文版
  4. 架构师之路 — 软件架构 — 软件质量模型
  5. WebForm与MVC混用
  6. java中如何改变状态栏_如何创建状态栏
  7. RHEL修改最大文件打开数,关于epoll socket Too many open files问题的解决
  8. 面试精讲之面试考点及大厂真题 - 分布式专栏 23 分布式系统下分布式锁的实现
  9. 计算机控制台win10,寻找win10电脑的控制面板工具
  10. 计算机的配置以及简单的操作
  11. getch方法_如何实现getch()函数的功能
  12. 第一次在win10的系统上装oracle 10g 的服务端和客户端遇到了一下两个问题,在这里记录一下。。。。。。
  13. npm init 自动创建 package.json 文件
  14. 软考信息系统项目管理师_合同法_著作权_实施条例---软考高级之信息系统项目管理师030
  15. 游戏中要遵守道德规范吗?谈《荒野大镖客2》道德体验设计的意义
  16. python轰炸敌机小游戏_python实现飞机大战微信小游戏
  17. 理工男博士买房记:按照科学原理去爱,没哪个妹子能招架得了
  18. 【笨木头Unity】入门之旅007:Demo之四处找死(二)_主角移动和旋转
  19. 半导体通讯标准EAP、SECS/GEM视频介绍
  20. 一套计算机网络系统设计方案,包含外网、内网、智能化设备网

热门文章

  1. byte[]与Image Image与 byte[] 之间的转换
  2. MapReduce的map流程
  3. [转载] python difference用法_set.difference() 的用法(python3)_python3 set集合,三元运算以及
  4. [转载] python3.x总复习
  5. [转载] 树莓派并行控制电机_使用由并行端口控制的软盘驱动步进电机的相机摇摄器
  6. angularJS前端分页插件
  7. 3dContactPointAnnotationTool开发日志(八)
  8. python之路 《四》 字典
  9. Eclipse------新建文件时没有JSP File解决方法
  10. mybatis 调用存储过程