Android message prompt: AlertDialog, Toast, and Notification usage, androidalertdialog
This article mainly introduces the components that Android uses frequently for message prompts: ALertDialog, Toast, and Notification, as well as their basic usage, discusses some advanced topics, and summarizes some common problems in the development process.
Code address: https://github.com/JueYingCoder/AndroidNotice
First, we will give you an intuitive understanding of these three message prompting mechanisms:AlertDialog Toast, Notification
Next, we will introduce the application scenarios and usage of these three mechanisms respectively.
AlertDialog
Use Cases: The use of AlertDialog in applications is still very common. It is often used for users to make certain choices, and such a choice must be simple interaction, if it is complex, you should use another Activity to undertake rather than AlertDialog, basic usage and high-level theme: Please refer to the article I have written before, introduce very detailed: http://blog.csdn.net/qwm8777411/article/details/45420451
Toast usage
Scenario: Toast has two notable features:
1. The Toast prompts that the message will not get the focus;
2. The Toast prompts that the message will automatically disappear after a period of time.
Based on the preceding two points, Toast is often used to prompt simple messages that do not need to interact with users,
Basic usage: You can create a simple Toast for text prompts or custom View Toast.
Basic Steps for using a simple Toast:
1. Create a Toast object 2 by using the static Toast method makeText (), call other methods of Toast to set attributes 3, and call the show () method to display it;
It is easy to use, most of which are used to display simple text prompts. If the application needs to display complex prompts such as various slices and lists, it is generally completed using a dialog box. Of course, you can useSetView ()Methods To implement a customized Toast view;
Simple Toast for text display
Toast toast = ToastmakeText (context, "text message", Toast. LENGTH_SHORT); toast. show ();
Toast of the custom View:
Toast toast = new Toast (Context context); toast. setGravity (Gravity. CENTER,); // set the display position toast. setView (R. layout. toast_view); // sets the toast. setDuration (Toast. LENGTH_SHORT); // sets the display duration toast. show ();
Use of Notification
** Application Scenario: ** Notification is the preferred mechanism for invisible application components (BroadcastReceiver, Service, and inactive Activity) to remind users, events that require their attention have already occurred. It can also be used to indicate a continuously running background Service.
Notification is a method in which an application notifies you of certain events. You do not need to see an Activity. Notification is handled by icationicationmanager. The following functions are currently available:
- Show status bar icon:
- Flashing
- Vibrate mobile phones
- Sound reminder
- Use interactive operations in the notification tray to broadcast Intent
Basic Steps for using Notification:
1. CreateIcationicationmanager
NotificationManager nm= (NotificationManager)getSystemService(SEREVICE_NOTIFICATION);
2. General method creationNotification
Int icon = R. drawable. icon; String ticker = "a new message"; Long when = System. currentTimeMillis; // corresponding to the Notification display icon. The ticker text and display order are arranged by time. notification = new Notification (icon, ticker, when );
3. UseNotification BuilderCreate Notification
Another way to create Notification is as follows,Notification BuilderIt was introduced in Android 3.0 to simplify the above process;
Notification. builder builder = new Notification. builder (Context context); builder. setSmallcon (R. drawable. icon); builder. setDefaults (); NotificationManager manager = (icationicationmanager) getSystemService (icationication_service);/** the ID value here is the unique identifier of Notification, */manager. notify (int id, builder. build (); // trigger Notification
Through the above steps, we can create a Notification and display it in the Notification bar, but there are several points to note:
// You can also set the Notification property setLastEventInfo (context, string ticker, string content, PendingIntent intent) using the following methods; // If the ID is the same, it will be updated rather than rebuilt (such as continuous download) manager. notify (ID, notification); // update notification: The notification should not be kept in the notification bar. to reuse or update the notification, you can use a counter setNumber (4); // clear the notification: manager. cancel (ID); // or use builder. setAutoCancel (true );
Use the Notification of the custom View:
RemoteView: RemoteView view = new RemoteView (getPackageName (), R. layout. remote); // custom view notification. setView (view );
With the above knowledge, we can implement a comprehensive exercise to achieve the following results:
MainActivity.java
:
Public class MainActivity extends ActionBarActivity implements View. onClickListener {private Button simpleToast, customToast; private Button 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 () {case R. id. simple_toast: simpleToast (); break; case R. id. custom_toast: customToast (); break; case R. id. simple_notification: simpleNotification (); break; case R. id. custom_notification: customNotification (); break;} public void simpleToast () {// display a simple text information Toast toast = Toast. makeText (MainActivity. this, "This is a simple Toast", Toast. LENGTH_SHORT); toast. show ();} public void customToast () {Toast toast = new Toast (MainActivity. this); // set the Toast display position toast. setGravity (Gravity. BOTTOM, 0, 0); // sets the Toast view. Here we add an image LinearLayout layout = new LinearLayout (getApplicationContext (); layout. setOrientation (LinearLayout. VERTICAL); ImageView imageView = new ImageView (getApplicationContext (); imageView. setImageResource (R. mipmap. touxiang); // set an image layout. addView (imageView, new LinearLayout. layoutParams (LinearLayout. layoutParams. MATCH_PARENT, LinearLayout. layoutParams. MATCH_PARENT); toast. setView (layout); // set the display duration toast. setDuration (Toast. LENGTH_SHORT); toast. show ();} public void simpleNotification () {// obtain icationicationmanager manager = (icationicationmanager) getSystemService (icationication_service); // construct a Notification. builder object icationicationcompat. builder builder = new NotificationCompat. builder (MainActivity. this); // set the Notification icon builder. setSmallIcon (R. mipmap. ic_launcher); // builder. setLargeIcon (myIcon); // set Notification tickertext builder. setTicker ("A new Message"); // set the notification question builder. setContentTitle ("A new notification"); // set the notification content builder. setContentText ("This is content text"); builder. setContentInfo ("Info"); // The builder can automatically cancel Setting Notifications. setAutoCancel (true); // sets the time-ordered Notification builder displayed in the Notification bar. setWhen (System. currentTimeMillis (); // you can specify other physical attributes, including notification prompts, vibrations, and led flashes at the bottom of the screen. setSound (RingtoneManager. getDefaultUri (RingtoneManager. TYPE_NOTIFICATION); // set a local file as the prompt builder. setVibrate (new long [] {1000,1000, 1000,1000}); builder. setLights (Color. RED,); // set the Intent to be started after the notification is clicked. Pay attention to the PendingIntent usage and the four parameters (context, int requestCode, Intent, int flags); Intent intent = new Intent (MainActivity. this, AnotherActivity. class); PendingIntent pi = PendingIntent. getActivity (MainActivity. this, 0, intent, 0); builder. setContentIntent (pi); // instantiate Notification notification = builder. build (); // define y (int id, notification object); id indicates each notification manager. notify (1, notification);} public void customNotification () {icationicationmanager manager = (icationicationmanager) getSystemService (icationication_service); NotificationCompat. builder builder = new NotificationCompat. builder (MainActivity. this); builder. setTicker ("playing music"); builder. setSmallIcon (R. mipmap. ic_launcher); builder. setWhen (System. currentTimeMillis (); builder. setAutoCancel (true); // set the custom RemoteView RemoteViews view = new RemoteViews (getPackageName (), R. layout. remote_view); builder. setContent (view); PendingIntent pi = PendingIntent. getActivity (MainActivity. this, 1, new Intent (MainActivity. this, AnotherActivity. class), 0); builder. setContentIntent (pi); builder. setOngoing (true); manager. notify (2, builder. build ());}}
Through the above exercises, we have basically mastered the usage of Notification. Below are commonSome advanced topics:
Attaches a click listener to the View in RemoteView:
You need to input the associated View resource ID and PendingIntent after the view is clicked.
Intent I = new Intent (BUTTON_CLICK); PendingIntent pi = PendingIntent. getActivity (MyActivity. this, 2. I, 0); notification. contentView. setOnClickPendingIntent (R. id. status_progress, pi); // clicking any area in the Notification layout that is not bound in this way will trigger the Notification content Intent
Conclusion: Design useful notifications:
The notification function of the Android platform is so strong that you may be using it excessively. The following are some good suggestions:
* Use notifications only when the application is not on the frontend. Otherwise, use Toast and AlertDialog * to select the desired notification type and frequency, and when to trigger the notification * regularly clear the notification to avoid providing outdated messages to the user * use a soft notification language when you are not sure * Ensure that Ticker text is in the notification, the title and Body contain useful messages and run meaningful Intent;
The notification framework is lightweight but powerful. However, software such as alarm and stock monitor may need to provide functions beyond the notification framework. In this case, they may use background services and use their own complete Activity when a specific event arrives. Applications can use notifications to interact with users, surpassing their own Activity boundaries. Notifications can be either visual or audible, or use the vibration function of the device. You can use various methods to customize notifications to send more information to users. However, it is important to note that the notification should be appropriate and the quantity should be required, otherwise the user will be bored with the application.
References:
* Android 4 advanced programming (3rd) * Android In Practice * Android mobile application development Volume 2: Improved