2013年8月21日星期三

Android

 

Introduction

 

spoke before a blog using Toast the way Android prompt message. This blog explain in Android use Notification prompt message to the user, Notification overall effect is a kind of notification procedures generally through NotificationManager service to send Notification. In this blog, you will learn Notification of regular use, and customize the way the use, for each of the different ways, have provided examples showing the effect.

 

 

Notification

 

Notification , commonly known as the notification is a notification of having a global effect, it shows the top of the screen, the first will appear as a form of an icon when the user slides down when the notification show specific content.

 

Note: Because some of the Android version compatibility issues, in terms of the Notification, Android3.0 was a watershed in its previous building Notification recommended Notification.Builder build, while in Android3.0, it is generally recommended to use NotificationCompat.Builder build. This code environment are all completed in 4.3, if you use 4.1 what equipment testing, please note that compatibility issues.

 

notice generally through NotificationManager service to send a Notification object to accomplish, NotificationManager is an important system-level services, the object is located in the application framework layer, the application can use it as a global system to send notifications. This time you need to create a Notification object, used to carry the content of the notice. But generally in the actual use of the process, are generally not constructed directly Notification object, but it's an internal class used to instantiate an object NotificationCompat.Builder (Android3.0 used under Notification.Builder), and set various notification attributes, and finally through NotificationCompat.Builder.build () method to get a Notification object. When obtaining this object, you can use NotificationManager.notify () method to send notifications.

 

NotificationManager Notification Manager class is a class that this object is maintained by the system services, based on a single case model to obtain, it is generally not directly instantiate this object. In Activity, you can use Activity.getSystemService (String) method to get NotificationManager object, Activity.getSystemService (String) method can handle the Android system-level services, returns the corresponding object. Here need to return NotificationManager, so you can directly transfer Context.NOTIFICATION_SERVICE.

 

Although various attributes provided in the notification settings, but a notification object, there are several attributes that must be set up, other attributes are optional, you must set the following attributes:

 
      
  • small icon, use setSamllIcon () method to set.
  •   
  • title, use setContentTitle () method to set.
  •   
  • text content, use setContentText () method to set.
  •  
 

 

update and removal notification

 

using NotificationManager.notify () to send a notification when the need to pass an identifier that uniquely identifies this notification. For some scenes, not infinite add new notification, sometimes need to update the original notification information can be rewritten at this time built Notification, the use of the same identifier to notify a notification is sent notification of this time was used replaced by a new notification, play update notification effect.

 

for a notification when the status bar after the show, but after use, how to cancel it? Android gives us two ways to remove the notice, one is Notification own maintenance, use setAutoCancel () method to set whether to maintain, pass a boolean types of data. Another use of NotificationManager Notification Manager object to maintain it through the notify () to send a notification when the notification identifier Id to the specified operation notification, can cancel (int) to remove a specified notification can also be used cancelAll () Removes all notifications.

 

Use NotificationManager remove the specified notification example:

 
  
1         NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
2 mNotificationManager.cancel(0);
 
 

 

PendingIntent

 

a notification for the purpose, it displays a message is limited, generally only used to indicate a number of summary. But generally a short message, and can not express need to tell the entire contents of the user, so the need to bind an intent when the user clicks the notification, when calling an intent to demonstrate an Activity to display details. The Notification, do not use the regular Intent to pass an intent, but the use PendingIntent.

 

Let's talk about the difference between Intent and PendingIntent, PendingIntent Intent can be seen is the packaging, the name can be seen through the impending PendingIntent intent for processing, while the right place to deal with Intent intent. For the notification, it is a system level global notification is not intended to be sure that this execution time. When the application is executed outside PendingIntent because it holds the trigger App's Context, makes external App can be enforced if the current App PendingIntent in the Intent, even if the execution App triggered the notification does not exist, but also through the presence PendingIntent Lane Context perform as usual Intent, and can also handle Intent brought additional information.

 

PendingIntent provides several static getXxx () method is used to obtain for different scenarios PendingIntent object. Generally need to pass several parameters are normal, only introduce a flag argument, the constructor is used to identify PendingIntent selection:

 
      
  • FLAG_CANCEL_CURRENT: If you build the PendingIntent already exists, cancel the previous one, to re-build a.
  •   
  • FLAG_NO_CREATE: PendingIntent if the previous one does not exist, will not build it.
  •   
  • FLAG_ONE_SHOT: indicate here PendingIntent constructed only once.
  •   
  • FLAG_UPDATE_CURRENT: If you build the PendingIntent already exists, replace it commonly used.
  •  
 

 

Notification visual style

 

Notification There are two kinds of visual style, one is the standard view (Normal view), one is the large view (Big view). Standard view in Android versions are common, but for large view, the only support Android4.1 + version.

 

learned from an official document, a standard view of the size of the display to be maintained at 64dp high standard width of the screen. Standard view main contents of the notification about a few:

 

 
      
  1. notification header.
  2.   
  3. large icons.
  4.   
  5. contents of the notice.
  6.   
  7. notification message.
  8.   
  9. small icons.
  10.   
  11. notice of the time, usually the time for the system can also be used setWhen () settings.
  12.  
 

following through an example that mimics the effect of the above notification.

 
  
 1 btnNotification.setOnClickListener(new View.OnClickListener() { 
2
3 @Override
4 public void onClick(View v) {
5 Bitmap btm = BitmapFactory.decodeResource(getResources(),
6 R.drawable.msg);
7 NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
8 MainActivity.this).setSmallIcon(R.drawable.msg)
9 .setContentTitle("5 new message")
10 .setContentText("twain@android.com");
11 mBuilder.setTicker("New message");//第一次提示消息的时候显示在通知栏上
12 mBuilder.setNumber(12);
13 mBuilder.setLargeIcon(btm);
14 mBuilder.setAutoCancel(true);//自己维护通知的消失
15
16 //构建一个Intent
17 Intent resultIntent = new Intent(MainActivity.this,
18 ResultActivity.class);
19 //封装一个Intent
20 PendingIntent resultPendingIntent = PendingIntent.getActivity(
21 MainActivity.this, 0, resultIntent,
22 PendingIntent.FLAG_UPDATE_CURRENT);
23 // 设置通知主题的意图
24 mBuilder.setContentIntent(resultPendingIntent);
25 //获取通知管理器对象
26 NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
27 mNotificationManager.notify(0, mBuilder.build());
28 }
29 });
 
 

display:

 

 

 

while for large view (Big View) is concerned, it can only display the details area 256dp height of content, and only after Android4.1 + devices only support the view that it is not the same than the standard place, need using the setStyle () method to set its general effect is as follows:

 


setStyle () to pass a NotificationCompat.Style object, which is an abstract class, Android provides us with three implementation class used to display different scenes. Are:

 
      
  • NotificationCompat.BigPictureStyle, in the details section displays a 256dp height bitmap.
  •   
  • NotificationCompat.BigTextStyle, in the details section displays a large block of text.
  •   
  • NotificationCompat.InboxStyle, in the details section displays a line of text.
  •  
 

if only display a picture using BigPictureStyle is the most convenient; If you need to display a rich text message, you can use BigTextStyle; if only for displaying a text message, you can then use the InboxStyle. An example will be followed to show InboxStyle use, imitating the picture above the display.

 

implementation code:

 
  
 1         btnBigViewNotification.setOnClickListener(new View.OnClickListener() { 
2
3 @Override
4 public void onClick(View v) {
5
6 Bitmap btm = BitmapFactory.decodeResource(getResources(),
7 R.drawable.msg);
8 Intent intent = new Intent(MainActivity.this,
9 ResultActivity.class);
10
11 PendingIntent pendingIntent = PendingIntent.getActivity(
12 MainActivity.this, 0, intent,
13 PendingIntent.FLAG_CANCEL_CURRENT);
14
15 Notification noti = new NotificationCompat.Builder(
16 MainActivity.this)
17 .setSmallIcon(R.drawable.msg)
18 .setLargeIcon(btm)
19 .setNumber(13)
20 .setContentIntent(pendingIntent)
21 .setStyle(
22 new NotificationCompat.InboxStyle()
23 .addLine(
24 "M.Twain (Google+) Haiku is more than a cert...")
25 .addLine("M.Twain Reminder")
26 .addLine("M.Twain Lunch?")
27 .addLine("M.Twain Revised Specs")
28 .addLine("M.Twain ")
29 .addLine(
30 "Google Play Celebrate 25 billion apps with Goo..")
31 .addLine(
32 "Stack Exchange StackOverflow weekly Newsl...")
33 .setBigContentTitle("6 new message")
34 .setSummaryText("mtwain@android.com"))
35 .build();
36
37 NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
38 mNotificationManager.notify(0, noti);
39 }
40 });
 
 

showing the effect of:

 

 

 

progress bar style notification

 

For a standard notification message is displayed and sometimes is not necessarily static, but also a progress bar can be set to display the progress of the transaction is complete.

 

Notification.Builder classes provide a setProgress (int max, int progress, boolean indeterminate) method is used to set the progress bar, max for setting the maximum number of progress, progress for setting the current progress, indeterminate for progress to determine whether it is a progress bar only. By indeterminate settings, you can achieve progress in two different styles, one is a progress (false), one is circulating (false). The following two examples were used to demonstrate:

 

a progress bar, implementation code:

 
  
 1         btnProgreNotification.setOnClickListener(new View.OnClickListener() { 
2 @Override
3 public void onClick(View v) {
4 manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
5 builder = new NotificationCompat.Builder(MainActivity.this)
6 .setSmallIcon(R.drawable.ic_launcher)
7 .setContentTitle("Picture Download")
8 .setContentText("Download in progress");
9 builder.setAutoCancel(true);
10 //通过一个子线程,动态增加进度条刻度
11 new Thread(new Runnable() {
12 @Override
13 public void run() {
14 int incr;
15 for (incr = 0; incr <= 100; incr += 5) {
16 builder.setProgress(100, incr, false);
17 manager.notify(0, builder.build());
18 try {
19 Thread.sleep(300);
20 } catch (InterruptedException e) {
21 Log.i(TAG, "sleep failure");
22 }
23 }
24 builder.setContentText("Download complete")
25 .setProgress(0, 0, false);
26 manager.notify(0, builder.build());
27 }
28 }).start();
29 }
30 });
 
 

display:

 

 

for circulating the progress bar, the following is the implementation code:

 
  
 1         btnProNotification.setOnClickListener(new View.OnClickListener() { 
2 @Override
3 public void onClick(View v) {
4 manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
5 builder = new NotificationCompat.Builder(MainActivity.this)
6 .setSmallIcon(R.drawable.ic_launcher)
7 .setContentTitle("Picture Download")
8 .setContentText("Download in progress");
9 builder.setProgress(0, 0, true);//设置为true,表示流动
10 manager.notify(0, builder.build());
11
12 //5秒之后还停止流动
13 new Thread(new Runnable() {
14 @Override
15 public void run() {
16 try {
17 Thread.sleep(5000);
18 } catch (InterruptedException e) {
19 e.printStackTrace();
20 }
21 builder.setProgress(100, 100, false);//设置为true,表示刻度
22 manager.notify(0, builder.build());
23 }
24 }).start();
25 }
26 });
 
 

results show:

 

 

 

custom notification

 

and Toast like notification can also use custom XML from custom styles, but for notification purposes, because of its global nature, and not simply through inflate inflate a View, because it may trigger a notification when the response The App is closed, you can not get when the specified XML layout file. So you need to use a separate one RemoteViews class operation.

 

RemoteViews, describes a view hierarchy structure can be displayed in another process. Hierarchy also from the layout file "bloat" out of a view, this class provides some basic operations seeking to change the content of its expansion.

 

RemoteViews provides several constructors, the general use RemoteViews (String packageName, int layoutId). The first parameter is the package name, the second layout resource Id. When you get to the RemoteViews object, you can use it for a series of setXxx () method through the control's Id set the control's properties. Finally use NotificationCompat.Builder.setContent (RemoteViews) method to set it to a Notification in.

 

below presents an example of it:

 

custom layout XML code:

 
  
 1 <?xml version="1.0" encoding="utf-8"?> 
2 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
3 android:layout_width="match_parent"
4 android:layout_height="match_parent"
5 android:padding="10dp" >
6
7 <ImageView
8 android:id="@+id/imageNo"
9 android:layout_width="wrap_content"
10 android:layout_height="match_parent"
11 android:layout_alignParentLeft="true"
12 android:layout_marginRight="10dp" />
13
14 <TextView
15 android:id="@+id/titleNo"
16 android:layout_width="wrap_content"
17 android:layout_height="wrap_content"
18 android:layout_toRightOf="@id/imageNo" />
19
20 <TextView
21 android:id="@+id/textNo"
22 android:layout_width="wrap_content"
23 android:layout_height="wrap_content"
24 android:layout_below="@id/titleNo"
25 android:layout_toRightOf="@id/imageNo" />
26
27 </RelativeLayout>
 
 

implementation code:

 
  
 1         btnCustomNotification.setOnClickListener(new View.OnClickListener() { 
2 @Override
3 public void onClick(View v) {
4 RemoteViews contentViews = new RemoteViews(getPackageName(),
5 R.layout.custom_notification);
6 //通过控件的Id设置属性
7 contentViews
8 .setImageViewResource(R.id.imageNo, R.drawable.btm1);
9 contentViews.setTextViewText(R.id.titleNo, "自定义通知标题");
10 contentViews.setTextViewText(R.id.textNo, "自定义通知内容");
11
12 Intent intent = new Intent(MainActivity.this,
13 ResultActivity.class);
14
15 PendingIntent pendingIntent = PendingIntent.getActivity(
16 MainActivity.this, 0, intent,
17 PendingIntent.FLAG_CANCEL_CURRENT);
18 NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
19 MainActivity.this).setSmallIcon(R.drawable.ic_launcher)
20 .setContentTitle("My notification")
21 .setTicker("new message");
22 mBuilder.setAutoCancel(true);
23
24 mBuilder.setContentIntent(pendingIntent);
25 mBuilder.setContent(contentViews);
26 mBuilder.setAutoCancel(true);
27 NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
28 mNotificationManager.notify(10, mBuilder.build());
29 }
30 });
 
 

results show:

 

 

 

set prompt response

 

for some notifications, you need to call some of the device's resources, allowing users to more quickly find new notification, the general response that can be set are: ringtones, flash, vibration. For these three attributes, NotificationCompat.Builder provides three methods set:

 
      
  • setSound (Uri sound): Set a ringtone, notification time for response. Uri pass a parameter in the format "file :/ / / mnt/sdcard/Xxx.mp3".
  •   
  • setLights ( int argb, int onMs, int offMs ): Set the front LED lights blink rate, sustained milliseconds, pause milliseconds.
  •   
  • setVibrate (long [] pattern): setting the vibration mode to a long array holds millisecond intervals vibration.
  •  
 

Most of the time, we do not need to set a specific response effect, users only need to follow the effect of system notification on the device can be, then you can use setDefaults (int) method to set the default response parameters, in the Notification, the Use constants defined its parameters, we can simply use:

 
      
  • DEFAULT_ALL: ringtones, flash, vibration are the system default.
  •   
  • DEFAULT_SOUND: system default ringtone.
  •   
  • DEFAULT_VIBRATE: system default vibration.
  •   
  • DEFAULT_LIGHTS: system default flash.
  •  
 

In Android, if you need to access the hardware device, it is the need to be licensed, so you need to add in the manifest file AndroidManifest.xml two authorization were granted permission to visit vibrators with Flash:

 
  
1     <!-- 闪光灯权限 --> 
2 <uses-permission android:name="android.permission.FLASHLIGHT"/>
3 <!-- 振动器权限 -->
4 <uses-permission android:name="android.permission.VIBRATE"/>
 
 

 

because it is only one attribute set, and most of the time, you can use the system setup here is not to provide the sample code.

 

source download

 

Summary

 

Android notification be more commonly used in a function, you can keep yourself App, forever, the user does not go to the App, it also provides the possibility of interaction with the user.

 

Please support the original, respect for the original, reproduced please indicate the source. Thank you.

没有评论:

发表评论