This article focuses on the components that Android often uses for message hinting: Alertdialog, TOAST, notification usage scenarios, and their basic usage, explore some advanced topics, and finally summarize some of the common problems in the development process.
Let's start with a visual understanding of these three message-hinting mechanisms, namely Alertdialog Toast, Notification
Next, we introduce the corresponding usage scenarios and usage of the three mechanisms respectively.
Alertdialog
Usage Scenarios : The use of Alertdialog in the application is still very common, often used to let the user make a choice, and this choice must be simple interaction, if it is complex should use another activity to undertake rather than alertdialog, Basic usage and advanced topics: Please refer to this article which I have written before, the description is very detailed: http://blog.csdn.net/qwm8777411/article/details/45420451
Use of Toast
Usage Scenario: First Toast has two notable features:
1,toast tip message does not get focus;
2,toast prompts the message to automatically disappear over time.
Based on two points above, toast is often used to prompt some simple messages that do not require interaction with the user.
Basic usage: You can create a simple toast for text hints, or you can create a toast for a custom view
Basic steps for using simple toast:
1,通过Toast的静态方法makeText()创建一个Toast对象2,调用Toast的其他方法设置属性3,调用show()方法将它显示出来;
It is relatively simple to use, mostly to display simple text hints, if the application needs to display the pieces, lists and other complex hints, general Use dialog box to complete. Of course, a custom toast view can be implemented through the Setview () method;
Simple toast that displays text
Toast toast=ToastmakeText(context,"文本消息",Toast.LENGTH_SHORT); toast.show();
To customize the toast of a view:
Toast toast=new Toast(Context context); toast.setGravity(Gravity.CENTER,0,0);//设置显示位置 toast.setView(R.layout.toast_view);//设置视图 toast.setDuration(Toast.LENGTH_SHORT);//设置显示时长 toast.show();
Use of notification
* * Usage Scenario: **notification is the preferred mechanism for invisible application components (Broadcastreceiver, Service, inactive activity) to alert users that events that require their attention have already occurred. It can also be used to indicate a continuous running background service.
Notification is a way for an application to remind a user of certain events, which are handled by Notificationmanager without an activity visible, and currently include the following features:
- Display the status bar icon :
- Flashing lights
- Let the phone vibrate
- Make a sound reminder
- Use interactive actions in the notification tray to broadcast intent
Basic steps for using notification:
1, create Notificationmanager
NotificationManager nm= (NotificationManager)getSystemService(SEREVICE_NOTIFICATION);
2, general method to create Notification
int icon=R.drawable.icon; String ticker="一条新消息"; when=System.currentTimeMillis; //分别对应通知显示的图标,ticker文字和显示顺序按时间排列 Notification notification=new Notification(icon,ticker,when);
3, create Notification using Notification Builder
Notification there is another way to create,Notification Builder is introduced in Android 3.0, simplifying the process;
Notification.Builder builder=new Notification.Builder(Context context); builder.setSmallcon(R.drawable.icon); builder.setDefaults(); NotificationManager manager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE); /* *此处的ID值作为Notification的唯一标示, */ manager.notify(int id,builder.build());//触发Notification
With the above steps we can already create a notification and display it in the notification bar, but there are a few things to note:
//也可以通过以下方法设置Notification属性 setLastEventInfo(context,string ticker,string content,PendingIntent intent); //如果ID相同的话将被更新而不是重建(例如连续下载) manager.notify(ID,notification); //更新通知:通知不应该一直在通知栏里,需要复用或者更新通知,可以使用一个计数器 setNumber(4); //清除通知: manager.cancel(ID); //或者使用 builder.setAutoCancel(true);
Using the notification of a custom view:
RemoteView:RemoteView view=new RemoteView(getPackageName(),R.layout.remote);//自定义的视图notification.setView(view);
With the knowledge above, we will implement a comprehensive exercise to achieve the effect:
MainActivity.java
:
Public class mainactivity extends actionbaractivity implements View . Onclicklistener { PrivateButton Simpletoast,customtoast;PrivateButton simplenotification,customnotification;@Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main); Simpletoast= (Button) Findviewbyid (r.id.simple_toast); Customtoast= (Button) Findviewbyid (r.id.custom_toast); simplenotification= (Button) Findviewbyid (r.id.simple_notification); customnotification= (Button) Findviewbyid (r.id.custom_notification); Simpletoast.setonclicklistener ( This); Customtoast.setonclicklistener ( This); Simplenotification.setonclicklistener ( This); Customnotification.setonclicklistener ( This); }@Override Public void OnClick(View view) {Switch(View.getid ()) { CaseR.id.simple_toast:simpletoast (); Break; CaseR.id.custom_toast:customtoast (); Break; CaseR.id.simple_notification:simplenotification (); Break; CaseR.id.custom_notification:customnotification (); Break; } } Public void Simpletoast(){//Display a simple text messageToast Toast=toast.maketext (mainactivity. This,"This was a simple Toast", Toast.length_short); Toast.show (); } Public void Customtoast() {Toast toast=NewToast (mainactivity. This);//Set the display location of toastToast.setgravity (Gravity.bottom,0,0);//Set toast view, here we add a pictureLinearLayout layout=NewLinearLayout (Getapplicationcontext ()); Layout.setorientation (linearlayout.vertical); ImageView imageview=NewImageView (Getapplicationcontext ()); Imageview.setimageresource (R.mipmap.touxiang);//Set up a pictureLayout.addview (ImageView,NewLinearlayout.layoutparams (linearlayout.layoutparams.match_parent,linearlayout.layoutparams.match_parent)); Toast.setview (layout);//Set Display durationToast.setduration (Toast.length_short); Toast.show (); } Public void simplenotification(){//Get Notificationmanager instancesNotificationmanager manager= (Notificationmanager) Getsystemservice (Notification_service);//Construct Notification.builder objectNotificationcompat.builder builder=NewNotificationcompat.builder (mainactivity. This);//Set notification iconBuilder.setsmallicon (R.mipmap.ic_launcher);//builder.setlargeicon (Myicon); //Set notification TickertextBuilder.setticker ("A new Message");//Set the title of the notificationBuilder.setcontenttitle ("A New Notification");//Set the content of the notificationBuilder.setcontenttext ("This is content text"); Builder.setcontentinfo ("Info");//settings notifications can be automatically canceledBuilder.setautocancel (true);//Set the notification displayed in the notification bar to be sorted by timeBuilder.setwhen (System.currenttimemillis ());//Set other physical properties, including notification tones, vibrations, led flashes at the bottom of the screenBuilder.setsound (Ringtonemanager.getdefaulturi (ringtonemanager.type_notification));//Set a local file here for the BeepBuilder.setvibrate (New Long[]{ +, +, +, +}); Builder.setlights (Color.Red,0,1);//Set the Intent that will be launched after the notification is clicked, it is necessary to pay attention to the use of pendingintent, four parameters in the construction method (Context,int requestcode,intent,int flags);Intent intent=NewIntent (mainactivity. This, Anotheractivity.class); Pendingintent pi=pendingintent.getactivity (mainactivity. This,0, Intent,0); Builder.setcontentintent (PI);//instantiation of notificationNotification Notification=builder.build ();//notify (int id,notification object); ID is used to mark each notificationManager.notify (1, notification); } Public void customnotification() {Notificationmanager manager= (notificationmanager) Getsystemservice (Notification_service); Notificationcompat.builder builder=NewNotificationcompat.builder (mainactivity. This); Builder.setticker ("Music is playing"); Builder.setsmallicon (R.mipmap.ic_launcher); Builder.setwhen (System.currenttimemillis ()); Builder.setautocancel (true);//Set the custom RemoteViewRemoteviews view=NewRemoteviews (Getpackagename (), R.layout.remote_view); Builder.setcontent (view); Pendingintent pi=pendingintent.getactivity (mainactivity. This,1,NewIntent (mainactivity. This, Anotheractivity.class),0); Builder.setcontentintent (PI); Builder.setongoing (true); Manager.notify (2, Builder.build ()); } }
We have basically mastered the use of notification through the above exercises, and here are some of the high-level topics that are commonly used:
Builder.setlargeicon (Bitmap object); Set a large picture
- Builder.setprogress (Max,value,false);//Set notification to display as a progress bar
- When setting Setcontentview (RemoteView object) manually, you must also set the Setcontentintent
- To trigger a notification, you need to pass it and an integer reference ID to the Notify method of the Notification Manager. If you have used a notification
Builder constructs, you can use builder. GetNotification ();
- To update a notification, you need to pass the same ID to notification Manager, either passing in an identical notification object, or passing in a different, as long as the ID value is the same, The new notification will replace the original, to update the notification without causing the associated strobe, audio, and vibration, you can use Notificationbuilder.setonlyalertonce (true); In addition, notificationmanager.flags=notification.flag_only_alert_once can be used;
- It is usually a click-to-Cancel notification: Automatically cancels your setautocancel when clicked (true);
- You can also use Notificationmanager manager.cancel (ID);
Configure continuous and continuous notification: * The notification can be configured as continuous and discontinuous through the notification flag_insistent and flag_ongoing_event flags. *
Notification that are marked as persistent can represent events that are currently in progress (such as downloading) *
Use Builder.setongoing (TRUE); *
You can also use Notification.flags=flag_ongoing_event, the front service must have a continuous notification (music playback?). )
*
The continuous notification repeats the audio, vibrate, and splash screen until it is canceled. These notification are typically used for events that require immediate attention and handling, and are generally not commonly used
* *
Can be used by notification.flags=notification.flag_insistenet, not recommended for third-party applications, so there is no such method in builder
To attach a click listener to a view in RemoteView:
需要传入关联的View资源ID和当view点击后的PendingIntent
Intent i=new Intent(BUTTON_CLICK); PendingIntent pi=PendingIntent.getActivity(MyActivity.this,2.i,0); notification.contentView.setOnClickPendingIntent(R.id.status_progress,pi); //单击Notification布局中任何没有采用这种方式绑定的区域将会触发Notification的内容Intent
Summary: Design useful notifications:
The notifications on the Android platform are so robust that you might be over-used, and here are some good suggestions:
* 只有在应用不处于前台是使用通知,否则使用Toast和AlertDialog* 允许用户选择他想要的通知类型和频率,以及在什么情况下触发通知* 经常性地清理通知以避免向用户提供过时的消息* 在不确定的情况下,使用柔和的通知语言* 确保在通知的Ticker文字,标题和正文包含有用的消息,并且运行有意义的Intent;
The notification framework is lightweight but powerful, but software such as alarms and stock monitors may need to provide functionality beyond the notification framework, in which case they may use a background service and use their full activity when a particular event arrives, and the application can use notifications to interact with the user. Beyond the bounds of their own activity. Notifications can be either visual or auditory, or use the device's vibration function. You can use a variety of methods to customize notifications to deliver richer information to users. However, it is important to note that notifications are appropriate and quantity-related, otherwise users will be bored with the application.
Resources:
* Android 4 高级编程(第3版)* Android In Practice* Android移动应用开发 卷2:提高篇
Android Message tip: Use of alertdialog, TOAST, notification