<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Giorgos Neokleous on Medium]]></title>
        <description><![CDATA[Stories by Giorgos Neokleous on Medium]]></description>
        <link>https://medium.com/@giorgos.neokleous93?source=rss-612b184157f7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*0DkgtsNx66AblyEQKaAOsw.jpeg</url>
            <title>Stories by Giorgos Neokleous on Medium</title>
            <link>https://medium.com/@giorgos.neokleous93?source=rss-612b184157f7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 15:16:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@giorgos.neokleous93/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Let’s talk (Tts)Spans in Android Accessibility]]></title>
            <link>https://proandroiddev.com/lets-talk-tts-spans-in-android-accessibility-fc79c57754eb?source=rss-612b184157f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc79c57754eb</guid>
            <category><![CDATA[accessibility]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android-app-developers]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Giorgos Neokleous]]></dc:creator>
            <pubDate>Wed, 29 Apr 2020 20:05:23 GMT</pubDate>
            <atom:updated>2020-04-30T22:41:48.753Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*lApEAwLrVCLkZOMGawfEhg.png" /></figure><blockquote><em>Originally shared on my </em><a href="https://www.giorgosneokleous.com/2020/04/29/lets-talk-ttsspans-in-android-accessibility/"><em>personal blog post</em></a><em>.</em></blockquote><p>A great talk from the Google IO 2019 called “<a href="https://www.youtube.com/watch?v=bTodlNvQGfY"><em>Demystifying Android Accessibility Development</em></a>” mentions that when designing apps, we often miss to account for the users with accessibility needs. Users with accessibility needs won’t interact with the app directly, but instead they will use tools such as the <a href="https://play.google.com/store/apps/details?id=com.google.android.marvin.talkback&amp;hl=en_GB">Android Accessibility Suite</a> (includes Talkback and Switch Access). The user will interact with the Accessibility service and then the service will interact with the app.</p><p>Accessibility services need information on what the screen has or shows to be able to provide the correct contextual information to the user or to be able to navigate through the app. An example of that information can be provided using <a href="https://developer.android.com/guide/topics/ui/accessibility/apps#describe-ui-element">Content Descriptions</a>.</p><p>In this blog post we’ll talk about <a href="https://developer.android.com/guide/topics/text/spans">Spans</a> in Android and how to enrich <a href="https://developer.android.com/reference/android/text/Spannable">Spannable</a>s to provide a better UX to users with accessibility needs.</p><blockquote><em>Spans are powerful markup objects that you can use to style text at a character or paragraph level.</em></blockquote><p>With Spans we can change the text color of a substring or have a link-clickable part within a string, or even different size substrings. Sky is the limit 🚀</p><p>In this post, we’ll specifically talk about <a href="https://developer.android.com/reference/android/text/style/TtsSpan?hl=en">TtsSpan</a>.</p><h3><a href="https://developer.android.com/reference/android/text/style/TtsSpan?hl=en">TtsSpan</a></h3><p>A <em>TtsSpan</em> can provide metadata for a Spannable. The metadata will be supplied to <a href="https://developer.android.com/reference/android/speech/tts/TextToSpeech">Text-To-Speech</a> Engines such as <a href="https://play.google.com/store/apps/details?id=com.google.android.marvin.talkback&amp;hl=en_GB">Talkback</a>.</p><p>This span comes with several builders and each builder helps <em>building</em> metadata for a different type. The types supported by the builders are:</p><ul><li><a href="https://developer.android.com/reference/android/text/style/TtsSpan?hl=en#TYPE_CARDINAL">TYPE_CARDINAL</a></li><li><a href="https://developer.android.com/reference/android/text/style/TtsSpan?hl=en#TYPE_DATE">TYPE_DATE</a></li><li><a href="https://developer.android.com/reference/android/text/style/TtsSpan?hl=en#TYPE_DECIMAL">TYPE_DECIMAL</a></li><li><a href="https://developer.android.com/reference/android/text/style/TtsSpan?hl=en#TYPE_DIGITS">TYPE_DIGITS</a></li><li><a href="https://developer.android.com/reference/android/text/style/TtsSpan?hl=en#TYPE_ELECTRONIC">TYPE_ELECTRONIC</a></li><li><a href="https://developer.android.com/reference/android/text/style/TtsSpan?hl=en#TYPE_FRACTION">TYPE_FRACTION</a></li><li><a href="https://developer.android.com/reference/android/text/style/TtsSpan?hl=en#TYPE_MEASURE">TYPE_MEASURE</a></li><li><a href="https://developer.android.com/reference/android/text/style/TtsSpan?hl=en#TYPE_MONEY">TYPE_MONEY</a></li><li><a href="https://developer.android.com/reference/android/text/style/TtsSpan?hl=en#TYPE_ORDINAL">TYPE_ORDINAL</a></li><li><a href="https://developer.android.com/reference/android/text/style/TtsSpan?hl=en#TYPE_TELEPHONE">TYPE_TELEPHONE</a></li><li><a href="https://developer.android.com/reference/android/text/style/TtsSpan?hl=en#TYPE_TEXT">TYPE_TEXT</a></li><li><a href="https://developer.android.com/reference/android/text/style/TtsSpan?hl=en#TYPE_TIME">TYPE_TIME</a></li><li><a href="https://developer.android.com/reference/android/text/style/TtsSpan?hl=en#TYPE_VERBATIM">TYPE_VERBATIM</a></li></ul><p>To demonstrate their benefits, we’ll explore the following types:</p><ul><li><strong><em>TtsSpan.TYPE_DATE</em></strong></li><li><strong><em>TtsSpan.TYPE_MEASURE</em></strong></li><li><strong><em>TtsSpan.TYPE_TIME</em></strong></li><li><strong><em>TtsSpan.TYPE_ELECTRONIC</em></strong></li></ul><h3>Brief introduction to demo</h3><p>The demo application has a list of items. Each item is duplicated, one without TtsSpan and one with TtsSpan to highlight the differences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/0*Wj54C60DrOQiDSyE.png" /></figure><p>When an item is clicked, we pass the Spannable (with or without TtsSpan) to the TextToSpeech service to output the metadata.</p><h3>Verification</h3><p>To verify that the metadata are supplied to the <em>TextToSpeech</em> engines correctly, we could do the following:</p><ol><li>Supply the spannables to the TextToSpeech.<a href="https://developer.android.com/reference/android/speech/tts/TextToSpeech#speak(java.lang.CharSequence,%20int,%20android.os.Bundle,%20java.lang.String)">speak</a> method which will output the data</li><li>Turn on Talkback and navigate the demo using the service</li></ol><p>The demo videos use the first point + <a href="https://support.google.com/accessibility/android/answer/9350862?hl=en-GB">Live Caption</a> to verify and present you the output.</p><h3>Building the list</h3><p>The list is built using RecyclerView with TtsItem classes. Each item has a <em>title</em>, a caption and a nullable type of TtsSpan (if null then no TtsSpan is built).</p><pre>data class TtsItem(<br>    val title: String,<br>    val caption: String,<br>    private val ttsSpanType: String?<br>) {<br>  var id: Int = 0</pre><pre>  fun toSpannable(): SpannableString? { ... }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/0*q0_dwXnL_bb5BBRM.png" /></figure><p>To produce the different TtsItem, we have a data factory called DummyDataFactory .</p><pre>object DummyDataFactory {</pre><pre>    fun getListOfTtsItem(): List&lt;TtsItem&gt; = listOf(<br>        TtsItem(&quot;18/04/2020&quot;, &quot;Date without TTSSpan&quot;, null),<br>        TtsItem(&quot;18/04/2020&quot;, &quot;Date with TtsSpan.DateBuilder&quot;, TtsSpan.TYPE_DATE),</pre><pre>        TtsItem(&quot;5 meter&quot;, &quot;Measure without TTSSpan&quot;, null),<br>        TtsItem(&quot;5 meter&quot;, &quot;Measure with TTSSpan&quot;, TtsSpan.TYPE_MEASURE),</pre><pre>        TtsItem(&quot;14:00&quot;, &quot;Time without TTSSpan&quot;, null),<br>        TtsItem(&quot;14:00&quot;, &quot;Time with TTSSpan&quot;, TtsSpan.TYPE_TIME),</pre><pre>        TtsItem(&quot;admin:123456789&quot;, &quot;Password without TTSSpan&quot;, null),<br>        TtsItem(&quot;admin:123456789&quot;, &quot;Password with TTSSpan&quot;, TtsSpan.TYPE_ELECTRONIC)<br>    ).also { list -&gt;<br>        list.forEachIndexed { index, ttsItem -&gt; ttsItem.id = index }<br>    }<br>}</pre><h3>Explore toSpannable() from TtsItem</h3><p><strong><em>Disclaimer</em></strong><em>: Please note that some of the code shown below is for demonstration purposes only and mapping strings to TtsSpan most likely won’t work like that in real life projects.</em></p><p><strong>Note: </strong>Have a look at the <strong>captions </strong>to see the difference with and without TtsSpan.</p><h3>TtsSpan.TYPE_DATE</h3><pre>val calendar = Calendar.getInstance()<br>calendar.time = simpleDataFormat.parse(title)<br>   ?: throw IllegalStateException(&quot;Not expected null Date&quot;)</pre><pre>TtsSpan.DateBuilder()<br>   .setWeekday(calendar.get(Calendar.DAY_OF_WEEK))<br>   .setDay(calendar.get(Calendar.DAY_OF_MONTH))<br>   .setMonth(calendar.get(Calendar.MONTH))<br>   .setYear(calendar.get(Calendar.YEAR))</pre><p>The above code block will take a String date, parse it into a Date object which is then supplied to a Calendar. Then the Calendar object is used to extract different information that would be useful to <a href="https://developer.android.com/reference/android/text/style/TtsSpan.DateBuilder?hl=en"><em>TtsSpan.DateBuilder()</em></a>.</p><figure><img alt="Demonstration of the Date TtsSpan Builder" src="https://cdn-images-1.medium.com/max/600/1*sLQvgpa_HhVz4m5zH3anLA.gif" /></figure><ul><li><strong>Caption without TtsSpan:</strong> “<em>18 slash 04 slash 2020</em>”</li><li><strong>Caption with TtsSpan:</strong> “<em>Sunday the 18th of April 2020</em>”</li></ul><h3>TtsSpan.TYPE_MEASURE</h3><pre>val number = digitsPattern.find(title)?.value // extracts digits<br>val unit = stringPattern.find(title)?.value // extracts string<br>TtsSpan.MeasureBuilder()<br>   .setNumber(number)<br>   .setUnit(unit)</pre><p>The above code block will extract the digits from the string which will be treated as the <em>number</em> and then extract the text from the string which will be treated as the Measurement unit. All the extracted data are supplied to the <a href="https://developer.android.com/reference/android/text/style/TtsSpan.MeasureBuilder?hl=en">TtsSpan.MeasureBuilder</a>.</p><figure><img alt="Demonstration of the Measure Unit builder with TtsSpan" src="https://cdn-images-1.medium.com/max/600/1*HP5G_LOTmgjsSOZDePlGlQ.gif" /></figure><ul><li><strong>Caption without TtsSpan:</strong> “<em>5 metre</em>”</li><li><strong>Caption with TtsSpan:</strong> “<em>5 metres</em>”</li></ul><p>As you can see the metadata helps identify whether the measurement is singular or plural.</p><h3>TtsSpan.TYPE_TIME</h3><pre>val hours = title.split(&quot;:&quot;)[0]<br>val minutes = title.split(&quot;:&quot;)[1]<br>TtsSpan.TimeBuilder()<br>   .setHours(hours.toInt())<br>   .setMinutes(minutes.toInt())</pre><p>The above code block builds metadata needed for time. It simply extracts hours and minutes from string and supplies them to the <a href="https://developer.android.com/reference/android/text/style/TtsSpan.TimeBuilder?hl=en">TtsSpan.TimeBuilder()</a>.</p><figure><img alt="Demonstration of the Time Builder with TtsSpan" src="https://cdn-images-1.medium.com/max/600/1*88-o2HfyRkYu6ta_1mFkGA.gif" /></figure><ul><li><strong>Caption without TtsSpan:</strong> “<em>14 colon zero zero</em>”</li><li><strong>Caption with TtsSpan:</strong> “<em>14 hundred</em>”</li></ul><h3>TtsSpan.TYPE_ELECTRONIC</h3><p>This particular type can be used to build several “electronic” metadata. In our example we’ll build metadata for a username and password.</p><pre>val username = title.split(&quot;:&quot;)[0]<br>val password = title.split(&quot;:&quot;)[1]<br>TtsSpan.ElectronicBuilder()<br>   .setPassword(password)<br>   .setUsername(username)</pre><p>The above code block uses the <a href="https://developer.android.com/reference/android/text/style/TtsSpan.ElectronicBuilder?hl=en">TtsSpan.ElectronicBuilder</a> to build the metadata. The first part of the string is treated as the username and the second part as the password.</p><figure><img alt="Demonstration of the Electronic Builder with TtsSpan" src="https://cdn-images-1.medium.com/max/600/1*11KCwDlXIFpRXDtIODAMdw.gif" /></figure><ul><li><strong>Caption without TtsSpan:</strong> “<em>admin 123 million 456 thousands 7 hundred and 89</em>”</li><li><strong>Caption with TtsSpan:</strong> “<em>admin passoword 1 2 3 4 5 6 7 8 9</em>”</li></ul><p>The above example is my favourite as it demonstrates how powerful the Text-to-Speech engine can be with the correct metadata.</p><h3>Conclusion</h3><p>Providing rich UX is important, and we need to make sure that our apps are accessible for all users. We have seen some examples on how to add some metadata in apps so that Text to Speech services provide contextual information.</p><p><strong>➡ All the above examples can be found at the </strong><a href="https://github.com/giorgosneokleous93/text-to-speech-span-example"><strong>sample project on Github</strong></a><strong>.</strong></p><p>Feel free to ping me on <a href="https://twitter.com/neokleoys2005">Twitter</a> or check out my <a href="https://www.giorgosneokleous.com/">personal blog</a>.</p><p>Till next time! 👋</p><h3>Recommended Reading &amp; Listening</h3><ul><li><a href="https://developer.android.com/guide/topics/ui/accessibility/testing">Test your app’s accessibility</a></li><li><a href="https://developer.android.com/reference/android/text/style/TtsSpan">TtsSpan documentation</a></li><li><a href="https://developer.android.com/guide/topics/ui/accessibility">Get started with Android Accessibility</a></li><li><a href="http://androidbackstage.blogspot.com/2020/04/episode-137-accessibility.html">Episode 137 on Android Developer Backstage</a></li><li><a href="https://codelabs.developers.google.com/codelabs/basic-android-accessibility/">Codelab — Basic Android Accessibility</a></li><li><a href="https://play.google.com/store/apps/details?id=com.google.android.apps.accessibility.auditor&amp;hl=en_GB">Accessibility Scanner</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc79c57754eb" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/lets-talk-tts-spans-in-android-accessibility-fc79c57754eb">Let’s talk (Tts)Spans in Android Accessibility</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Full-Screen Intent Notifications — Android]]></title>
            <link>https://medium.com/android-news/full-screen-intent-notifications-android-85ea2f5b5dc1?source=rss-612b184157f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/85ea2f5b5dc1</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Giorgos Neokleous]]></dc:creator>
            <pubDate>Wed, 18 Mar 2020 15:49:25 GMT</pubDate>
            <atom:updated>2021-07-29T15:37:21.938Z</atom:updated>
            <content:encoded><![CDATA[<h3>Full-Screen Intent Notifications — Android</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*hCae4PKu8dNfRLhKTq09OA.png" /></figure><blockquote>Originally shared on my <a href="https://www.giorgosneokleous.com/2020/03/15/full-screen-intent-notifications-android/">personal blog post</a>.</blockquote><h3>What are Full-Screen Intents?</h3><p>Full-Screen Intents are <a href="https://developer.android.com/reference/android/content/Intent">Intents</a> that can launch in full-screen and can be used for showing a full-screen notification.</p><p>Well, I guess that needs a bit more explanation so keep on reading.</p><blockquote><a href="https://developer.android.com/training/notify-user/build-notification#urgent-message"><em>Your app might need to display an urgent, time-sensitive message, such as an incoming phone call or a ringing alarm. In these situations, you can associate a full-screen intent with your notification.</em></a></blockquote><h3>Why should Full-Screen Intents be used?</h3><p>A restriction was added with Android Q where an app couldn’t start an activity if <a href="https://developer.android.com/guide/components/activities/background-starts#exceptions">not meeting the criteria</a>. Although this breaks a lot of things, it doesn’t affect full-screen intents. (see <a href="https://developer.android.com/guide/components/activities/background-starts#display-notification">Restrictions on starting activities from the background</a>)</p><p><a href="http://stackoverflow.com/users/1676363/ianhanniballake(opens%20in%20a%20new%20tab)">Ian Lake</a> from the Android Toolkit team said the following on a <a href="https://stackoverflow.com/questions/57964961/how-to-set-an-alarm-on-android-q">Stackoverflow question</a>:</p><blockquote><em>Full screen intent has been the recommended best practice for alarms since it was introduced in API 9 and was even more important with the introduction of heads up notifications (where your alarm shows as a heads up notification if the user is actively using their device)</em></blockquote><h3>When should Full-Screen Intents be used?</h3><p>Full-screen intents were added to the framework since forever and it is the recommended way of launching an <em>activity</em> while the system is locked or busy.</p><p><strong>Examples:</strong></p><ul><li><strong>Incoming call: </strong>When there is an incoming call, the system launches a full-screen activity if the phone is locked or shows a normal notification with high priority.</li><li><strong>Alarm Clock:</strong> An alarm clock can use full-screen intent to either show an activity or a notification with high priority.</li></ul><p>Notifications with a Full-Screen Intent are less intrusive to the user and there is less chance to break in the future with any API changes.</p><h3>Show me the code</h3><p><strong>Note: </strong>On Android 10 and above to use a full-screen intent, a special <a href="https://developer.android.com/about/versions/10/behavior-changes-10#full-screen-intents">permission</a> needs to be declared in the Manifest.</p><p>We are going to explore three different scenarios:</p><ol><li>Notify while the app is on the foreground</li><li>Schedule Full-Screen Intent Notification</li><li>Full-Screen Intent on Lock Screen with a Keyguard</li></ol><p><em>Disclaimer: </em>Some logic will be omitted for demonstration purposes</p><h3>1. Notify while the app on the foreground.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I2BVnW9XjezpAOzgj-lj6g.gif" /><figcaption><em>Demonstration of the first scenario, showing full-screen intent notification while on the foreground</em></figcaption></figure><p>In order to show a full-screen intent, we need to first build the notification and <strong>set the full-screen intent to the notification</strong>.</p><p>To build the intent we need a pending intent, which can be achieved using <a href="https://developer.android.com/reference/android/app/PendingIntent">PendingIntent</a>.</p><pre>val builder = NotificationCompat.Builder(this, channelId)<br>        .setSmallIcon(android.R.drawable.arrow_up_float)<br>        .setContentTitle(title)<br>        .setContentText(description)<br>        .setPriority(NotificationCompat.PRIORITY_HIGH)<br><br>// request code and flags not added for demo purposes<br>val pendingIntent = PendingIntent.getActivity(this, 0, intent, 0)<br><br>builder.setFullScreenIntent(pendingIntent) // THIS HERE is the full-screen intent</pre><p>Don’t forget to add in your AndroidManifest.xml’s Activity the following as well:</p><pre>&lt;activity android:name=&quot;.LockScreenActivity&quot;<br>    android:showOnLockScreen=&quot;true&quot;/&gt;</pre><h3>2. Schedule Full-Screen Intent Notification</h3><p>Building the notification is identical to the previous example. The main difference is that the notification is not built by an Activity but by a <a href="https://developer.android.com/reference/android/content/BroadcastReceiver">BroadcastReceiver</a> to enable scheduling in the future using <a href="https://developer.android.com/reference/android/app/AlarmManager">AlarmManager</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QCK8GmDtdZK7mfGXQy47VQ.gif" /><figcaption>Schedule Full-Screen Intent Notification demo</figcaption></figure><p><strong>Scheduling</strong></p><p>AlarmManager needs a PendingIntent with a BroadcastReceiver.</p><pre>fun Context.scheduleNotification(isLockScreen: Boolean) {<br>    val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager<br>    val timeInMillis = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(SCHEDULE_TIME)<br><br>    with(alarmManager) {<br>        setExact(AlarmManager.RTC_WAKEUP, timeInMillis, getReceiver(isLockScreen))<br>    }<br>}<br><br>private fun Context.getReceiver(isLockScreen: Boolean): PendingIntent {<br>    // for demo purposes no request code and no flags<br>    return PendingIntent.getBroadcast(<br>        this,<br>        0,<br>        NotificationReceiver.build(this, isLockScreen),<br>        0<br>    )<br>}</pre><p><strong>Receiver</strong></p><p>The Receiver below is called in two cases:</p><ul><li>When the system is locked</li><li>When the system is not locked</li></ul><pre>class NotificationReceiver : BroadcastReceiver() {<br><br>    override fun onReceive(context: Context, intent: Intent) {<br>        if(intent.getBooleanExtra(LOCK_SCREEN_KEY, true)) {<br>            context.showNotificationWithFullScreenIntent(true)<br>        } else {<br>            context.showNotificationWithFullScreenIntent()<br>        }<br>    }<br><br>    companion object {<br>        fun build(context: Context, isLockScreen: Boolean): Intent {<br>            return Intent(context, NotificationReceiver::class.java).also {<br>                it.putExtra(LOCK_SCREEN_KEY, isLockScreen)<br>            }<br>        }<br>    }<br>}<br><br>private const val LOCK_SCREEN_KEY = &quot;lockScreenKey&quot;</pre><h3>3. Full-Screen Intent on Lock Screen with a Keyguard</h3><p><a href="https://developer.android.com/reference/android/app/KeyguardManager">Keyguard</a> could prevent the notification from being displayed.</p><p>Let’s see an example to visualize it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a4hlzEdAMtYaQ7qi-9hBuA.gif" /><figcaption>Not requesting keyguard demonstration.</figcaption></figure><p>The framework provides some flags to dismiss keyguard.</p><ul><li>Activity#<a href="https://developer.android.com/reference/android/app/Activity#setShowWhenLocked(boolean)"><em>setShowWhenLocked</em></a><em>(true)</em> method</li></ul><p><strong>Note:</strong> To be able to turn on the screen we need to also request it using the:</p><p>– Activity#<a href="https://developer.android.com/reference/android/app/Activity#setTurnScreenOn(boolean)">setTurnScreenOn</a>(true) method</p><p>Time for an extension function that sets both flags with backward compatibility 🚀</p><pre>fun Activity.turnScreenOnAndKeyguardOff() {<br>    if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.O_MR1) {<br>        setShowWhenLocked(true)<br>        setTurnScreenOn(true)<br>    } else {<br>        window.addFlags(<br>            WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON<br>                    or WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON<br>        )<br>    }<br><br>    with(getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager) {<br>        if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.O) {<br>            requestDismissKeyguard(this@turnScreenOnAndKeyguardOff, null)<br>        }<br>    }<br>}</pre><p><strong>Demo 🎥</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3KwKo6jId8u65GM7KLVv0w.gif" /><figcaption>Demonstration with Keyguard On</figcaption></figure><h3>Conclusion</h3><p>Using Full-Screen Intents is easy and it’s the recommended way of launching an activity, especially for alarms.</p><p>The API should be used with care, and developers shouldn’t abuse it as it’s quite intrusive especially when the screen wakes up.</p><p>You can find a sample project <a href="https://github.com/giorgosneokleous93/fullscreenintentexample/">here</a>.</p><p>Feel free to ping me on <a href="https://twitter.com/neokleoys2005">twitter</a>.</p><p>Till next time! 👋</p><h3>Recommended Reading</h3><ul><li><a href="https://developer.android.com/guide/components/activities/background-starts#display-notification">https://developer.android.com/guide/components/activities/background-starts#display-notification</a></li><li><a href="https://developer.android.com/training/notify-user/time-sensitive">https://developer.android.com/training/notify-user/time-sensitive</a></li><li><a href="https://developer.android.com/about/versions/10/behavior-changes-10#full-screen-intents">https://developer.android.com/about/versions/10/behavior-changes-10#full-screen-intents</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85ea2f5b5dc1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/full-screen-intent-notifications-android-85ea2f5b5dc1">Full-Screen Intent Notifications — Android</a> was originally published in <a href="https://medium.com/android-news">AndroidPub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Documenting your XML attributes — Custom View]]></title>
            <link>https://medium.com/@giorgos.neokleous93/documenting-your-xml-attributes-custom-view-cc36b02dbe5e?source=rss-612b184157f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc36b02dbe5e</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[custom-view-android]]></category>
            <dc:creator><![CDATA[Giorgos Neokleous]]></dc:creator>
            <pubDate>Sun, 19 Jan 2020 22:23:41 GMT</pubDate>
            <atom:updated>2020-01-19T22:23:41.350Z</atom:updated>
            <content:encoded><![CDATA[<h3>Documenting your XML attributes — Custom View</h3><blockquote><em>Originally shared on my </em><a href="https://www.giorgosneokleous.com/2020/01/19/documenting-your-xml-attributes-custom-view/"><em>personal blog post</em></a><em>.</em></blockquote><p>Today, I will walk you through on how to create a very basic Custom View, and we will do something that many libraries and developers often forget to do:</p><p><strong>Documenting XML Attributes, which offer customizations on custom views.</strong></p><h3>Why</h3><p>Documentation sometimes is redundant if the method, class or property is self-describing. However, imagine any Android API without it. Android development will instantly turn into living hell. To figure out what’s going on we will have to step into source code and trial-and-error different options.</p><h3>Custom View</h3><p>I will be using the following custom view, which draws a Circle. The customizations available will be: <em>fill color</em> and <em>radius</em>.</p><figure><img alt="final result of the custom view — a circle" src="https://cdn-images-1.medium.com/max/1024/1*V2PZ_upGaJYW5NnszmvKcg.png" /><figcaption>The final result of the custom view</figcaption></figure><h3>Implementation</h3><h4>Create custom attributes</h4><p>Creating custom attributes allows specifying properties on the XML directly instead of programmatically. These attributes will be fetched at the construction of the View.</p><p>To declare the attributes:</p><ul><li>Create a Values resource file — usually called <em>attrs.xml</em></li><li>Open a <strong><em>declare-styleabl</em>e</strong> tag</li><li>Include the attributes within the view</li></ul><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;resources&gt;<br>    &lt;declare-styleable name=&quot;CircleCustomView&quot;&gt;<br>        &lt;attr name=&quot;fillColor&quot; format=&quot;color&quot; /&gt;<br>        &lt;attr name=&quot;radius&quot; format=&quot;dimension&quot; /&gt;<br>    &lt;/declare-styleable&gt;<br>&lt;/resources&gt;</pre><p>The “<em>name</em>” should be your custom view’s class name to bind the enclosed attributes to it. In our case that would be “<strong><em>CircleCustomView</em></strong>”.</p><p>Now the enclosed attributes would be:</p><ol><li>Fill Color of the format “color” resource</li><li>The radius of the format dimension</li></ol><h3>Fetch custom attributes</h3><p>In the initialization of our custom view, we need to fetch and store those attributes in order to use them when drawing on the <a href="https://developer.android.com/reference/android/graphics/Canvas">Canvas</a>.</p><pre>init {<br>  context.theme.obtainStyledAttributes(<br>            attrs,<br>            R.styleable.CircleCustomView,<br>            0,<br>            0<br>        ).apply {<br>            circleFillColor = getColor(<br>                R.styleable.CircleCustomView_fillColor,<br>                context.getColor(R.color.colorAccent)<br>            )<br>            circleRadius = getDimension(R.styleable.CircleCustomView_radius, 100f)<br>        }<br>}</pre><h3>Draw the circle</h3><pre>override fun onDraw(canvas: Canvas?) {<br>   super.onDraw(canvas)</pre><pre>   paint.color = circleFillColor</pre><pre>   canvas?.drawCircle(canvas.width / 2f, canvas.height / 2F, circleRadius, paint)<br>}</pre><h3>Full Class</h3><pre>class CircleCustomView <a href="http://twitter.com/JvmOverloads">@JvmOverloads</a> constructor(<br>    context: Context,<br>    attrs: AttributeSet? = null,<br>    defStyleAttr: Int = 0<br>) : View(context, attrs, defStyleAttr) {</pre><pre>    private var circleFillColor: Int<br>    private var circleRadius: Float</pre><pre>    private val paint = Paint()</pre><pre>    init {<br>        context.theme.obtainStyledAttributes(<br>            attrs,<br>            R.styleable.CircleCustomView,<br>            0,<br>            0<br>        ).apply {<br>            circleFillColor = getColor(<br>                R.styleable.CircleCustomView_fillColor,<br>                context.getColor(R.color.colorAccent)<br>            )<br>            circleRadius = getDimension(R.styleable.CircleCustomView_radius, 100f)<br>        }<br>    }</pre><pre>    override fun onDraw(canvas: Canvas?) {<br>       super.onDraw(canvas)</pre><pre>       paint.color = circleFillColor</pre><pre>       canvas?.drawCircle(canvas.width / 2f, canvas.height / 2F, circleRadius, paint)<br>    }</pre><pre>    fun setFillColor(<a href="http://twitter.com/ColorRes">@ColorRes</a> colorRes: Int) {<br>        this.circleFillColor = context.getColor(colorRes)<br>    }</pre><pre>    fun setRadius(<a href="http://twitter.com/DimenRes">@DimenRes</a> radius: Int) {<br>        this.circleRadius = context.resources.getDimension(radius)<br>    }<br>}</pre><h3>Document XML Attributes</h3><p>Without documentation, if I try to check for it over the fillColor, I am getting the following.</p><figure><img alt="No documenation found screenshot" src="https://cdn-images-1.medium.com/max/1024/1*inHQkZCSPDgql_E_FImGHw.png" /><figcaption>No documentation found screenshot</figcaption></figure><p>Using normal XML comments above the attributes will result in attaching the comments as documentation for them.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;resources&gt;<br>    &lt;declare-styleable name=&quot;CircleCustomView&quot;&gt;<br>        &lt;!-- Sets the fill color of the circle --&gt;<br>        &lt;attr name=&quot;fillColor&quot; format=&quot;color&quot; /&gt;<br>        &lt;!-- Sets the radius of the circle --&gt;<br>        &lt;attr name=&quot;radius&quot; format=&quot;dimension&quot; /&gt;<br>    &lt;/declare-styleable&gt;<br>&lt;/resources&gt;</pre><p>Now if I ask for documentation on the attribute, I am getting proper documentation as seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*obO0KafoQDl0sqRKWhbBkg.png" /><figcaption>Radius documentation screenshot</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*zbff-4dTcWS9rJMKPVuUTg.png" /><figcaption>Fill color documentation screenshot</figcaption></figure><h3>Conclusion</h3><p>Documenting XML attributes for your custom views is as simple as attaching an XML comment using the &lt;!-- comment --&gt;.</p><p>In my opinion, documentation is not always needed. If something is self-describing then you can afford to skip it. On the other hand, if something will be used by many others or does something that is not specified or described from the class, property or method name then it needs documentation.</p><p>Feel free to ping me on <a href="https://twitter.com/neokleoys2005">twitter</a>.</p><p>Till next time! 👋</p><p>Get started with custom views with the following links:</p><ol><li><a href="https://developer.android.com/training/custom-views/create-view">https://developer.android.com/training/custom-views/create-view</a></li><li><a href="https://developer.android.com/training/custom-views/custom-drawing">https://developer.android.com/training/custom-views/custom-drawing</a></li><li><a href="https://developer.android.com/guide/topics/ui/custom-components">https://developer.android.com/guide/topics/ui/custom-components</a></li><li>Codelab <a href="https://codelabs.developers.google.com/codelabs/advanced-android-training-customize-view/index.html?index=..%2F..advanced-android-training#0">Part A</a> &amp; <a href="https://codelabs.developers.google.com/codelabs/advanced-android-training-custom-view-from-scratch/index.html?index=..%2F..advanced-android-training#0">Part B</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc36b02dbe5e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Name your .apk & .aab files]]></title>
            <link>https://medium.com/@giorgos.neokleous93/name-your-apk-aab-files-3cf3d123a48c?source=rss-612b184157f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/3cf3d123a48c</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Giorgos Neokleous]]></dc:creator>
            <pubDate>Sun, 01 Dec 2019 17:15:52 GMT</pubDate>
            <atom:updated>2019-12-01T17:15:52.654Z</atom:updated>
            <content:encoded><![CDATA[<h3>Name your .apk &amp; .aab files</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PDRGEGbeNL7SpVUqw7r9JA.png" /></figure><blockquote>Originally shared on my <a href="https://www.giorgosneokleous.com/2019/12/01/name-your-apk-aab-files/">personal blog post</a>.</blockquote><p>This post will explore how to rename your artifacts, to convey meaning.</p><h3>Why?</h3><p><strong>Use cases:</strong></p><ol><li>When your application has multiple “flavours”, you need the outputs identifiable.</li><li>When you produce multiple versions at the same time, you need to tell which artifact is which.</li></ol><p>To check your current artifact’s name simply run assembleDebug Gradle task. If you haven&#39;t modified it yet, your output will be <strong>app-debug.apk</strong></p><p>What would be better to have is something that is identifiable and meaningful like the template below:</p><p><strong>${applicationId}-v${versionName}(${versionCode})-${buildType}.apk</strong></p><p>This template will produce something like:</p><p><strong>com.example.sampleproject-v1.0.0(101)-release.apk</strong></p><p>By using this template you know what the APK is about.</p><h3>Option 1</h3><p>I personally do not recommend the following solution but you can find it in many StackOverflow answers.</p><p><em>When I tried it with app bundles, it was not working.</em></p><pre>applicationVariants.all { variant -&gt;<br>    variant.outputs.all {<br>        outputFileName = &quot;${applicationId}-v${versionName}(${versionCode})-${buildType}.apk&quot;<br>    }<br>}</pre><h4>The DSL Version</h4><pre>applicationVariants.all {<br>        outputs.forEach { output -&gt;<br>            if (output is com.android.build.gradle.internal.api.BaseVariantOutputImpl) {<br>                output.outputFileName =<br>                    &quot;${applicationId}-v${versionName}(${this.versionCode})-${name}.${output.outputFile.extension}&quot;<br>            }<br>        }<br>    }</pre><p>The above works fine for APKs but not for app bundles.</p><p><strong>Output</strong></p><p><strong>com.example.sampleproject-v1.0.0(101)_release.apk</strong></p><h3>Option 2</h3><p>The following implementation is easy, simple and elegant.. <em>but</em> as the property “<em>archivesBaseName</em>” implies, it will only set up the base name and not the full file’s name.</p><pre>android {<br>  ...<br>  defaultConfig {<br>    ...<br>    archivesBaseName = &quot;${applicationId}-v${versionName}(${versionCode})&quot;<br>  }<br>}</pre><h4>THE DSL VErsion</h4><pre>android {<br>  ...<br>  defaultConfig {<br>    ...<br>    setProperty(&quot;archivesBaseName&quot;, &quot;${applicationId}-v${versionName}(${versionCode})&quot;)<br>  }<br>}</pre><p><strong>Output</strong></p><p><strong>com.example.sampleproject-v1.0.0(101)-release.apk</strong></p><p>The “<em>-release</em>” part is added according to the build type automatically by the build system.</p><h3>Performance Comparison</h3><p>In this section, Option 1 will be compared against Option 2.</p><p>The following metrics were taken on a 7-module project by running the following tasks:</p><ul><li>clean</li><li>assembleDebug</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*Dfq7W4A4krQDtVi5P5SAzQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*WWf9NFORSPGaBlqmJgPo1A.png" /></figure><p>As you can see from the graphs and metrics above, the two options have identical performance, with no clear winner. To be honest, I was expecting <strong>Option 2</strong> to be faster 🤷.</p><h3>Conclusion</h3><p>Personally I prefer <strong>Option 2</strong>, it’s simple and it did not break when App Bundles were introduced.</p><p><strong>Remember:</strong> When naming your artifacts make sure that you are giving them meaningful names.</p><p>If you have anything to add or want to share your experiences with me feel free to ping me on <a href="https://twitter.com/neokleoys2005">twitter</a>.</p><p>If you enjoyed this blog post then hit the 👏 below!</p><p>Till next time! 👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3cf3d123a48c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mock Responses with OkHttp & Retrofit]]></title>
            <link>https://medium.com/@giorgos.neokleous93/mock-responses-with-okhttp-retrofit-f77bf81f9b84?source=rss-612b184157f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/f77bf81f9b84</guid>
            <category><![CDATA[junit]]></category>
            <category><![CDATA[retrofit]]></category>
            <category><![CDATA[okhttp]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Giorgos Neokleous]]></dc:creator>
            <pubDate>Mon, 25 Nov 2019 18:23:35 GMT</pubDate>
            <atom:updated>2019-11-26T15:15:36.683Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*jPqK-EIq26ZMzICG9idmKw.png" /></figure><blockquote>This blog post does not explore Retrofit nor OkHttp and all their glory. Instead, we are looking into OkHttp’s testing API and how to use that to provide confidence into our codebase.</blockquote><p>Testing is often daunting but crucial for software development. I am going to keep this post short and sweet. We will explore together the <a href="https://square.github.io/okhttp/"><em>OkHttp</em></a>’s “<em>MockWebServer</em>” and how to integrate with Retrofit.</p><p><strong>Target Audience: </strong>Retrofit Users</p><h3>The Why?</h3><p>We need our tests <strong>non-flaky</strong>, and <strong>reliable</strong>! What that means is:</p><ol><li>Our tests should run in isolation</li><li>Our tests should not be affected by external factors</li><li>Our tests conditions are controllable</li></ol><blockquote><a href="https://hackernoon.com/flaky-tests-a-war-that-never-ends-9aa32fdef359">A flaky test is a test which could fail or pass for the same configuration.</a></blockquote><p>All the above points are needed so that we can control and test different scenarios. For example, if the tests are making a real network call, then they could fail when the network connectivity is lost.</p><h3>Setup 🔨</h3><p>You need to add the following dependency in <em>build.gradle</em></p><pre>testImplementation(&quot;com.squareup.okhttp3:mockwebserver:$Version&quot;)</pre><p>Explore more about <em>MockWebServer</em> dependency at the <a href="https://github.com/square/okhttp/tree/master/mockwebserver">Github Repository</a>.</p><h3>Explore 🛫</h3><p>The <em>MockWebServer</em> is really powerful and provides us with some incredible APIs to ease the pain when testing such features.</p><p><strong>Some of the highlights are:</strong></p><ul><li>Mocking Responses</li><li>Throttling for bodies</li><li>Throttling for headers</li><li><em>Many many more</em></li></ul><blockquote><em>This library makes it easy to test that your app Does The Right Thing when it makes HTTP and HTTPS calls. It lets you specify which responses to return and then verify that requests were made as expected.</em></blockquote><blockquote><a href="https://github.com/square/okhttp/tree/master/mockwebserver"><em>Github Repository for MockWebServer</em></a></blockquote><h3>Create the mock web server 🏗</h3><pre>val mockWebServer = MockWebServer()</pre><p>When you are ready to start your tests, make sure you “<em>Start</em>” the mock server like:</p><pre>mockWebServer.start()</pre><h3>Mocking a response</h3><pre>MockResponse()<br>   .setResponseCode(HttpURLConnection.HTTP_OK)<br>   .setBody(&quot;&quot;{\&quot;status\&quot;:\&quot;error\&quot;,\&quot;code\&quot;:\&quot;responseCode\&quot;}&quot;<br>&quot;)</pre><p>To instruct the server to return the mocked response, you need to <a href="https://square.github.io/okhttp/4.x/mockwebserver/okhttp3.mockwebserver/-mock-web-server/enqueue/">enqueue</a> the mock response such as:</p><pre>mockWebServer.enqueue(mockResponse)</pre><p>For further studying, head to MockWebServer’s Javadoc <a href="https://square.github.io/okhttp/4.x/mockwebserver/okhttp3.mockwebserver/-mock-web-server/">here</a>.</p><h3>Basic setup for unit tests</h3><p>The following setup will make sure that you start your mock server and shut it down between tests.</p><pre>class YourTest {<br> lateinit var mockWebServer: MockWebServer</pre><pre>    @Before<br>    fun setUp() {<br>        mockWebServer = MockWebServer()<br>        mockWebServer.start()<br>    }</pre><pre>    @After<br>    fun tearDown() {<br>        mockWebServer.shutdown()<br>    }<br>}</pre><h3>MockWebServer with Retrofit</h3><p>Now, let’s explore, how to use Retrofit with all the above.</p><p>Basic setup for Retrofit looks like:</p><pre>Retrofit retrofit = new Retrofit.Builder()<br>    .baseUrl(&quot;https://ourapi.com/&quot;)<br>    .build()</pre><p>We are used to passing a <em>String</em> to the method .baseUrl(string). However, there is an overload which takes an <a href="https://square.github.io/okhttp/4.x/okhttp/okhttp3/-http-url/">HttpUrl</a> object. The HttpUrl object is what the mock web server exposes and we could use to integrate it into tests.</p><p>If we actually check the <a href="https://github.com/square/retrofit/blob/master/retrofit/src/main/java/retrofit2/Retrofit.java#L490">source code</a> the .baseUrl(string) internally looks like:</p><pre>public Builder baseUrl(String baseUrl) {<br>    checkNotNull(baseUrl, &quot;baseUrl == null&quot;);<br>    return baseUrl(HttpUrl.get(baseUrl));<br>}</pre><p>What we then pass for the base URL:</p><ul><li><strong>Production</strong></li></ul><pre>HttpUrl.get(&quot;https://ourapi.com/&quot;)</pre><ul><li><strong>Tests</strong></li></ul><pre>mockWebServer.url(https://medium.com/&quot;/&quot;)</pre><h3>The Transformation</h3><p>First, pass the above to your Retrofit builder and then start receiving the mock responses and leveraging the test environment for your benefit.</p><p>As you can see from the examples below, we should now inject the HttpUrl to allow the <em>MockWebServer</em> to do its magic.</p><h4>Before</h4><pre>class OurApi(<br>    private val baseUrl: String = &quot;https://ourapi.com/&quot;<br>) {<br>    private val retrofit = Retrofit.Builder()<br>        .baseUrl(baseUrl)<br>        .addConverterFactory(MoshiConverterFactory.create())<br>        .build()<br>}</pre><h4>After</h4><pre>class OurApi(<br>    private val baseUrl: HttpUrl = HttpUrl.get(&quot;https://ourapi.com/&quot;)<br>) {<br>    private val retrofit = Retrofit.Builder()<br>        .baseUrl(baseUrl)<br>        .addConverterFactory(MoshiConverterFactory.create())<br>        .build()<br>}</pre><p><strong>That’s it really, thanks for reading the post!</strong></p><p>Happy coding and testing!</p><p>Feel free to ping me on <a href="https://twitter.com/neokleoys2005">twitter</a> or check out my <a href="https://www.giorgosneokleous.com/">personal blog</a>.</p><p>Till next time! 👋</p><p>(👇 check out the bonus section below 👇)</p><blockquote><a href="https://www.giorgosneokleous.com/2019/11/25/mock-responses-with-okhttp-retrofit/">Original Post can be found at my Personal Blog</a></blockquote><h3>Bonus 🎉</h3><p>You can place different responses in your Test Resources which you can instruct the MockWebServer instance to return.</p><p>Steps:</p><ol><li>Create a folder under the following path:~/${MODULE}/src/test/resources</li><li>Place there the responses as JSON files such as <em>error.json</em></li><li>From your unit test read the file as a String and pass to the mock web server instance</li></ol><h4>Read JSON files as Strings</h4><pre>object FileUtils {<br>    fun readTestResourceFile(fileName: String): String {<br>        val fileInputStream = javaClass.classLoader?.getResourceAsStream(fileName)</pre><pre>        return fileInputStream?.bufferedReader()?.readText() ?: &quot;&quot;<br>    }<br>}</pre><pre>// pass to mock web server<br> val response = MockResponse()<br>response.setResponseCode(HttpURLConnection.HTTP_OK)<br>response.setBody(FileUtils.readTestResourceFile(&quot;error.json&quot;))</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f77bf81f9b84" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>