Basic usage of Android notification

First, a NotificationManager() method is needed to manage notifications.
It can be obtained by calling the getSystemService() method of Context.
The getSystemService() method receives a string parameter to determine which service of the system to obtain,
here we can pass in Content.NOTIFICATION_SERVICE.
Therefore, obtaining an instance of NotificationManager can be written as:

NotificationManager manager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);

Next, you need to use a Builder constructor to create the Notification object, but the problem is that almost every version of the Android system will make more or less modifications to this part of the notification function. The problem of API instability is particularly serious in the notification. . So use the compatible API provided in the support library. The support-v4 library provides a NotificationCompat class. Using the constructor of this class to create a Notification object can ensure that our program can work normally on all Android system versions. The code is as follows:

Notification notification = new NotificationCompat.Builder(context).build();

Of course, the above code just creates an empty Notification object, and has no practical effect. We can create a rich Notification object by connecting any number of setting methods before the final build() method. Let’s look at some of the most basic Settings:

Notification notification = new NotificationCompat.Builder(context)
		.setContentTitle("This is content title")
		.setContentText("This is content text")
		.setWhen(System.currentTimeMillis())
		.setSmallIcon(R.drawable.small_icon)
		.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.large_icon))
		.build();

A total of five setting methods are called in the above code, which are analyzed one by one below.

The **setContentTitle()** method is used to specify the title content of the notification, which can be seen by pulling down the system status bar.

The **setContentText()** method is used to specify the body content of the notification, and you can see this part of the content by pulling down the system status bar.

The **setWhen()** method is used to specify the time when the notification is created, in milliseconds. When the system status bar is pulled down, the time specified here will be displayed on the corresponding notification.

The **setSmallIcon()** method is used to set the small icon of the notification. Note that only pictures with a pure alpha layer can be used for setting, and the small icon will be displayed on the system status bar.

The **setLargeIcon()** method is used to set the large icon of the notification. When you pull down the system status bar, you can see the large icon set.

After the above work is completed, only need to call the nitify() method of NotificationManager to display the notification.

**notify()** method receives two parameters

The first parameter is id . Make sure that the id specified for each notification is different.

The second parameter is the Notification object, here we can directly pass in the Notification object we just created. Therefore, a notice can be written as:

manager.notify(1,notification);

Specifically, let's see what the notification looks like through an example:

Create a new NotificationTest project and modify the code in activity_main as follows:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="net.nyist.lenovo.notificationtest.MainActivity"
    android:orientation="vertical"
    >

   <Button
       android:id="@+id/send_notice"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Send notice"
       />

</LinearLayout>

The layout file is very simple, there is only a Send notice button to send a notice. Next, modify the code in MainActivity:

public class MainActivity extends AppCompatActivity  implements View.OnClickListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button sendNotice = (Button) findViewById(R.id.send_notice);
        sendNotice.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
     switch (v.getId()){
         case R.id.send_notice:
             NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
             Notification notification = new NotificationCompat.Builder(this)
                     .setContentTitle("This is content title")
                     .setContentText("This is content text")
                     .setWhen(System.currentTimeMillis())
                     .setSmallIcon(R.mipmap.ic_launcher)
                     .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
                     .build();
             manager.notify(1,notification);
             break;
         default:
             break;
     }
    }
}

The operation is as follows:
Write picture description here
If you have used an Android phone, you should subconsciously think that this notification is clickable. But when you click on it, you will find no effect.
If we want to achieve the click effect of the notification, we also need to make the corresponding settings in the code, which involves a new concept: PendingIntent .

PendingIntent looks similar to Intent from the name, and they do have a lot in common. For example, they can all specify a certain "intent", which can be used to start activities, start services, and send broadcasts. The difference is that Intent is more inclined to execute an action immediately, while PendingIntent is more inclined to execute an action at a suitable time. Therefore, PendingIntent can also be simply understood as a delayed execution Intent.

The usage of PendingIntent is also very simple. It mainly provides several static methods for obtaining instances of PendingIntent. You can choose to use the getActivity() method, getBroadcast() method or getService() method according to your needs. The parameters received by these methods are the same.

The first parameter is still Context , no need to explain.

The second parameter is generally not used, it is usually passed in 0 .

The third parameter is an Intent object through which we can construct the "intent" of the PendingIntent.

The fourth parameter is used to determine the behavior of PendingIntent. There are four values ​​available: FLAG_ONE_SHOT , FLAG_NO_CREATE , FLAG_CANCEL_CURRENT, and FLAG_UPDATE_CURRENT .
You can check the documentation for the specific meaning of each value. Normally, you can pass in 0 for this parameter.

Here I checked the meaning of the parameters to see:

FLAG_ONE_SHOT :
this PendingIntent can only be used once. If set, after send() is called on it, it will be automatically canceled for you and any future attempt to send through it will fail.
The PendingIntent obtained by FLAG_ONE_SHOT can only be used once. Even if the above three methods are used again to obtain again, using PendingIntent again will fail.

FLAG_NO_CREATE:
if the described PendingIntent does not already exist, then simply return null instead of creating it.
The PendingIntent obtained with FLAG_NO_CREAT, if the described Intent does not exist, returns a NULL value.

FLAG_CANCEL_CURRENT :
if the described PendingIntent already exists, the current one is canceled before generating a new one. You can use this to retrieve a new PendingIntent when you are only changing the extra data in the Intent; by canceling the previous pending intent, this ensures that only entities given the new data will be able to launch it. If this assurance is not an issue, consider FLAG_UPDATE_CURRENT.
If the described PendingIntent already exists, the current one will be cancelled before generating a new Intent. You can use it to retrieve the new Intent, if you just want to change the additional data in the Intent. By canceling the previous Intent, it is available to ensure that only the latest entity is available to start it. If this guarantee is not a problem, consider flag_update_current.

FLAG_UPDATE_CURRENT:
if the described PendingIntent already exists, then keep it but its replace its extra data with what is in this new Intent. This can be used if you are creating intents where only the extras change, and don't care that any entities that received your previous PendingIntent will be able to launch it with your new extras even if they are not explicitly given to it. The
most frequently used is FLAG_UPDATE_CURRENT, because this flag is needed to update your description when the described Intent is updated. Otherwise, the extras will always be the extras of the first Intent when the next event occurs or the time arrives.

After having a certain understanding of PendingIntent , let's look back and take a look at NotificationCompat.Builder. This constructor can also be concatenated with a **setContentIntent()** method, and the received parameter is exactly a PengdingIntent object. Therefore, here, a delayed execution "intent" can be constructed through PengdingIntent. When the user clicks on the notification The corresponding logic will be executed.

Let’s optimize the above item and add a click function to the notification just now so that when the user clicks on it, another activity will be started.

First, you need to prepare another activity, to create a new Activity, named NotificationActivity, the layout named notification_layout. Then modify the code in notification_layout.xml as follows:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="net.nyist.lenovo.notificationtest.NotificationActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:textSize="24sp"
        android:text="This is notification layout"
        />

</RelativeLayout>

Now modify the code in MainActivity to add the click function:

public class MainActivity extends AppCompatActivity  implements View.OnClickListener{

········

    @Override
    public void onClick(View v) {
     switch (v.getId()){
         case R.id.send_notice:
             Intent intent = new Intent(this,NotificationActivity.class);
			//先创建Intent表达出我们想要启动NotificationActivity的"意图"
             PendingIntent pi = PendingIntent.getActivity(this,0,intent,0);
			//得到PendingIntent的实例。
             NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
             Notification notification = new NotificationCompat.Builder(this)
                     .setContentTitle("This is content title")
                     .setContentText("This is content text")
                     .setWhen(System.currentTimeMillis())
                     .setSmallIcon(R.mipmap.ic_launcher)
                     .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
                     .setContentIntent(pi)
					 //在这里调用setContentIntent()方法,把它作为参数传入。
                     .setAutoCancel(true)
                     .build();
             manager.notify(1,notification);
             break;
         default:
             break;
     }
    }
}

Notify click event

It can be found that the notification icon on the status has not disappeared. Yes, if we do not cancel the comrade in the code, it will always be displayed on the status bar of the system. There are two solutions, one is in NotificationCompat .Builder is connected with a setAutoCancel() method, one is to explicitly call the cancle() method of NotificationManagrer to cancel it. Two methods can be learned.

The first method:
Notification notification = new NotificationCompat.Builder(this)
·········
.setAutoCancel(true)
.build();

As you can see, the setAutoCancel() method passes true, which means that when the notification is clicked, the notification will be automatically canceled.

The second method:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    **NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    manager.cancel(1);**
    Button sendNotice = (Button) findViewById(R.id.send_notice);
    sendNotice.setOnClickListener(this);
}

Here we pass in 1 in the cancel() method. This 1 is the id we set for this notification at that time is 1. Therefore, if you want to cancel a notification, pass in the notification in the cancel() method The id machine will do.

#Advanced tips for notifications

Let's take a look at the setSound() method first, it can play a piece of audio when the notification is sent, so that it can better tell the user that the notification is coming. The setSound() method receives a Uri parameter, so when specifying
an audio file, you also need to get the URI corresponding to the audio file. For example, there are many audio files in the /system/media/audio/ringtones directory of each mobile phone. We can select an audio file from them, and then we can specify it in the code:

//Play
audio.setSound(Uri.fromFile(new File("/system/media/audio/ringtones/Luna.ogg")))

//Mobile phone vibration.
setVibrate(new long[]{0,1000,1000,1000})
If you want to control mobile phone vibration, you need to declare permissions. Therefore, we have to edit the AndroidManifest.xml file and add the following declaration:

// flash
.setLights (Color.GREEN, 1000,1000)

The first parameter is used to specify the color of the LED light, the second parameter is used to specify the length of time the LED light is on, in milliseconds, and the third parameter is used to specify the length of time the LED is dimmed, also in milliseconds.

Of course, if you don’t want to do so many complicated settings, you can also directly use the default effect of the notification. It will decide which ringtone to play and how to vibrate according to the current phone environment. The writing is as follows:

				.setDefaults(NotificationCompat.DEFAULT_ALL)

Note that the advanced techniques mentioned above must be run on a mobile phone to see the effect, and the simulator cannot show functions such as vibration and LED flashing.

Advanced notifications:

Continue to observe the NotificationCompat.Builder class, there are more powerful API usage.
Let's take a look at the setStyle() method first, which allows us to construct rich text notification content. In other words, not only can there be text and icons in the notification, it can also contain more things. The setStyle() method receives a NotificationCompat.Builder.Style parameter, this parameter is used to build specific rich text information, such as long text, pictures, etc. Before starting to use the setStyle() method, let's
do an experiment. The previous notification content is relatively short. If it is set to a very long text, what will be the effect, run it below to see:
Long notice

As you can see, the notification content cannot be displayed completely, and the redundant part will be replaced by an ellipsis. In fact, this is also very normal, because the content of the notification should be concise and concise, and the detailed content will be more suitable for the activity opened after the click.

But if you really need to display a long text in the notification, Android also supports it. It can be done through the setStyle() method. The specific writing is as follows:

.setStyle(new android.support.v4.app.NotificationCompat.BigTextStyle().bigText("Learn how to build notifications,send and sync data,and use voice actions.Get the official Android IDE and deceliper tools to build apps for Android."))

We created a NotificationCompat.BigTextStyle object in the setStyle() method. This object is used to encapsulate long text information. We call its bifText() method and pass in the text content.
The effect of running again is as follows:
setStyle long text

In addition to displaying long text, a large picture can also be displayed in the notification, and the specific usage is basically similar:

 .setStyle(new android.support.v4.app.NotificationCompat.BigPictureStyle().bigPicture(BitmapFactory.decodeResource(getResources(),R.drawable.big_image)))

Here is still the setStyle() method that is called. This time we create a NotificationCompat.BigPictureStyle object in the parameters, this object is used to set the big picture, and then call its bigPicture() method and pass in the picture. Here I have prepared a picture in advance, parse the picture into a Bitmap object through BitmapFactory's decodeResource() method, and then pass it to the bigPicture() method.

In this way, the important content in the setStyle() method is basically mastered.

Next, learn about the setPriority() method, which can be used to set the importance of notifications.

The **setPriority()** method receives an integer parameter to set the importance of this notification. There are 5 constant values ​​to choose from:

PRIORITY_DEFAULT indicates the default importance, which is the same as not setting the effect.

PRIORITY_MIN indicates the lowest importance. The system may only display this notification in certain scenarios, such as when the user pulls down the status bar.

PRIORITY_LOW indicates a lower level of importance. The system may reduce this type of notification or change the order of its display to rank it after more important notifications;

PRIORITY_HIGH indicates a higher degree of importance. The system may magnify such notifications or change the order of their display, placing them in the higher position.

PRIORITY_MAX represents the highest degree of importance. This type of notification message must be immediately seen by the user, and even requires the user to respond. The specific wording is as follows:
//The highest degree of importance

     .setPriority(NotificationCompat.PRIORITY_MAX)

Here we set the importance of the notification to the highest, which means that this is a very important notification and requires users to see it immediately. Now the running program is as follows: As
Highest level notification
you can see, instead of displaying a small icon in the system status bar, this notification pops up with a banner with details of the notification, indicating that this is a very important notification.

Guess you like

Origin blog.csdn.net/i_nclude/article/details/77688566