Android Notification bar version compatible solution

Source: Internet
Author: User
Tags gettext

The Android notification bar is what we almost have to use in the app, and the custom notification bar gives us a lot of extensibility, but when we use the custom notification bar, we often encounter incompatibilities such as custom notification bar and system color, font, etc. This blog will focus on how to solve the Android custom notification bar on each Android system adaptation issues.

Overview:

As you know, there are two types of Android notifications, default notifications and custom notifications.
The default notification bar can be implemented by invoking the system interface, with the following code:

New Notificationcompat. Builder(this)/ * status bar related * /The status bar shows the icon, size recommendations are -x24 (size is too large in some systems, such as:4.x. xWill only show the middle part of the picture), must be set, otherwise report an exception. Setsmallicon(R. Mipmap. Notification_status_bar_icon). Setticker("New Notification reminders")/ * Notifications Show relevant * /                . Setlargeicon(bitmapfactory. Decoderesource(Getresources (), R. Mipmap. Chopper)). Setcontenttitle("Jabbar"). Setcontenttext("Cotton Candy"). Setwhen(System. Currenttimemillis())//. Setshowwhen(false)//whether the time is displayed. Setcontentinfo("I'm in the bottom right corner.")//. Setnumber( +)//content conflict with Setcontentinfo ()/ * other * /                . SetDefaults(Notification. DEFAULT_all). Setautocancel(true). Setdeleteintent(Getdeletependingintent ()). Setcontentintent(Getclickpendingintent ())

The effect of the presentation is as follows:

Custom notifications are a little more cumbersome, you need to define a layout file, load it with Remoteviews and set some click events, and then set it to builder, with the following code:

Remoteviews Notifactionview = new Remoteviews (mcontext. Getpackagename(), R. Layout. CL_screen_notification);Mbuilder. SetContent(Notifactionview);Notifactionview. Setonclickpendingintent(R. ID. CL_screen_notification, Pendingintent);Bitmap Pluginicon = Drawabletobitmap (plugindrawable);Logutils. D("Myl","Get Icon"+ Pluginicon);Notifactionview. Setimageviewbitmap(R. ID. CL_plugin_icon, Pluginicon);Notifactionview. Settextviewtext(R. ID. DL_plugin_msg, Plugincontent);Notification Notification = Mbuilder. Build();int id =199;Logutils. D(TAG,"Create notification");Mnotificationmanager. Notify(ID, notification);
Notification bar version compatibility issues

Why is there a version adaptation issue? There is no style adaptation in the default notification bar, because the default notification layout, color, background, and so on are all systems, and the system always displays the default notification correctly.
But custom notifications are different because we can customize any background, color. The Android notification bar has a variety of backgrounds, with different ROMs with different backgrounds, white, black, and transparent. Different Android versions of the notification bar background is not the same, once we set a specific background or color for the elements on the custom notification, it will certainly bring compatibility issues (mainly text).

How do I resolve version compatibility issues?
The following workarounds are available:
Workaround 1: Customize the background color when customizing the layout
In detail: Set a fixed background for custom notifications (360 guards do that), such as black. Then the content is naturally white or nearly white. In this way, all the phones can be displayed normally, will not appear in the Black background notification bar display good, to the white background notice bar on almost nothing to see. Advantages and disadvantages are as follows:
Pros: Simple and rude, no need to consider version compatibility issues
Cons: Overall may be different from system notification style
The effect is as follows:

Workaround 2:
The color of the title and content is obtained by reading the system's notification bar style file, which is then set to the custom notification. Read the notification bar style file itself has compatibility issues, different Android version of the style file has changed, get title and content color, you can also through the algorithm (in detail) to determine whether the color is approximate white or approximate black, You can then determine whether the background of the notification bar is approximately black or white, so that you can load different custom notification layouts based on different notification bar backgrounds. And then do a good fit.

Use the corresponding system according to different versions and Targetsdkversion textappearance
Run environment Android 4.4 and below or run environment Android 5.0, but Targetsdkversion <=19:
Title Font @android:style/textappearance.statusbar.eventcontent.title
Content Font @android:style/textappearance.statusbar.eventcontent
Android 5.0 and later:
Title Font @android:style/textappearance.material.notification.title
Content Font @android:style/textappearance.material.notification.line2

Examples are as follows:

    • Version 5.0 or less:
      Background of the notification default system background,
      Font Color @style/textappearance.statusbar.eventcontent.
      TextAppearance.StatusBar.EventContent, as the name implies, StatusBar the event content text style. In the system, it will be matched by default, such as Gray.
<?xml version= "1.0" encoding= "Utf-8"?><relativelayoutxmlns:android="Http://schemas.android.com/apk/res/android" Xmlns:tool= "http://schemas.android.com/tools"android:layout_width="match_parent "android:layout_height=" 64DP "android:gravity="center_vertical " >                    ...<linearlayout  android: Layout_width  = "match_parent"  android:layout_ Height  = "match_parent"  android:layout_ Toendof  = "@+id/notification_iv_portrait"   Android:layout_torightof  = "@+id/notification_iv_portrait"  android:gravity  =" center_vertical " android:orientation  =;         <textview  android:layout _width  = "wrap_content"  android:layout_height  = "wrap_content"  android:text  = "@string/notification_widget_title"  android:textappearanc E  = "@style/textappearance.statusbar.eventcontent"  android:textsize  =" @dimen/d14sp "/>         <TextViewandroid:id="@+id/notification_tv_calories"android:layout_width ="Wrap_content"android:layout_height="Wrap_content"android:textappearance ="@style/textappearance.statusbar.eventcontent"android:textsize="@dimen/d20sp"  Tool:text="10 steps | 20 kcal "/>                                                                            </linearlayout></relativelayout>
    • Version 5.0 and above
      New LAYOUT-V21, Surface 5.0 version is used later.
      @android: Style/textappearance.material.notification.title the notification bar header.
      @android: Style/textappearance.material.notification.line2 The contents of the notification bar.
      This makes it possible to match the system color exactly.
<?xml version= "1.0" encoding= "Utf-8"?><relativelayoutxmlns:android="Http://schemas.android.com/apk/res/android" Xmlns:tool= "http://schemas.android.com/tools"android:layout_width="match_parent "android:layout_height=" 64DP "android:gravity="center_vertical " >                        <imageview  android:id
      = "@+id/notification_iv_portrait"  android: Layout_width  = "70DP"  android:layout_height
       = "64DP"  android:paddingbottom  = "8DP"  android:paddingtop  =         "8DP"  android:scaletype  = "centerinside"  tool:src  = "@drawable/widget_normal" />     <linearlayout  android: Layout_width  = "match_parent"  android:layout_ Height  = "match_parent"  android:layout_ Torightof  = "@+id/notification_iv_portrait"   android:gravity  = "center_vertical"  android:o Rientation  =;         <textview  android:layout _width  = "wrap_content"  android:layout_height  = "wrap_content"  android:text  = "@string/notification_widget_title"  android:textappearanc E  = "@android: Style/textappearance.material.notification.title"  android:textsize  = "14sp" />         <TextViewandroid:id="@+id/notification_tv_calories"android:layout_width ="Wrap_content"android:layout_height="Wrap_content"android:textappearance ="@android: Style/textappearance.material.notification.line2"android:textsize=" 20sp "tool:text=" 10 steps | 20 kcal "/>                                                                            </linearlayout></relativelayout>

The effect is as follows:

Advantages: Overall and system notification style basically consistent
Cons: A system that does not work well with some of the magic changes, such as Meizu's system, is not compatible, and the effect is as follows:

Workaround 3:

    • Gets an instance of Contentview (remoteviews) from a notification instance of a system default style

    • Call Contentview's apply method to bind the entire layout of the default style's notification to a framelayout

    • Find the TextView instance showing title from this framelayout.

    • Call TextView's Getcurrenttextcolor () method to remove the color value of the title of the default style to assign to the corresponding custom view

      Examples are as follows:

 Public StaticSystemnotifictionbeanGetnotificationtitlecolor(Context context) {if(Context = =NULL|| Ssystemnotificationbean! =NULL) {returnSsystemnotificationbean; } Notificationcompat.builder Builder =NewNotificationcompat.builder (context); Builder.setcontenttitle (title_string);//Set a string to mark the caption controlBuilder.setcontenttext (title_content);//Set a string to mark content controlsNotification Notification = Builder.build ();//Use the Remoteviews's apply method to get the root layout of the instantiated default style layoutViewGroup RootVG = (viewgroup) notification.contentView.apply (context,NewFramelayout (context));//traverse the layout of the default style, find the control that contains the caption string, find out and record its font color valueIteratorview (RootVG,NewFilter () {@Override         Public void Filter(View view) {if(ViewinstanceofTextView) {TextView TextView = (TextView) view;if(Title_string.equals (Textview.gettext (). toString ())) {if(Ssystemnotificationbean = =NULL) {Ssystemnotificationbean =NewSystemnotifictionbean ();                } Ssystemnotificationbean.mtitlecolor = Textview.getcurrenttextcolor (); }            }        }    });//traverse the layout of the default style, find the control that contains the content string, find out and record its font color valueIteratorview (RootVG,NewFilter () {@Override         Public void Filter(View view) {if(ViewinstanceofTextView) {TextView TextView = (TextView) view;if(Title_content.equals (Textview.gettext (). toString ())) {if(Ssystemnotificationbean = =NULL) {Ssystemnotificationbean =NewSystemnotifictionbean ();                } Ssystemnotificationbean.mcontentcolor = Textview.getcurrenttextcolor (); }            }        }    });returnSsystemnotificationbean;}Private Static void Iteratorview(View view, filter filter) {if(View = =NULL|| Filter = =NULL) {return; } filter.filter (view);if(ViewinstanceofViewGroup) {ViewGroup container = (viewgroup) view; for(inti =0, j = Container.getchildcount (); I < J;        i++) {Iteratorview (Container.getchildat (i), filter); }    }}

Advantages: Accurate adaptation to all systems
Cons: In the native system operating environment Android 5.0 and Targetsdkversion are less than 19 o'clock, there will be a problem with the adaptation

In combination with the above 3 workaround, we recommend a compatible workaround:
1. Set the targetsdkversion to 21 or above
2, the adoption of solution 3 solution

Warm Tips

    • SmallIcon must be set, not set to report an exception: Java.lang.IllegalArgumentException:Invalid
      Notification (no valid small icon)

    • The size of the SmallIcon is best 24x24, otherwise it will not be displayed on some machines.

    • SmallIcon the RGB artwork when the targetsdkversion is below 21, but it turns white at 21 and above, and the solution is to make the icon a color of only white, and then use the alpha layer to draw a logo style.

    • Both Setnumber () and Setcontentinfo () are the contents of the lower right-hand corner of the notification, but there is a conflict between the two, where one is invalid


Android Notification bar version compatible solution

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.