NotificationManager is the management class of status bar notifications, and is responsible for issuing notifications, clearing notifications and other operations.
NotificationManager is a system service that can be obtained through the getSystemService (NOTIFICATION_SERVICE) method.
Next I want to talk about the pop-up notification after Android 5.0.
The online method is:
//Step 1: Instantiate the notification bar constructor: builder =new ();//Instantiate the notification bar constructor, the parameters are required (Context type), and are the context of creating the instance //Step 2: Get status notification bar management: NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);//Get the management class for status bar notifications (responsible for issuing notifications, clearing notifications, etc.) //Step 3: Set the notification bar PendingIntent (click action events, etc. are included here): Intent push =new Intent(,);// Create a new explicit intent. The first parameter Context is interpreted to obtain the package name so as to find the location of the second parameter Class //PendingIntent can be regarded as a wrapper of an Intent. The name shows that the PendingIntent is used to deal with the intent that is about to occur, while the Intent is used to deal with the intent that occurs immediately. //This program is used to respond to click notification to open the application. The second parameter is very important. Click notification to enter the activity, use the pendingIntent class method. The second parameter of (), namely the request parameter, is actually used to distinguish different Intents. If the id is the same, the previous Intent will be overwritten. PendingIntent contentIntent = (,0,push,0); //Step 4: Configure Builder: builder .setContentTitle("My notification")//title .setContentText("Hello World!")// Details .setContentIntent(contentIntent)//Set click intention .setTicker("New message")//The first time push, the content displayed next to the corner marker .setLargeIcon((getResources(),.ic_launcher))//Set large icon .setDefaults(Notification.DEFAULT_ALL);//Open the breathing light, sound, vibration, trigger the system default behavior /*Notification.DEFAULT_VIBRATE //Add default vibration reminder VIBRATE permission is required Notification.DEFAULT_SOUND //Add default sound reminder Notification.DEFAULT_LIGHTS//Add default three-color light reminder Notification.DEFAULT_ALL//Add default all the above three reminders*/ //.setLights(, 300, 0)//Set the breathing light separately, generally three colors: red, green, blue, after testing, Xiaomi supports yellow //.setSound(url)//Set sound separately //.setVibrate(new long[] { 100, 250, 100, 250, 100, 250 })//Set vibration separately //Compare the SDK version of mobile phone with the SDK of Android 5.0 Lollipop if(.SDK_INT>= .VERSION_CODES.LOLLIPOP) { builder /*android5.0 has added a new mode Notification display level, with three types: VISIBILITY_PUBLIC will only display notifications when there is no lock screen VISIBILITY_PRIVATE Any notification will be displayed VISIBILITY_SECRET displays notifications in case of security lock and no lock screen*/ .setVisibility(Notification.VISIBILITY_PUBLIC) .setPriority(Notification.PRIORITY_DEFAULT)//Set the notification priority .setCategory(Notification.CATEGORY_MESSAGE)//Set notification category //.setColor(().getColor(.small_icon_bg_color))//Set the background color of smallIcon .setFullScreenIntent(contentIntent, true)//Change Notification into suspended Notification .setSmallIcon(.ic_launcher);//Set small icon } else{ builder .setSmallIcon(.ic_launcher);//Set small icon } //Step 5: Send a notification request: Notification notify = ();//Get a Notification object (1,notify);//Send a notification request }
But the above method cannot make notifications pop up on devices below android 5.0, so the following method is to rewrite Notification by yourself (some of the information I found online, I forgot the source, I'm sorry)
If we need to make the notification automatically display, we need to redefine the notification interface after receiving the notification and make it load and display it on the Window interface. This requires readers to understand the Window loading mechanism.
In fact, to put it simply, it is achieved through the only three methods of windowManager (loading, updating, and deleting). If a master is familiar with this knowledge, you can share it.
Ideas for custom Notification:
1. Inherit and rewrite NotificationCompat and Builder to implement similar Notification
2. Customize the notification interface
3. Customize NotificationManager and send display notifications
Without further ado, please start with the main code:
public class HeadsUp { private Context context; /** * Time of occurrence unit is second */ private long duration= 3; /** * */ private Notification notification; private Builder builder; private boolean isSticky=false; private boolean activateStatusBar=true; private Notification silencerNotification; /** * Interval time */ private int code; private CharSequence titleStr; private CharSequence msgStr; private int icon; private View customView; private boolean isExpand; private HeadsUp(Context context) { =context; } public static class Builder extends { private HeadsUp headsUp; public Builder(Context context) { super(context); headsUp=new HeadsUp(context); } public Builder setContentTitle(CharSequence title) { (title); (title); //The status bar displays content return this; } public Builder setContentText(CharSequence text) { (text); (text); return this; } public Builder setSmallIcon(int icon) { (icon); (icon); return this; } public HeadsUp buildHeadUp(){ (()); (this); return headsUp; } public Builder setSticky(boolean isSticky){ (isSticky); return this; } } public Context getContext() { return context; } public long getDuration() { return duration; } public Notification getNotification() { return notification; } protected void setNotification(Notification notification) { = notification; } public View getCustomView() { return customView; } public void setCustomView(View customView) { = customView; } public int getCode() { return code; } protected void setCode(int code) { = code; } protected Builder getBuilder() { return builder; } private void setBuilder(Builder builder) { = builder; } public boolean isSticky() { return isSticky; } public void setSticky(boolean isSticky) { = isSticky; } }
public class HeadsUpManager { private WindowManager wmOne; private FloatView floatView; private Queue<HeadsUp> msgQueue; private static HeadsUpManager manager; private Context context; private boolean isPolling = false; private Map<Integer, HeadsUp> map; private NotificationManager notificationManager=null; public static HeadsUpManager getInstant(Context c) { if (manager == null) { manager = new HeadsUpManager(c); } return manager; } private HeadsUpManager(Context context) { = context; map = new HashMap<Integer, HeadsUp>(); msgQueue = new LinkedList<HeadsUp>(); wmOne = (WindowManager) context .getSystemService(Context.WINDOW_SERVICE); notificationManager= (NotificationManager) (Context.NOTIFICATION_SERVICE); } public void notify(HeadsUp headsUp) { if ((())) { ((())); } ((), headsUp); (headsUp); if (!isPolling) { poll(); } } public synchronized void notify(int code,HeadsUp headsUp) { (code); notify(headsUp); } public synchronized void cancel(HeadsUp headsUp) { cancel(()); } private synchronized void poll() { if (!()) { HeadsUp headsUp = (); (()); // if ( .SDK_INT < 21 || () != null ){ isPolling = true; show(headsUp); ("Custom notification"); // }else { // // When the system is lollipop or above and there is no custom layout, call the system's own notification// isPolling = false; // ((),().setSmallIcon(()).build()); // ("Call system notification");// } } else { isPolling = false; } } private void show(HeadsUp headsUp) { floatView = new FloatView(context, 20); params = ; = .FLAG_NOT_TOUCH_MODAL | .FLAG_NOT_FOCUSABLE |.FLAG_FULLSCREEN | .FLAG_LAYOUT_IN_SCREEN; = .TYPE_SYSTEM_ERROR; = .MATCH_PARENT; = .WRAP_CONTENT; = -3; = | ; = ; = 10; = 1f; (floatView, params); ObjectAnimator a = (, "translationY", -700, 0); (600); (); (headsUp); if(()!=null){ ((), ()); } } public void cancel(){ if(floatView !=null && ()!=null) { (); } } protected void dismiss() { if (()!=null) { (floatView); (new Runnable() { @Override public void run() { poll(); } }, 200); } } protected void animDismiss(){ if(floatView !=null && ()!=null){ ObjectAnimator a = (, "translationY", 0, -700); (700); (); (new () { @Override public void onAnimationStart(Animator animator) { } @Override public void onAnimationEnd(Animator animator) { dismiss(); } @Override public void onAnimationCancel(Animator animator) { } @Override public void onAnimationRepeat(Animator animator) { } }); } } protected void animDismiss(HeadsUp headsUp){ if(().getCode()==()){ animDismiss(); } } public void cancel(int code) { if ((code)) { ((code)); } if(floatView!=null && ().getCode()==code){ animDismiss(); } } public void close() { cancelAll(); manager = null; } public void cancelAll() { (); if (floatView!=null && ()!=null) { animDismiss(); } } }
public class FloatView extends LinearLayout { private float rawX = 0; private float rawY=0; private float touchX = 0; private float startY = 0; public LinearLayout rootView; public int originalLeft; public int viewWidth; private float validWidth; private VelocityTracker velocityTracker; private int maxVelocity; private Distance distance; private ScrollOrientationEnum scrollOrientationEnum=; public static winParams = new (); public FloatView(final Context context, int i) { super(context); LinearLayout view = (LinearLayout) (getContext()).inflate(.notification_bg, null); maxVelocity= (context).getScaledMaximumFlingVelocity(); rootView = (LinearLayout) (); addView(view); viewWidth = ().getDisplayMetrics().widthPixels; validWidth=viewWidth/2.0f; originalLeft = 0; } public void setCustomView(View view) { (view); } @Override protected void onFinishInflate() { (); } private HeadsUp headsUp; private long cutDown; private Handler mHandle=null; private CutDownTime cutDownTime; private class CutDownTime extends Thread{ @Override public void run() { (); while (cutDown>0){ try { (1000); cutDown--; } catch (InterruptedException e) { (); } } if(cutDown==0) { (0); } } }; public HeadsUp getHeadsUp() { return headsUp; } private int pointerId; public boolean onTouchEvent(MotionEvent event) { rawX = (); rawY=(); acquireVelocityTracker(event); cutDown= (); switch (()) { case MotionEvent.ACTION_DOWN: touchX = (); startY = (); pointerId=(0); break; case MotionEvent.ACTION_MOVE: switch (scrollOrientationEnum){ case NONE: if(((rawX - touchX))>20) { scrollOrientationEnum=; }else if(startY-rawY>20){ scrollOrientationEnum=; } break; case HORIZONTAL: updatePosition((int) (rawX - touchX)); break; case VERTICAL: if(startY-rawY>20) { cancel(); } break; } break; case MotionEvent.ACTION_UP: (1000,maxVelocity); int dis= (int) (pointerId); if(scrollOrientationEnum==){ if(().contentIntent!=null){ try { ().(); cancel(); } catch ( e) { (); } } break; } int toX; if(preLeft>0){ toX= (int) (preLeft+(dis)); }else{ toX= (int) ((dis)); } if (toX <= -validWidth) { float preAlpha=(preLeft)/validWidth; preAlpha=preAlpha>=0?preAlpha:0; translationX(preLeft,-(validWidth+10),preAlpha,0); } else if (toX <= validWidth) { float preAlpha=(preLeft)/validWidth; preAlpha=preAlpha>=0?preAlpha:0; translationX(preLeft,0,preAlpha,1); }else{ float preAlpha=(preLeft)/validWidth; preAlpha=preAlpha>=0?preAlpha:0; translationX(preLeft, validWidth + 10, preAlpha, 0); } preLeft = 0; scrollOrientationEnum=; break; } return (event); } /** * * @param event Add MotionEvent to VelocityTracker * * @see #obtain() * @see #addMovement(MotionEvent) */ private void acquireVelocityTracker( MotionEvent event) { if(null == velocityTracker) { velocityTracker = (); } (event); } private int preLeft; public void updatePosition(int left) { float preAlpha=(preLeft)/validWidth; float leftAlpha=(left)/validWidth; preAlpha = preAlpha>=0 ? preAlpha : 0; leftAlpha = leftAlpha>=0 ? leftAlpha : 0; translationX(preLeft,left,preAlpha,leftAlpha); preLeft = left; } public void translationX(float fromX,float toX,float formAlpha, final float toAlpha ){ ObjectAnimator a1=(rootView,"alpha",formAlpha,toAlpha); ObjectAnimator a2 = (rootView, "translationX", fromX, toX); AnimatorSet animatorSet=new AnimatorSet(); (a1,a2); (new () { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { if(toAlpha==0){ (getContext()).dismiss(); cutDown=-1; if(velocityTracker!=null) { (); try { (); } catch (IllegalStateException e) { } } } } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }); (); } public void setNotification(final HeadsUp headsUp) { = headsUp; mHandle= new Handler(){ @Override public void handleMessage(Message msg) { (msg); (getContext()).animDismiss(headsUp); } }; cutDownTime= new CutDownTime(); if(!()){ (); } cutDown= (); if (() == null) { View defaultView = (getContext()).inflate(, rootView, false); (defaultView); ImageView imageView = (ImageView) (); TextView titleTV = (TextView) (); TextView timeTV = (TextView) (); TextView messageTV = (TextView) (); (()); (()); (()); SimpleDateFormat simpleDateFormat=new SimpleDateFormat("HH:mm"); ( (new Date())); } else { setCustomView(()); } } protected void cancel(){ (getContext()).animDismiss(); cutDown = -1; (); if(velocityTracker!=null) { try { (); (); } catch (IllegalStateException e) { } } } enum ScrollOrientationEnum { VERTICAL,HORIZONTAL,NONE } }
Specific usage:
PendingIntent pendingIntent=(,11,new Intent(,),PendingIntent.FLAG_UPDATE_CURRENT); View view=getLayoutInflater().inflate(.custom_notification, null); ().setOnClickListener(new () { @Override public void onClick(View v) { } }); HeadsUpManager manage = (getApplication()); builder = new (); ("remind") //To display notifications on the notification bar, this must be set .setSmallIcon() .setContentText("You have new news") //2.3 This parameter must be set, and it will be reported as an error .setContentIntent(pendingIntent) //.setFullScreenIntent(pendingIntent, false) HeadsUp headsUp = (); (view); (1, headsUp); }
Summarize
The above is the Notification pop-up implementation code in Android introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support for my website!