Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How does android create a simple notification

2025-03-04 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "how to create a simple notice in android". In daily operation, I believe many people have doubts about how to create a simple notice in android. The editor consulted all kinds of materials and sorted out a simple and useful method of operation. I hope it will be helpful to answer the doubts about "how to create a simple notice in android". Next, please follow the editor to study!

Notice

A notification is a message that is displayed in an interface outside your application. When you tell the system to post a notification, it first appears as an icon in the notification area. To see the details of the notification, the user can click on the notification area to launch a new interface.

Note: unless otherwise noted, this chapter refers to NotificationCompat.Builder, which is included in v4 Support Library and is officially added to API Level 15. But with v4 Support Library lower version of the system can also be used. In addition, Notification.Builder is added to android3.0.

7.1 Notification display element

Notifications are available in two visual styles, depending on the version and the status of the drawer:

Standard view

Standard notification view in drawer

Large view

A relatively large view. This view is part of the notification extension, which is added to android 4.1.

7.1.1 normal view

A standard view generally high-order 64dp. Even if you create a large view style, it still appears in the standard view until it is unfolded.

The following is a description of each section:

1. Content title

two。 Large icon

3. Content text

4. Content info

5. Mini icon

6. The time when the notice was issued. You can use setWhen () to set an explicit value.

7.1.2 large view

When the notification is expanded, the large view will appear and display. Generally, the user will use the unfold gesture to notify that the drawer will be expanded. Notification of deployment is only available on android 4.1. As shown in figure 7-4:

Note that most of the visual elements of a large View are shared with normal views. The only difference is the number 7, this area of detail. The major View style settings are somewhat different. Available styles are:

Big picture style

The details area contains a 256dp height bitmap in its details section.

Big text style

Displays a large block of text in the details section.

Inbox style

Displays the number of lines of text in the details section.

Here are the styles that are available for large view but not for standard view:

Big content title

Allows you to override the content title of the standard view so that it appears in the deployment view

Summary text

Allows you to add the number of lines of text in the detail area.

7.2 create a notification

If you want to specify UI information and actions for notifications in the NotificationCompat.Builder object, you must first use NotificationCompat.Builder.build () to create notifications. This method returns a Notification object. In order to issue notifications, you can pass the Notification object to the system by calling NotificationManager.notify ().

7.2.1 required notification content

A Notification object must contain the following:

Set a small icon through setSmallIcon ()

Set a title through setContentTitle ()

Set the detail text through setContentText ()

7.2.2 contents and settings of optional notifications

All other notification settings and content are optional. Please refer to the API NotificationCompat.Builder class for details.

7.2.3 Notification Action (action)

Although they are optional, you should add at least one action to your notification. An action allows the user to notify directly to an Activity of your application. A notification can provide multiple actions. You should always define an action and trigger it when the user clicks on the notification. Usually this action opens an Activity in your application. You can also add buttons to notifications (new features added in Android 4.1) to perform additional actions, such as a warning or instant response text message. If you use additional action buttons, you must make their functionality available in an Activity. In the notification, this action is defined by PendingIntent. Please use the appropriate method in NotificationCompat.Builder to create it. For example, when the user clicks the notification text in Drawer and you want to start Activity, you can add a PendingIntent by calling setContentIntent (). It is most common for users to click on a notification to start an Activity. Keep in mind that in Androird4.1 or later, you can launch an Activity from an action button.

7.2.4 create a simple notification

The following code snippet is a simple example that opens an activity when a user clicks on a notification. Notice that this code creates a TaskStackBuilder object and uses it to create a PendingIntent.

OtificationCompat.Builder mBuilder = new NotificationCompat.Builder (this) .setSmallIcon (R.drawable.notification_icon) .setContentTitle ("My notification") .setContentText ("Hello World!"); Intent resultIntent = new Intent (this, ResultActivity.class); TaskStackBuilder stackBuilder = TaskStackBuilder.create (this); stackBuilder.addParentStack (ResultActivity.class); stackBuilder.addNextIntent (resultIntent) PendingIntent resultPendingIntent = stackBuilder.getPendingIntent (0, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent (resultPendingIntent); NotificationManager mNotificationManager = (NotificationManager) getSystemService (Context.NOTIFICATION_SERVICE); mNotificationManager.notify (mId, mBuilder.build ()); 7.2.5 apply a large view style to notifications

When a large view appears after a general knowledge expansion, first create a NotificationCompat.Builder object that you want. Then call Builder.setStyle () to pass in the style object of the large view. Remember that previous versions of android4.1 are not available. Of course, we will explain how to be compatible with lower versions later.

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder (this) .setSmallIcon (R.drawable.notification_icon) .setContentTitle ("Event tracker") .setContentText ("Events received") NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle (); String [] events = new String [6]; inboxStyle.SetBigContentTitle ("Event tracker details:");... for (int item0; I < events.length; iTunes +) {inboxStyle.addLine (events [I]);} mBuilder.setStyle (inBoxStyle) .. 7.2.6 handle compatibility

Not all notification features are available for special versions. For example, the action button, which depends on the expanded notification, appears only in android 4.1 and later versions. Because only notifications expanded on this version are available. To ensure the compatibility of *, use NotificationCompat and its subclasses to create notifications. * use NotificationCompat.Builder. In addition, when you implement a notification, follow the following procedure:

1. No matter what version of the system the user uses, all the notification functions should be provided to all users. To do this, you need to verify that all the functions are available in an activity. You may want to add a new Activity. For example, if you want to use addAction () to control stopping and starting media playback, you first need to implement this control in an Activity.

two。 When the user clicks on the notification, make sure that all users can start an interface after clicking. We need to create a PendingIntent for Activity. Then use setContentIntent () to add PendingIntent to the notification.

7.3 manage notifications

When you need to process a notification multiple times for the same type of event, you should avoid regenerating a new notification each time. You should consider updating the previous notification, either changing some values or adding some values. For example, Gmail notifies the user that the new email has been received, and unread messages will be incremented. In fact, they have not received a notification message for processing. This is called "stacking" notification.

7.3.1 Update Notification

Of course, knowledge can be updated, use the notification ID to update it, and call NotificationManager.notify (ID, notification). If the previous notification is still visible, it is updated from the content of the Notification object. If the previous notification has been dismiss dropped, a new notification will be created. The following code demonstrates a notification update and displays the number of events

MNotificationManager = (NotificationManager) getSystemService (Context.NOTIFICATION_SERVICE); / / Notification IDint notifyID = 1; mNotifyBuilder = new NotificationCompat.Builder (this) .setContentTitle ("New Message") .setContentText ("You've received new messages.") .setSmallIcon (R.drawable.ic_notify_status) numMessages = 0;. MNotifyBuilder.setContentText (currentText) .setNumber (+ + numMessages); / / because ID remains unchanged, existing notifications are updated mNotificationManager.notify (notifyID, mNotifyBuilder.build ()); 7.3.2 remove notifications

The method to remove notifications is as follows:

1. Users notify via personal or "Clear All" dismiss

two。 The user clicks the notification and you call the setAutoCancel () method when you create the notification

3. You call the cancel () method based on the specified notification ID. This method also deletes notifications in progress

4. You call cancelAll (), which will delete all your previous notifications

7.4 keep navigating when starting an Activity

When you launch an Activity from a notification, you must save the user's tone navigation experience. Clicking the back key will have the same effect as clicking the Home key. To save the navigation user experience, you should start Activity in a new task. How to set up PendingIntent for a given new task depends on the nature of the Activity you start. There are usually two situations:

1. Conventional activity

When Activity is often started, set PendingIntent to start a new task and provide PendingIntent with a background stack to replicate the application's normal click on the Back key. Demonstrate this notification from Gmail APP. When you click on the notification when a message appears, you will see the message itself. When you click the back key, you will Gmail back to the Home screen, just as you have entered the Gmail, from Gmail to the Home screen.

two。 Special activity

This kind of Activity, in a sense, Activity extends the information provided by the notification, because it is difficult to display in the notification itself. In this case, set up PendingIntent to start a new task. There is no need to create a background stack because the Activity is not part of the positive flow of the application. The Home screen will still be displayed after clicking the back key.

7.4.1 set up a regular activity through PendingIntent

1. Define the Activity level of your application in manifest.

◆ supports Android 4.0.3 and earlier. Add child nodes under the node. Represents the relationship between the parent Activity and the child Activity. Set under the node

Android:name= "android.support.PARENT_ACTIVITY"

Android:value= ""

◆ supports Android4.1 and later versions. Add an android:parentActivityName attribute to the node

* supported xml codes

two。 Create a backend push stack based on Activity started by Intent:

◆ creates an Intent to start Activity

◆ creates a task stack by calling TaskStackBuilder.create ()

◆ adds the background push stack to the stack by calling addParentStack (). For each Activity level you define in manifest, the background stack contains an Intent object that starts the Activity. And this method also adds a flag to start the stack in the new task. Note: although the argument to addParentStack () is a reference to start Activity, this method does not actually add Intent to it.

◆ adds the Intent object by calling addNextIntent (). The object it adds is the intent object created by the top ◆.

◆ you can call TaskStackBuilder.editIntentAt () if you need to add parameters to the Intent object on the stack. This is sometimes necessary when the user uses the back key to navigate back to ensure that the target Activity displays meaningful data.

◆ calls getPendingIntent () to get a PendingIntent. Then you can call setContentIntent () to take this PendingIntent as an argument.

The following code snippet demonstrates this process

... Intent resultIntent = new Intent (this, ResultActivity.class); TaskStackBuilder stackBuilder = TaskStackBuilder.create (this); / / add background stack stackBuilder.addParentStack (ResultActivity.class); / / add Intent to top stack stackBuilder.addNextIntent (resultIntent); / / get a PendingIntent containing the entire background stack containing the entire back stackPendingIntent resultPendingIntent = stackBuilder.getPendingIntent (0, PendingIntent.FLAG_UPDATE_CURRENT); NotificationCompat.Builder builder = new NotificationCompat.Builder (this); builder.setContentIntent (resultPendingIntent); NotificationManager mNotificationManager = (NotificationManager) getSystemService (Context.NOTIFICATION_SERVICE); mNotificationManager.notify (id, builder.build ()); 7.4.2 set up a dedicated activity through PendingIntent

The following sections describe how to set up a dedicated activity through PendingIntent.

A dedicated Activity doesn't need a backstage stack, so you don't have to define its Activity level in manifest, and you don't have to call addParentStack () to build a backstage stack. Instead, use manifest to set the task options for Activity and create a PendingIntent by calling getActivity ():

1. Add the following attributes to the node in manifest.

◆ android:name= "activityclass"

Full class name

◆ android:taskAffinity= ""

Combined with the FLAG_ACTIVITY_NEW_TASK tag set in the code, it ensures that the activity does not enter the default task of the application.

◆ android:excludeFromRecents= "true"

The new task is excluded from Recents so that the user does not accidentally navigate back to it.

...

two。 Build and publish notifications

◆ creates an Intent to start Activity

◆ sets Activity to start in a new, empty task, which is handled by the setFlags () method, passing in FLAG_ACTIVITY_NEW_TASK and FLAG_ACTIVITY_CLEAR_TASK

◆ sets other required options for Intent

◆ creates a PendingIntent from Intent through getActivity (). You can use this PendingIntent object and pass it as an argument to setContentIntent ()

NotificationCompat.Builder builder = new NotificationCompat.Builder (this); Intent notifyIntent = new Intent (new ComponentName (this, ResultActivity.class)); notifyIntent.setFlags (FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK); PendingIntent notifyIntent = PendingIntent.getActivity (this, 0, notifyIntent PendingIntent.FLAG_UPDATE_CURRENT); builder.setContentIntent (notifyIntent); NotificationManager mNotificationManager = (NotificationManager) getSystemService (Context.NOTIFICATION_SERVICE) MNotificationManager.notify (id, builder.build ()); 7.5 shows the progress of the notification

The notification can include an animation progress indicator showing the status of the operation that the user is running. If you can estimate how long this will take, you can use an indicator in the form of "determinate" (a progress bar). If you can't estimate the time spent, use an indicator in the form of "indeterminate".

7.5.1 display a fixed time progress indicator

Display a definite progress bar, add bar to your notification by calling setProgress (), setProgress (max, progress, false), and then send out the notification.

... MNotifyManager = (NotificationManager) getSystemService (Context.NOTIFICATION_SERVICE); mBuilder = new NotificationCompat.Builder (this); mBuilder.setContentTitle ("Picture Download") .setContentText ("Download in progress") .setSmallIcon (R.drawable.ic_notification); new Thread (new Runnable () {@ Override public void run () {int incr; for (incr = 0; incr)

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report