How to create custom push notifications on Android 12

文章推薦指數: 80 %
投票人數:10人

Provide custom view layouts with the setCustomContentView() and setCustomBigContentView() methods to make collapsed and expanded states ... Product Infrastructure Cross-PlatformSubscriptionManagement Implementsubscriptionswithoutbackendinfrastructure Analytics RevenueAnalytics Getthesinglesourceoftruthforyoursubscriptionrevenue AppleSearchAds Accuratelymeasuretheperformanceofyourcampaigns GrowthTools ProductPerformance Boostyourrevenuewithautomatedpushnotifications Integrations Adjust AppsFlyer Amplitude Firebase Mixpanel Webhooks Allintegrations Pricing Resources Blog ProductDemo Successstories Benchmarks Community HelpCenter Viewallblogposts Documentation QuickStart Documentation Сomprehensiveguidesanddocumentation SDK’s iOS Stripe MacOS/Catalyst Android ReactNative Flutter Unity Cordova API FullAPIReference ViewsourceonGitHub(MIT) Star Company About Careers Contactus Login Signupforfree GooglecontinuouslyimprovesAndroid,makingitsinterfacemoreuser-friendlyandvisuallyappealing.Android12isnoexceptiontothat.Googlemadeseveralchangesforthebestwayanappcanreachuserswithcustompushnotifications.Generally,Googlerecommendsappdeveloperstofollowthestandardnotificationstylesinmostcases.IthelpsyourapptohaveaconsistentlookwithindifferentAndroiddevicesanditsOSversions.Neverthelessyoucanalsocreateyourowncustomnotificationwhereyoudecidewhatexactlyisdisplayedinthecollapsedandexpandedviews.Let’strytocreateacustomnotificationandseehowtheirbehaviorchangedonAndroid12.  Createcustomlayouts Forourcustomnotification,we’regoingtopreparetwolayoutfilesforcollapsedandexpandedviewsrespectively. notification_collapsed.xml notification_expanded.xml Therearetwopointsyoumayhavenoticed:fixedlayoutheightandTextViewstyle.  AccordingtoGoogledocumentation,customnotificationsheightforcollapsedviewlayoutisnowlimitedto48dp.Thelimitationsforexpandedandheads-upviewlayoutsyoucanfindhere.  SincethebackgroundnotificationcolordiffersacrossdifferentdevicemodelsandOSversions,Googlestronglyrecommendsnotusingfixedcolorforthetextinnotifications.Instead,useTextAppearance.Compat.Notificationstylestoadapttextandbackgroundcolorwithoutblendingit(black-on-black/white-on-white). Createnotificationchannel ToshownotificationsweneedtocreateatleastoneNotificationChannelandsetparameterslikechannelID,description,nameandimportancelevel.Thebestapproachistocreateachannelonetimeoncetheappstarts.TodothiswecanextendanApplicationclass: classApp:Application(){ overridefunonCreate(){ super.onCreate() createNotificationChannel() } privatefuncreateNotificationChannel(){ //IftheAndroidVersionisgreaterthanOreo, //thencreatetheNotificationChannel if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){ valname=getString(R.string.channel_name) valdescriptionText=getString(R.string.channel_description) valchannel=NotificationChannel( CHANNEL_ID, name, NotificationManager.IMPORTANCE_DEFAULT ).apply{ description=descriptionText } //Registerthechannel valnotificationManager:NotificationManager= getSystemService(NOTIFICATION_SERVICE)asNotificationManager notificationManager.createNotificationChannel(channel) } } } Setupcustomnotification ThepartoftheAndroidsystemthatdisplaysnotificationsisaseparateprocessthatdiffersfromtheapp’sprocess.That’swhywehavetouseRemoteViewstopassalayouttothisprocess. Youshouldconsiderthefollowingsteps:  ConstructNotificationCompat.BuilderwithanotificationchannelID. Сustomizethenotificationwithaniconandcolorifyouwant. ProvidecustomviewlayoutswiththesetCustomContentView()andsetCustomBigContentView()methodstomakecollapsedandexpandedstatesconsistent.  privatefuncreateNotificationBuilder():NotificationCompat.Builder{ //Layoutsforthecustomnotification valnotificationLayout=RemoteViews(packageName,R.layout.notification_collapsed) valnotificationLayoutExpanded=RemoteViews(packageName,R.layout.notification_expanded) //Applythelayoutstothenotificationbuilder returnNotificationCompat.Builder(this,CHANNEL_ID) .setSmallIcon(R.drawable.notification_icon) .setColor(ContextCompat.getColor(this,R.color.notificationColor)) .setStyle(NotificationCompat.DecoratedCustomViewStyle()) .setCustomContentView(notificationLayout) .setCustomBigContentView(notificationLayoutExpanded) } AndthenfinallyshowourcustomnotificationwiththeNotificationManagerCompat.notify()method.FornotificationIduseanyuniquevalueyouwanttobeanIDforthenotification.  privatefunshowNotification(){ valnotification=createNotificationBuilder() //ShowthenotificationwithnotificationId. valuniqueNotificationId=0 with(NotificationManagerCompat.from(this)){ notify(uniqueNotificationId,notification.build()) } } ShowcustomnotificationonAndroid12:appearancechanges Earlier,customnotificationscouldusetheentirenotificationarea.ForappstargetingAndroid12,fullcustomizationofthenotificationisnolongerallowed.Instead,thesystemusesastandardtemplatetoshowcustomnotifications: Standardtemplateforacustomnotification  Let’strytorunourcodeanddisplaythenotificationonAndroid12andforcomparisononAndroid11.Asaresult,thelockscreenlookslikethis(bothcollapsedandexpandedstatesarebelow): Android11vs.Android12  YoucanseethatnotificationsonAndroid12weredisplayedaccordingtothetemplatesmentionedabove.Asaresult,forthecollapsednotificationtheappnamehasdisappearedandtheappiconmovedfromthetoptoleftside.Theexpandednotificationoccupiesasmallerareahorizontallyandalargerareavertically.Googlealsochangedthenotificationicon’scolorandshapeforbothstates.Inorderfortheseupdatestoworkcorrectly,Googlehighlyrecommendstestingcustomnotificationsinexpandedandcollapsedstateswithdifferentdevicesanditsorientations. HowtotriggerpersonalizednotificationswithQonversion Wetrulybelieveinthepowerofpersonalizedpushnotifications.Itisevenmoreimportantforsubscription-basedappsthatassumelong-termcommunicationwiththeuser.Personalizednotificationsshowyourcustomersthatyoucare abouttheexperiencethattheyhavewithinyourapp.Moreover,itissmart:sendingnotificationsbasedonuserbehaviorincreasesconversionsfromsuchnotifications.Youcansuggestatrialordiscountorsimplyaskwhythepersonwantstoleave.Suchnotificationscanreducethechurnrate,allowtowinlapsedcustomersback,orremindyourcustomerabouthowvaluableyourappis.  Forsuchcases,QonversionhasanAutomationtool.Let’stakeacloserlookathowyoucantriggeryournotifications.  Howtocreateandhandlepush-notification Tocreateautomatedpush-notification,youshouldsetthethreekeycomponentswithintheQonversiondashboard: Event-basedtrigger(whenuserwantstounsubscribe,cancelthetrial,etc.).Afulllistofsubscriptioneventsisinthedashboard.Action(sendpush-notification).WithintheQonversiondashboard,youcanalsobuildthedesignforyournotification. Segment(setofuserswhoshouldreceivenotification). OnceyoucompletethesesettingsontheQonversiondashboardside,youshouldconfigurenotificationsonyourappside.QonversionusesFirebaseCloudMessagingtosendpushnotificationsonAndroid.ToenableQonversiontosendpushnotificationsсallQonversion.setNotificationsToken()andpassadeviceregistrationtoken.Hereyoucanfindmoreaboutthewaystoretrievethetoken. TobeabletoworkwithFirebasenotifications,createaservicethatextendsFirebaseMessagingService.OverridetheonMessageReceived()method.EverytimeyoucatchaRemoteMessage,createandshowthenotificationtotheuser.  NotificationsarenottheonlyoptionforAutomation.Qonversionalsoallowsyoutocreatein-appscreensandpaywallsthatpushnotificationsreferto.Thescreenshouldbedisplayedafterpushnotificationisclicked.Todefinethebehaviorforusers’clicksonpushnotificationsyouhavetospecifyaninstanceofthePendingIntentobjectandpasstheRemoteMessageasextradata.ThencallthesetContentIntent()methodoftheNotificationCompat.Builder. overridefunonMessageReceived(remoteMessage:RemoteMessage){ valtitle=remoteMessage.data["title"] valbody=remoteMessage.data["body"] //CreateanexplicitintentforanActivityinyourapp valintent=Intent(this,NotificationActivity::class.java) //Ifyouneed,settheintentflagfortheactivity intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) //SavetheRemoteMessageobjectasextradata intent.putExtra(INTENT_REMOTE_MESSAGE,remoteMessage) //FlagFLAG_ONE_SHOTindicatesthatthisPendingIntentcanbeusedonlyonce valpendingIntent:PendingIntent= PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT) valnotificationBuilder=NotificationCompat.Builder(this,CHANNEL_ID) .setSmallIcon(R.drawable.notification_icon) .setContentTitle(title) .setContentText(body) .setColor(ContextCompat.getColor(this,R.color.notificationColor)) //Settheintentthatwillfirewhentheusertapsthenotification .setContentIntent(pendingIntent) with(NotificationManagerCompat.from(this)){ notify(notificationId,notificationBuilder.build()) } } IntheNotificationActivityonCreate()methodretrieveaninstanceoftheRemoteMessageandcallQonversion.handleNotification()withthemessagedata.IfthenotificationwasreceivedfromQonversion,SDKwilltrytodisplaythescreenthatwaslinkedtothenotification.  overridefunonCreate(savedInstanceState:Bundle?){ ... //Checkiftheactivitywaslaunchedfromapushnotification valremoteMessage:RemoteMessage?=intent.getParcelableExtra(INTENT_REMOTE_MESSAGE) if(remoteMessage!=null&&!Qonversion.handleNotification(remoteMessage.data)){ //Handlenotificationyourself } } Summary TheappearanceandbehavioroffullycustomnotificationsareoneofthesignificantpartsofthemassiveAndroid12redesign.AsGoogleexplains,thesechangesallownotificationstofitbetterwithAndroid12’sharmonic,personal-orientedaestheticsandworkfaster.  Whilethenotificationsbecamemoreappealing,itdoesn’tguaranteethatuserswouldwelcomethem.Delivercustom,themostrelevantinformationtoeachusertounlockthepowerofthistool.TriggernotificationsbasedonuserbehaviororsimplyusetheAutomationtool,communicatewithcustomersvianotifications,askabouttheirneedsandbringthemtheverybestvaluewiththesenotificationsthatyoucan. Automation:automatedpushnotificationsandno-codein-appmessages Today Qonversion handles$200Minannualrevenuecomingfromin-apppurchasesandsubscriptionstohelpcustomersgrowtheirmobileapps.Globalconsumer... EugeneVirnik 5February AugustProductUpdate:GoogleAdsIntegration,ROASforAppleSearchAds,andmore! Asyouknow,Augustisthemonthforvacations,rest,andquiettimeformostpeople.However,wehavenot… Kate 6September HowtopassanAppStorereview.Practicalrecommendationsforsubscriptionappowners Apple’sAppStorereviewprocessisn’ttheeasiesttopass.Infact,in2020,thecompanyrejectedalmost1million… Kate 14July Backtoblog



請為這篇文章評分?