SoFunction
Updated on 2025-03-11

Detailed explanation of Notification and NotificationManger in Android

Android Status Bar Reminder

AlertDialog can also be used in Android, but we must use it with caution, because when using AlertDialog, the operation being performed by the user will be interrupted because the current focus is obtained by AlertDialog. We can imagine that when the user is having fun playing games, a text message comes. If the SMS is reminded by AlertDialog at this time, the user must first process this reminder so that the game can continue. Users may be pissed to death. Using Notification will not cause these troubles, and users can watch this text message after playing the game. Therefore, in development, you should choose the appropriate control according to actual needs.

step:

1. Add layout objects

Copy the codeThe code is as follows:

<Button
android:
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="showNotification" />

<Button
android:
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="cancelNotification" />


2. Modify the MianActivity inheritance Activity and implement the interface OnClickListener
Copy the codeThe code is as follows:

public class MainActivity extends Activity implements OnClickListener {
 private Context mContext = this;
 private Button showbtn, calclebtn;
 private Notification noti;
 private NotificationManager notiManger;
 private static int NOTIFICATION_ID = 0x0001;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  (savedInstanceState);
  setContentView(.activity_main);
  setUpViews();
 }

 private void setUpViews() {
  showbtn = (Button) findViewById();
  calclebtn = (Button) findViewById();
  noti = new Notification(.ic_launcher, "this is a notification", ());
= Notification.DEFAULT_SOUND;// Use the default prompt sound
|= Notification.DEFAULT_VIBRATE;// Add vibration
notiManger = (NotificationManager) (mContext.NOTIFICATION_SERVICE);//Get NofificationManger object
(this);//Let Activity implement the interface OnClickListener can simply add button click response events through these two lines of code
  (this);
 }

// Button click event response
 @Override
 public void onClick(View v) {
  if (v == showbtn) {
   Intent intent = new Intent((),());
// Set Intent.FLAG_ACTIVITY_NEW_TASK
   (Intent.FLAG_ACTIVITY_NEW_TASK);
   PendingIntent contentIntent = (this, 0, intent, 0);
// (context, contentTitle, contentText, contentIntent) Settings (context, title, content, PendingInteng)
(this, "10086", "You will be exempted from all phone bills from now on", contentIntent);
// Send notification (message ID, notification object)
   (NOTIFICATION_ID, noti);
  } else if (v == calclebtn) {
// Cancel notification (id)
   (NOTIFICATION_ID);
  }
 }
}