Android message prompt: AlertDialog, Toast, and Notification usage, androidalertdialog

Source: Internet
Author: User

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:

  • Builder. setLargeIcon (Bitmap object); // you can specify a large image.
  • Builder. setProgress (Max, value, false); // set the notification to display as a progress bar
  • When you manually set setContentView (RemoteView object), you must also set setContentIntent
  • To trigger a Notification, you need to pass it and the reference ID of an integer to the notify method of Notification Manager. If a Notification Builder is already used, you can use the builder. GetNotification ();
  • To update a Notification, you need to pass the same ID to the Notification Manager. You can pass in the same Notification object and a different Notification object, as long as the ID value is the same, the new Notification will replace the original one. To update the Notification without causing the associated flashing lights, audios, and vibrations, you can use icationicationbuilder. setOnlyAlertOnce (true); icationicationmanager can also be used. flags = Notification. FLAG_ONLY_ALERT_ONCE;
  • Generally, the notification is canceled after the operation is clicked: after the operation is clicked, the user's setAutoCancel (true) is automatically canceled );
  • You can also use icationicationmanager manager. cancel (ID );
  • Configure continuous and continuous Notification:

    • Through the FLAG_INSISTENT and FLAG_ONGOING_EVENT flags of Notification, you can configure Notification to be continuous and discontinuous.

      • Continuous Notification indicates the ongoing events (such as downloading)

        • Use builder. setOngoing (true );
        • You can also use Notification. flags = FLAG_ONGOING_EVENT. The front-end service must have continuous Notification (playing music ?)
      • Continuous notifications repeat audio, vibration, and screen flashes until they are canceled. These notifications are usually used for events that require immediate attention and processing.


        • You can use notification. flags = Notification. FLAG_INSISTENET, which is not recommended for third-party applications. Therefore, this method is not available in builder.

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.