<?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 . on Medium]]></title>
        <description><![CDATA[Stories by . on Medium]]></description>
        <link>https://medium.com/@gadi.krn?source=rss-426b18be75af------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*hGg7_w5OsuGjo-PR2z-bRQ.jpeg</url>
            <title>Stories by . on Medium</title>
            <link>https://medium.com/@gadi.krn?source=rss-426b18be75af------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 13:50:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gadi.krn/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[Happy new year!]]></title>
            <link>https://medium.com/@gadi.krn/happy-new-year-79ed79b0396d?source=rss-426b18be75af------2</link>
            <guid isPermaLink="false">https://medium.com/p/79ed79b0396d</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[2019]]></category>
            <category><![CDATA[app-development]]></category>
            <dc:creator><![CDATA[.]]></dc:creator>
            <pubDate>Tue, 01 Jan 2019 20:48:07 GMT</pubDate>
            <atom:updated>2019-01-01T20:48:07.647Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hGg7_w5OsuGjo-PR2z-bRQ.jpeg" /></figure><p>Happy new year!</p><p>Hello dear followers, I would like to wish you all a year full of happiness, health, joy and success!</p><p>This year I will continue to write more about Android and I would like to know which topics you find the most interesting? What would you like to write about this year?</p><p>For an amazing year to come,</p><p>Gadi</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79ed79b0396d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Espresso — More than just a coffee ;)]]></title>
            <link>https://medium.com/@gadi.krn/android-espresso-more-than-just-a-coffee-46d9592c3786?source=rss-426b18be75af------2</link>
            <guid isPermaLink="false">https://medium.com/p/46d9592c3786</guid>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[espresso]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[.]]></dc:creator>
            <pubDate>Tue, 11 Sep 2018 21:20:30 GMT</pubDate>
            <atom:updated>2018-09-11T21:21:09.342Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4FzJWow3qJOV_O-3iKgBOw.jpeg" /><figcaption>Coffee anyone? ;)</figcaption></figure><blockquote>Apps UI Tests in a nutshell</blockquote><p><strong>1. Intro to UI testings<br></strong>Part of the process of building an app is to check that the features you’ve implemented work as expected. For example: clicking a button on the screen and verifying the expected image appears.</p><p>One of the most apparent types of testing is User Interface Testing, or for short UI Testing. It means testing the components on the screen that the user can interact with.</p><p>Android Studio provides a powerful tool called Espresso to help us as developers efficiently UI test the apps we make. Espresso is a testing framework that includes a set of APIs that simulates and schedules user interactions to help us as developers test an app’s user interface automatically.</p><p>Most of the app we use have a lot of user interface components. We need to make sure that all the touch points in our app make a good user experience being seamless and functions as anticipated.</p><p>Espresso allows developers to automate the testing process so that it can be tested at scale and much more efficiently.</p><p>Steps to manually UI test:</p><blockquote>(1) Find the view<br>(2) Perform action on the view<br>(3) Check if the view does what you expected</blockquote><p>These are the building blocks for writing tests in Espresso.</p><p>Steps to UI test in code:</p><blockquote>(1) onView(ViewMatcher*) =&gt; onView(withId(R.id.send_button))<br>(2) .perform(ViewAction) =&gt; .perform(click())<br>(3) .perform(ViewAssertion**) =&gt; onView(withId(R.id.sent_text).check(isDisplayed())</blockquote><p>*ViewMatcher — A class that helps us specify the view we’re interested in the current view hierarchy. The matches come from the Hamcrest Matcher library, which is a compilation of possible ways to help us identify a view matches what we’re expecting using human-readable language.</p><p>** Assertion — A check to see if what we expected matches what actually happened. ViewAssertion is a class with methods that help us perform assertions (or checks) on views.</p><p>Altogether it’s the single compilation of statement we will use to execute the UI test in Espresso. The process is meant to mimic the human testing of the UI and be straightforward to use.</p><p>We should always follow this steps: Match the view, act on the view and then assert what we expect to happen.</p><p>Instrumented Test — This lesson will focus on User Interface (UI) Tests which are a type of Instrumented Tests. Instrumented Tests need to be run on a physical device or emulator. There are a number of other types of tests available as well, such as Unit Tests that run on the Java Virtual Machine of the PC. Instrumented Tests are always located under module-name/src/androidTest/java/</p><p>In that test file, we can add a @Rule and a @Test. ActivityTestRule is a rule that provides functional testing for a specific, single activity.</p><p>Espresso is helpful for testing: Views, AdapterViews, Intents and Idling Resources.</p><p>Idling Resources are used when testing any asynchronous code, for example: long-running database operations that are off the main thread.</p><p><strong>2. AdapterViews Testing<br></strong>While onView() can handle most Views in our UI, Espresso does require a different method call when dealing with AdapterView widgets. Since AdapterViews such as ListView and GridView load data dynamically from an Adapter, only a subset of the contents may be loaded in the current view hierarchy at a time. This means that onView() may not be able to find the necessary view.</p><p>To handle this we need to use onData() which loads the adapter item we are interested in onto the screen before operating on it.</p><p>To help us further specify the item in the AdapterView we’re interested in, we can use a DataOption method such as inAdapterView() or atPosition().</p><p>After that, we perform an action and then check that we get the desired result on the view that we’re interested in.</p><p>We test Views in AdapterViews is very similar to how we test single Views — matching, acting, and asserting.</p><p>To find data in AdapterView:<br>onData(ObjectMatcher).DataOptions.perform(ViewAction).check(ViewAssertion)<br>To find data in views:<br>onView(ViewMatcher).perform(ViewAction).check(ViewAssertions)</p><p><strong>3. Intent Testing<br></strong>Intent testing divided to two:</p><blockquote>(1) Intent Stub — A small piece of code that acts as a fake response to an intent call during a test. The benefit of using a stub is that it gives us consistent results and allows us to focus on testing just one action at a time (For example: checking an interface). We use a stub or a canned answer that we can use to do the test. Intent stubbing is useful for testing intent responses. In code: intending(Matcher&lt;Intent&gt; matcher. How to code the test: (a) @Rule — use IntentsTestRule instead of ActivityTestRule (b) @before — stubbing an intent must be set up each time a test is run and we need to make sure all external intents are blocked. In android 6 (M) and later on we also need to grant for permission. (c) @Test — An example: intending(hasComponent(hasShortClassName(“.ContactsActivity”))).respondWith(new ActivityResult(Activity.RESULT_OK, ContactsActivity.createResultData(VALID_PHONE_NUMBER)));</blockquote><blockquote>(2) Intent Verification — Helps us to make sure that the information that was intended to be sent was what actually sent, by using a hardcoded matcher. In code: intended(Matcher&lt;Intent&gt; matcher, VerificationMode verification). How to code the test: (a+b) Check out intent stubs steps (c)@Test — An example: intended(allOf(hasAction(Intent.ACTION_CALL), hasData(INTENT_DATA_PHONE_NUMBER), toPackage(PACKAGE_ANDROID_DIALER)));</blockquote><p><strong>4. Idling Resources Testing<br></strong>In order to account for the time it takes for async background work to happen, we need to implement idling resources, which has a time delay that allows us to wait for the async background work to finish before continuing the test. In that case, Espresso will pause testing until the background tasks are done.</p><p>Espresso waits until the app is idle, or not doing anything, to perform the next action. It’s idle if there are no UI events in the current message queue, and there are no more tasks in the default AsyncTask thread pool.</p><p>IdlingResource is an interface that requires to implement the following methods:</p><blockquote>(1) getName()<br>(2) isIdleNow()<br>(3)registerIdleTransitionCallback(IdlingResource.ResourceCallback callback)</blockquote><p>To run a test that involves idling resources we will need to register the idling resource (Espresso.registerIdlingResources()) before the test is run using a @Before method. What happens at the @Before block occurs after the activity is created. We need to make sure that the idling resource is registered before the async task.</p><p>After the test, we need to unregister the idling resource (Espresso.unregisterIdlingResources()) in our @After annotation. We do so that we don’t cause any issues if the idling resource needs to be used elsewhere in the future.</p><p>To make Idling resources work, we must not forget to add its matching dependency in the gradle file.</p><p><strong>5. More Tests<br></strong>Espresso holds more test components then Views, AdapterViews, Intents and Idling Resources. More test options available in Espresso:</p><blockquote>(1) Espresso Web — An API for writing automated tests for apps that contain one or more WebViews. Espresso Web reduces the boilerplate code needed to interact with these WebViews.</blockquote><blockquote>(2) Espresso for RecyclerViews — Espresso testing for RecyclerViews works differently from testing AdapterViews. It doesn’t use onData(); instead, has actions that scroll to positions or perform actions on items.</blockquote><blockquote>(3) Espresso Test Recorder — Allows you to create UI tests by simply recording your interactions on a device and the Test Recorder will auto-generate the test code for you!</blockquote><p>Different kinds of tests:</p><blockquote>(1) Instrumented Unit Tests — These are tests that must be run on an Android device or emulator because they depend on the Android framework (like: UI tests). Instrumented tests run using the AndroidJUnitRunner which controls launching the app and running UI tests on it. Instrumented Tests live under module-name/src/androidTest/java/</blockquote><blockquote>(2) Local Unit Tests — Local Unit Tests are Unit tests that are only run on the local Java Virtual Machine and don’t necessarily depend on the Android framework. We will use the JUnit testing framework for Java to just test that local test. Local Unit tests live under module-name/src/test/java/. JUnit is a framework used to test discrete pieces of code (usually methods). Android provides JUnit testing support via the AndroidJUnit Test Runner.</blockquote><blockquote>(3) Android Testing Support Library — Espresso is just one test automation tool provided by the Android Testing Support Library. This Library also includes the followings:<br>(a) AndroidJUnit — A test runner that runs JUnit style tests on Android devices. When used in Espresso tests, it controls launching the app and running UI tests.<br>(b) UI Automator — Framework for cross-app functional UI testing between the system and installed apps.<br>(c) Espresso — Framework for functional UI Testing</blockquote><p><strong>REFERENCES:</strong></p><p>You can find much more at the free course Advanced Android App Development by Google on the Udacity website over here: (check it out!)</p><p><a href="https://classroom.udacity.com/courses/ud855">https://classroom.udacity.com/courses/ud855</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46d9592c3786" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Widgets — Let the fun begin!]]></title>
            <link>https://medium.com/@gadi.krn/android-widgets-let-the-fun-begin-fcbe4484666?source=rss-426b18be75af------2</link>
            <guid isPermaLink="false">https://medium.com/p/fcbe4484666</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[background-task]]></category>
            <category><![CDATA[apps]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[widget]]></category>
            <dc:creator><![CDATA[.]]></dc:creator>
            <pubDate>Sun, 02 Sep 2018 19:06:10 GMT</pubDate>
            <atom:updated>2018-09-02T19:06:10.814Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*wqmivjGKGd9Tg0laZSkqpA.jpeg" /><figcaption>The world of mini apps is now open for your users to play with!</figcaption></figure><p>Learn how users can interact with your apps from their home screen!</p><p><strong>1. Intro to Widgets<br></strong>Widgets are mini apps that live on the home screen. They’re usually an extension of an existing app that’s already installed on your device. Unlike smaller launcher icons that normally appear on your home screen, widgets usually take up more space and display up-to-date information from the app that they belong to.</p><p>Most widgets are usually resizable, and the information displayed can change depending on the size of the widget.</p><p>A common widget behavior is to launch the app when clicked. Some parts of the widget can also launch a specific activity within the app.</p><p>We should remember that widgets:</p><blockquote>(1) Widgets are a fun and easy way to interact with any app, but they could be resource intensive if not managed properly<br>(2) Widgets handle their own update schedule, but remember that they run on the main UI thread so to offload any heavy tasks to a new thread, probably by using IntentServices which can communicate back to the widget in any time.</blockquote><p><strong>2. How to create a widget</strong><br>To add a widget to any application we need to create 3 things:</p><blockquote>(1) Widget Provider — A class that extends the AppWidgetProvider class.<br>(2) Widget Provider Info — XML file that describes the widgets metadata, including information such as the minimum width and height, and other important properties. (Go into the XML folder)<br>(3) Widget Layout — XML file that describes the widget’s views which will be similar to any other layout file with some limitations. (Go into the layout folder)</blockquote><p>Widgets communicate with the app using broadcast messages. The files above makes widgets a broadcast receiver. To make it work, we need to register the widget provider in the manifest using a &lt;receiver&gt; tag.</p><p>Android Studio automatically can create all of the above for us! By clicking on the “app” module and choosing “new” → “widget” → “app widget”. All settings will go into the AppWidgetProviderInfo XML. This file include resizable options, minimum width and height, and “updatePeriodMillis” which specifies in milliseconds the interval in which the widget updates itself. The shortest interval allowed is 30 minutes to prevent battery drainage. We should initialize “initalLayout” attribute to be our widget layout. In addition, we can set “previewImage” to be our launcher icon, which sets the icon in the widget menu that appears when we’re going to drag it into the home screen.</p><p><strong>3. Customize a widget — Using RemoteViews<br></strong>It’s important to note that widgets layouts are based on something called RemoteViews. This is because the widget is treated as a seperate app that runs on the home screen.</p><p>Android uses a RemoteView object to describe the view hierarchy that will be displayed in another process.</p><p>A widget’s layout seems just like any other layout XML. However, RemoteViews have some limitations on what they can support. That means not every view type can be added in a widget layout. The most popular basic views are supported, but complicated views like constraint layout or RecyclerView are not.</p><p>RemoteViews objects contain the entire view hierarchy and not just individual view items. It means, instead of finding individual views using the findViewById() method like we do for normal layouts, RemoteViews come with some special methods that allow you to directly access and update individual views inside of it (Ex: setTextViewText()).</p><p>Unfortunately, there are things that you would be able to do with a view object that just aren’t available here.</p><p>To set the click handler to launch the app we need to modify our widget provider class.</p><p>In widget provider we have the onUpdate() method, which get called once a new widget is created and in every update interval. The boilerplate loop in the method goes through all the widget instances that may have been added to the home screen and updates them (yes, there could be multiple instances of the same widget). Always assume that multiple instances do exist and we need to update them all. We do so using the AppWidgetManager class by getting access information about all existing widgets on the home screen.</p><p>To update a widget we need to pass in the id of that widget along with a RemoteViews object describing that widget.</p><p>The way RemoteViews handle click events is different than how normal views do it. We can’t simply set the onClick attribute to run a custom method as we’re used to doing.</p><p>Instead, RomoteViews can be linked to a pendingIntent that will launch once that view is clicked. This is achieved by calling the setOnClickPendingIntent() method. It takes the view id that should listen to the clicks and the pending intent.</p><p>Remember that a pendingIntent is just a wrap around an intent that allows other applications to have access and run that intent in our app.</p><p>Since Android API 14 and onwards, Android automatically includes margins between widgets as they appear on the user’s home screen. However, on previous API versions this was not the case, so it’s still a good idea to specify a margin to include around the widget on devices running Android versions less than 14.</p><p><strong>4. Background tasks for widgets<br></strong>Click events and widgets can only launch pending intents. PendingIntent doesn’t necessarily need to start an activity in the foreground. Pending intents can start activities broadcasts and services.</p><p>When we plan to something in the background launching a service will make the most sense. We can set the setOnClickPendingIntent() to a new view in our widget to start a new intent service. This intent service can run an update query in the background thread.</p><p>To do so we need to create a new intent service class which extends from IntentService, give it an action and override its onHandleIntent() method.</p><p>To make the service to send an update or response back to the widget, like updating the image, we need to do the following steps:</p><blockquote>(1) Create a new action string in the service class<br>(2) Handle it at onHandleIntent() method<br>(3) Run a different query in the background<br>(4) Update the widget in the widget provide code</blockquote><p><strong>5. Using a GridView in a widget<br></strong>We can change the layout of the widget depending on its width and height.</p><p>There are couple of collection types vies that widget can support as GridView and ListView. There’s a special collection view called StackView, which is commonly used to display and flip between photo galleries. We can also build animations using ViewFlipper.</p><p>We used AppWidgetManager to get a list of widget ids and to update any widgets layout. One of this class methods is getAppWidgetOptions() method. This method returns a bundle object containing properties associated with the widget. That’s include the widget dimensions, widget category and any custom extras that we may added to the widget.</p><p>To trigger updates of widget dimensions change (or any other widget options) we should override onAppWidgetOptionsChange() method in the widget provider and there update the widget layout.</p><p>Widget layouts are built using RemoteViews, which are slightly different than normal views and the typical layout.</p><p>The difference becomes clear when dealing with collection type views, such as ListView or GridView. Just like we need an adapter for a typical GridView, with widgets we need to create a RemoteViewsFactory, which will be basically a thin wrapper that goes around an adapter.</p><p>The typical onBindViewHolder() method in an adapter be replaced by the getViewAt() method in the RemoteViewsFactory.</p><p>On top of the RemoteViewsFactory, we will also need to create a RemoteViewsService, which is the service that connects a remote adapter to be able to request RemoteViews.</p><p>Since the RemoteViewsService is in fact a service, we also need to register it in the manifest.</p><p>We need to call the notifyAppWidgetViewDataChanged() in the AppWidgetManager, to trigger the data update to the GridView widget in order to force a data refresh.</p><p>Click events in widgets are only handled through pending intents. However, it’s very costly to set pending intents on the individual items in a collection view, so that’s not allowed.</p><p>Instead, you can set a PendingIntent template for the collection view. The PendingIntent template allows us to specify the intent that we like all the items in the collection to launch when clicked. This template is applied to each and every item in the collection. But we can customize each individual item using something called a FillInIntent.</p><p>FillInIntent allows us to pass extra data to the PendingIntent template. That way, all items in the collection will launch the same activity, but each will pass a unique extra value that will allow the launched intent to react differently.</p><p>Remember that widgets layouts are based on RemoteViews, which act a bit different than regular views:</p><blockquote>(1) Click events are handled with pending intents and collections need a PendingIntent Template<br>(2) Not all view types are supported<br>(3) Collection views require a remote service and a remote view factory to act as an adapter</blockquote><p><strong>REFERENCES:</strong></p><p>You can find much more at the free course Advanced Android App Development by Google on the Udacity website over here: (check it out!)</p><p><a href="https://classroom.udacity.com/courses/ud855">https://classroom.udacity.com/courses/ud855</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fcbe4484666" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Media — Beat by bit!]]></title>
            <link>https://medium.com/@gadi.krn/android-media-beat-by-bit-43f5715a497b?source=rss-426b18be75af------2</link>
            <guid isPermaLink="false">https://medium.com/p/43f5715a497b</guid>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[framework]]></category>
            <category><![CDATA[medium]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[music]]></category>
            <dc:creator><![CDATA[.]]></dc:creator>
            <pubDate>Tue, 28 Aug 2018 21:09:50 GMT</pubDate>
            <atom:updated>2018-08-28T21:10:03.301Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*qJcOC6MVJq6hMKRtUQp3VA.jpeg" /><figcaption>Let the music speak!</figcaption></figure><p>Learn how to make your users move to the beats of your app!</p><p><strong>1. Player UI structure<br></strong>Using media in an app is a common task and nearly every use case shares some common features.</p><p>The first is the media player. The component that can take in digital media and render it as audio or video.</p><p>The second is the media controller. This is the piece of UI that controls the media player and include all of our playback buttons.</p><p>There are many options when it comes to these components including building them from scratch for our specific needs, but the nature of their interactions is nearly the same for every app.</p><p>Android framework provides 2 classes that impose a well defined structure for building a media player app:</p><blockquote>(a) Media Session — Sits between the media controller and the player. <br>(b) Media Controller — Sits between the media session and the UI.</blockquote><p>Both classes communicate with each other by session callbacks to keep the UI in sync with the player. We can also include extensible custom calls that can use to define special behaviors unique to our app.</p><p>We can think about this components as a standard decoupling pattern.</p><p>The media player isolates the player from our UI so we can easily swap different players or change the look and feel without changing the features available in the player.</p><p>Media is often controlled by more than one controller. This is why we should use it as a client-server architecture. The media session then becomes the server that holds the info about the media and the state of the player and each controller becomes a client that needs to stay in sync with the media session.</p><p>When playing both audio and video the UI is expected to stay visible for the duration of the playback. Navigating away from the UI should probably terminate the playback. For video apps the lifecycle of the player is completely tied to the lifecycle of the UI. For this reason, all components of the media app can be implemented in a single activity, which contains both the media controller hooked into the UI and the media session which controls the player.</p><p>When playing only audio we most likely would want the playback to continue even if the user navigates away from the UI. In this case, the player may outlive the activity that started it, if the user navigates away. We want to have our media session running in a service, which updates our UI activity when the player state changes. This activity-service communication is simplified by some framework classes so we don’t need to implement it ourselves.</p><p><strong>2. Players and media formats<br></strong>There are a few media players we can choose from:</p><blockquote>(1) MediaPlayer — Made by android framework. Provides the basic functionality for a player that supports the most common audio and video formats and data sources.<br>(2) ExoPlayer — Open source library that exposes the lower-level Android audio APIs. It supports high-performance features like Dash and HLS (adaptive streaming technologies). It can be customize making it easy to add new components.<br>(3) YouTube APIs — Are best for playing videos from youtube.<br>(4) Custom Media Player — Build from low level media APIs such as MediaCodec, AudioTrack and MediaDRM, that suits the exact needs of your our media app.</blockquote><p>The customizability of ExoPlayer makes it the prefered choice since its support of many different formats and extensible modular features makes it usable in almost every use case.</p><p>Media exists in a variety of different formats and we need to use a player that will support it.</p><p>The term media format can actually refer to a format at different levels:</p><blockquote>(1) Sample format — Used for Audio/Video frame. The format of the individual media samples (Ex: H.264, AAC…). Typical video file will contain media in at least two sample formats — One for the video and one for the audio.<br>(2) Container format — This format houses the media samples and associated metadata. A media file has a single container format (Ex: mp4, avi…), which is commonly indicated by the file extension.</blockquote><p>For some audio only formats, like mp3, the sample and container formats might be the same.</p><p><strong>3. Add media controller to the code<br></strong>Remember that a media player belongs in either a service or an activity, depending on whether the app requires background playback.</p><p>The best architecture for a media player is de-coupled such that the player itself never communicates with the UI that controls it but only to a media session which is then connected to the UI through a media controller.</p><p>The reason for the de-coupled client-server structure is the possibility of multiple clients. And for that, a media session is necessary.</p><p>But the ExoPlayer library includes a UI element called SimpleExoPlayerView which greatly simplifies implementing a controller for ExoPlayer. It automatically binds to the ExoPlayer instance using the single setPlayer() method.</p><p>We still want a media session so that we can control our media from other clients (as our headphones). We can have it both if we threat the ExoPlayer player view as an atomic unit without the need for a media session to mediate the communication between UI and player. Then we can create a seperate media session, keeping it in sync with the ExoPlayer state. This way external clients can still control the player through the media session but the SimpleExoPlayerView will control the ExoPlayer directly within the app.</p><p>We can customize the SimpleExoPlayerView layout file to give it a different look or add/remove controllers creating a new xml layout file with the name “exo_playback_control_view.xml”.</p><p>The last step is to make it play well with external clients and other apps. But before we can set up a Media Session, we need to find out what the state of ExoPlayer is so that we can keep our Media Session in sync. We can do it by using the ExoPlayer.eventListener interface and then override it onPlayerStateChanged() method.</p><p><strong>4. Add media session to the code<br></strong>Creating a media session in an activity breaks down to the following steps:</p><blockquote>When activity created:<br>(1) Create a MediaSessionCompact object<br>(2) Set the flags (features we want to support)<br>(3) Set an optional media button receiver component<br>(4) Set the available actions and the initial state<br>(5) Set the callbacks (An inner class extends from MediaSessionCompat.Callback with the following methods: onPlay(), onPause(), onSkipToPrevious()) — our media session external clients will use them when they perform the actions<br>(6) Start the session</blockquote><blockquote>When activity destroyed:<br>(7) End the session when it’s no longer needed</blockquote><p>We need to ensure whether the app is controlled from the internal client or any external client, both the ExoPlayer and the media session contain the state information and remain in sync.</p><p>We need to make sure that when the state changes from the UI, the media session is updated. We can do it by using the PlaybackStateCompact.builder class to build a PlaybackStateCompact object and pass it into our media session using the setPlaybackState() method. We should do it every time the player state changes.</p><p>We also need to make sure that external clients can control the ExoPlayer as well. Our MediaSession.callbacks will automatically be called by external clients provided they use a media controller to control the session. All that we need to do then is to make sure our callbacks call the appropriate ExoPlayer method, which will then trigger the ExoPlayer.EventListener and therefore update the media session state.</p><p><strong>5. Android media framework and ExoPlayer extras</strong></p><p>Android Media Framework Extras:</p><blockquote>(1) Audio Focus — This is how the Android framework knows about different applications using audio. Used for “fade out” sound for example.<br>(2) Noisy Intent — android framework sends out the ACTION_AUDIO_BECOMING_NOISY intent when headphones are plugged off, which allow us to register a broadcast receiver and take a specific action when this occurs <br>(3) Audio Stream — Android uses separate audio streams for playing music, alarms, notifications, etc. This allows users to control the volume of each stream independently.</blockquote><p>ExoPlayer Extras:</p><blockquote>(1) Subtitle side loading — Given a video file and a separate subtitle file, MergingMediaSource can be used to merge them into a single source for playback.<br>(2) Looping a video — A video can be seamlessly looped using a LoopingMediaSource.</blockquote><p><strong>REFERENCES:</strong></p><p>You can find much more at the free course Advanced Android App Development by Google on the Udacity website over here: (check it out!)</p><p><a href="https://classroom.udacity.com/courses/ud855">https://classroom.udacity.com/courses/ud855</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43f5715a497b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Places — Let’s go!]]></title>
            <link>https://medium.com/@gadi.krn/android-places-lets-go-155caa824e61?source=rss-426b18be75af------2</link>
            <guid isPermaLink="false">https://medium.com/p/155caa824e61</guid>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[google-play-services]]></category>
            <category><![CDATA[location]]></category>
            <category><![CDATA[places]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[.]]></dc:creator>
            <pubDate>Wed, 15 Aug 2018 17:47:33 GMT</pubDate>
            <atom:updated>2018-08-15T17:48:23.303Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*XuY8VXr4cGzd66vLBIQrew.gif" /><figcaption>Write me in the comments — Where are you from and where would you like to go next? :)</figcaption></figure><blockquote>Time to explore the world! Or at least explore Android location and places!</blockquote><p><strong>1. How location works and intro to Google Play Services<br></strong>There are 2 ways to detect a device’s location:</p><blockquote>(1) GPS — Global Positioning System (GPS) which is built in your phone. This module receives signals from all satellites in sight and then triangulates the device’s position based on a signal strength from each satellite, within an accuracy of a few meters. GPS drains the phone’s battery and it best to request it only every now and then.</blockquote><blockquote>(2) Cell towers and WiFi hotspots — Their accuracy not match the GPS one, but they do tend to use much less battery power than using GPS. They are quicker in helping decide what country or area the device is located. They have faster communication than GPS to locate the device for the very first time.</blockquote><p>Combining all these techniques together Android can smartly locate a device with the best accuracy and with minimal power consumption.</p><p>Google Play Services is an API package that is managed and updated automatically by Google play. Google Play Services started out as a simple way to offer developers access to Google authentication APIs but expanded to include a lot more Google powered services, including location APIs.</p><p>To able to use some of Google Play Services we need to sign up for an API key.</p><p>This API key, after generated, should be added as a meta-data in our AndroidManifest. To be able to use any of Google Play Services we need to include them as dependencies in our build.gradle file (like the places and location APIs).</p><p>To connect and use Google Play services we need to do the following steps:</p><blockquote>- Create and include API key<br>- Add dependencies to build.gradle<br>- Grant required permissions<br>- Create a Google API client</blockquote><p>There are 2 types of location permissions that we can add to the manifest:</p><blockquote>(a) ACCESS_COARSE_LOCATION — Permission to access location via network provider (Cell towers and WiFi hotspots)<br>(b) ACCESS_FINE_LOCATION — Permission to access GPS as well to more accurate location.</blockquote><p>To create a Google API client we need to use GoogleApiClient.Builder in our code.</p><p><strong>2. Get Place by ID<br></strong>The Places SDK for Android provides your app with rich information about places, including the place’s name and address, etc. To access this information for a specific place, you can use the place ID, a unique identifier.</p><p>When using any API, you should make a habit of familiarizing yourself with the terms and conditions that accompany it. Please note that Google requires any developer to follow certain rules when using their APIs and you can read more about it in their policies.</p><p><strong>3. GPS Polling and Geofences</strong><br>There are couple of ways to listen to a device location.</p><p>GPS Polling is one of them, this method request a GPS signal every known short time, and therefore it drains the phone battery pretty fast. It’s not a good best practice to use when you want to compare between remote and local locations.</p><p>Geofence is another way to listen to a device location. A geofence is a virtual perimeter surrounding a particular real world physical location. You can have up to more 100 geofences per device. We can start listening to geofence simply by registering it with Google Play Services. Android will keep listen to that geofence even if our app isn’t running.</p><p>When entering/existing a geofence the system will launch an intent of whatever type you’ve specified — intent service or a broadcast receiver.</p><p>Each geofence has a lifetime that we can specify when creating it. Once expired, location services automatically removes that Geofence. We can also unregister all geofences registered by your app at any time y explicitly removing them from Google Play Services.</p><p>We can set a geofence to never expired but this is very dangerous (!) because if we won’t unregister it, it will stay even if we will uninstall the app! We can use JobScheduler to re-register a geofence after it expires.</p><p>In Geofences Android optimizes all 3 location techniques to minimize battery consumption. Cell towers and WiFi, along with the latest GPS location are al used first to check if there’s a chance of entering or exiting a geofence.</p><p>Then polling live GPS data is rarely forced, so we stay kind to our users battery. Pay attention that using geofence might take a device might need a few minutes to know it got in or out from the geofence zone. It best practice to use geofence when we try to follow entering/exiting a particular place.</p><p><strong>REFERENCES:</strong></p><p>You can find much more at the free course Advanced Android App Development by Google on the Udacity website over here: (check it out!)</p><p><a href="https://classroom.udacity.com/courses/ud855">https://classroom.udacity.com/courses/ud855</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=155caa824e61" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android FCM — Sharing is caring!]]></title>
            <link>https://medium.com/@gadi.krn/android-fcm-sharing-is-caring-dc04704a7fc8?source=rss-426b18be75af------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc04704a7fc8</guid>
            <category><![CDATA[firebase-cloud-functions]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[messaging]]></category>
            <dc:creator><![CDATA[.]]></dc:creator>
            <pubDate>Tue, 14 Aug 2018 23:14:54 GMT</pubDate>
            <atom:updated>2018-08-14T23:15:46.951Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qmvFg6ILS7Y8WsUxa2vLOw.gif" /><figcaption>FCM in a nutshell. (Animation made by The Firebase Blog by Google)</figcaption></figure><blockquote>FCM or Firebase Cloud Messaging, what‘s the rush?</blockquote><p><strong>1. Polling vs. Pushing<br></strong>Chats and social media apps share one thing in common — they all connect to the internet and receive their data from a server.</p><p>For app to work like that we need a client app and a web server. Engineers who work on servers knows as back-end engineers.</p><p>As client side engineers we need to decide how to sync data to our app with the data on the server. There are two data syncing strategies:</p><blockquote>(a) Polling — The act of continually pinging the server every so often to see if there are any updates. Apps using JobSchedulers or sync adapters using the polling strategy. We need to be careful to not uselessly pinging the server, otherwise it will drain the battery.</blockquote><blockquote>Using the wireless radio is one of the most battery-draining things we can do on an Android device. Every time the wireless radio is used, our device needs to power up the radio, which is especially costly. It is much better to do a bunch of network activity all at once. <br> <br>(b) Pushing — Apps that need data in real time used that strategy. In pushing strategy the server is responsible for telling the phone when it has new information. It is mostly used when we talk to a server that gets updates not in a regular time. The server can decide what information to send down in the message. Once the client app received the message it’s up to the client app how to respond.</blockquote><p><strong>Pushing as an update strategy is always more battery efficient than polling.<br></strong>The cost is that we need to change the code both in the app and in the server.</p><p><strong>2. Intro to Firebase Cloud Messaging<br></strong>Pushing is a good strategy when we are looking to have real time updates and spare our users battery.</p><blockquote>How can we set up pushing strategy?<br>Server side:<br>- Our server to keep track of the different client devices<br>- Our server needs to be able to deliver messages, even if one of the phones temporarily loses connectivity, or is off.</blockquote><blockquote>Client side:<br>- Our app needs to be configured to handle messages from the server</blockquote><p>Google simplifies pushing by offering a cloud messaging service called Firebase Cloud Messaging, or FCM for short. FCM service has 2 parts:</p><blockquote>(a) FCM server — Manages and sends messages to our client devices.<br>(b) Android client FCM messaging library — Allows you to receive messages from the FCM server on the client app.</blockquote><p>FCM gives you some free functionality:</p><blockquote>(a) Automatic retries — FCM will know when the message has been sent successfully.<br>(b) Mass messages — Send messages to groups of phones and multiple devices.<br>(c) Cross platform — Work for Android, iOS and the web.<br>(d) Scale — FCM could deliver messages to huge numbers of users fast.</blockquote><p><strong>3. Intro to Firebase<br></strong>In May 2016, Google took a pre-existing product called Firebase and expanded it into what is now a one stop shop for a bunch of technologies that make building mobile and web apps easier.</p><p>Firebase is a platform where you can mix and match common features of web and mobile apps, and then use Google SDKs to include them in your app. A lot of google services were packed as part of Firebase.</p><p>How to set up FCM?</p><blockquote>(a) Make a Firebase account<br>(b) Make a new Firebase project<br>(c) Configure the project with the Android client<br>(d) Send your first message</blockquote><p>Every separate project that you have that uses Firebase should have a different Firebase project associated with it. A single project may have multiple types of app platforms (clients) associated with it. Connecting to Firebase will involve some configuration in the Firebase console, along with changing a few things in your Android app to add the Firebase SDK.</p><p><strong>4. Intro to messages<br></strong>The firebase console sends message to the FCM server that will be sent to our app (client).</p><p>The way the notification data is bundled looks like a json, with the “notification” as the main object and “body” as the message itself. Using the Firebase console its possible to send extra data in the form of key-value pairs.</p><p>The automatically generated notification on your device will open the activity using an intent, which have our extra data that we’ve sent along with the message.</p><p>By using the extra data we can detect weather the intent that opened the app came from FCM or not. So, we can make our app react differently if it was launched from the FCM notification as opposed to somewhere else.</p><p>The ability to accept a ping from FCM and then turn it into a notification which then opens up your app is a feature that’s built in to the FCM SDK.</p><p>We can target everybody uses the app using “user segment” or a single device using FCM registration token, which uniquely identify a device. It’s generated when the app first starts and changes when we reinstall the app. We can find it by printing it to the log while creating a service that would extends from FirebaseInstanceIdService.</p><p>We can send real data messages, not just notifications, by creating our own server that can talk to the FCM server to send out the messages.</p><p><strong>There is a difference between notification messages and data messages.<br>Our app will react differently when it gets a notification message or data message.</strong></p><blockquote>Notification message:<br>- Main json object is “notification”<br>- Display notification automatically when the app is in the background<br>- Predefined key values (“body”)<br>- Extra values in intent extra<br>- Can be sent from Firebase console<br>- App in the background: shows notification<br>- App in the foreground: triggers onMessageReceived()<br>* Example: advertisements or notifications</blockquote><blockquote>Data message:<br>- Main json object is “data”<br>- Requires you to do all the data processing<br>- All custom key value pairs<br>- Cannot be sent from Firebase console<br>- App in foreground or background triggers onMessageReceived() <br>* Example: Email app that should sync</blockquote><blockquote>Notification and data message combined:<br>- Cannot be sent from the Firebase console<br>- Behave like a notification message<br>- App in the background: shows notification, does not trigger onMessageReceived(), the notification has extras in the intent <br>- App in the foreground: triggers onMessageReceived()</blockquote><p>To receive and process a data message, you need to implement another service called FirebaseMessagingService. We can do it by implementing the next steps:</p><blockquote>(a) Create service that extends FirebaseMessagingService<br>(b) Add service to manifest with MESSAGING_EVENT intent filter<br>(c) Override onMessageReceived()</blockquote><p>This will create a service on your client phone that is triggered by incoming FCM data messages, as well as notification messages when the app is in the foreground. This is useful because it means the app can be in the background and get pinged by FCM data message. We can execute any code we want in onMessageReceived().</p><p>The onMessageReceived() takes a RemoteMessage object as a parameter. You can use this object to get a map of the data contained within the message by calling getData(). getData() will return a map object with keys and values that are both strings.</p><p>In conclusion, whether the incoming message is a data message or a notification message is determined bb whoever built the server. We have the choice.</p><p><strong>5. Sending to multiple devices<br></strong>To get global reach we want to send updates to many followers. There are a few ways to send data to multiple phones using FCM:</p><blockquote>(a) Device groups — Typically sets of devices that all belong to the same user (ex: 2 phones and a tablet with the same app). We can store sets of devices together in a device group. The creation and management of these device groups is done all in the server side on the app server.</blockquote><blockquote>(b) Topics — Topics are like mailing lists. Some client devices will choose to subscribe to a topic, and then only those devices which subscribed will be sent the messages when the topic sends a message.</blockquote><p>How topics look like in code?</p><blockquote>On the server side, instead of sending a message to a specific id, we could send the message to a topic. A topic is represented by a single string key. Note that the topic key will always come after the word “topics”, surrounded by forward slashes. Client devices can subscribe and unsubscribe to topics using that key.</blockquote><p>This would then send the associated data or notification message to all client devices that are registered to that topic. The key we subscribe to and the key the server sends the message to — must be identical.</p><p><strong>REFERENCES:</strong></p><p>You can find much more at the free course Advanced Android App Development by Google on the Udacity website over here: (check it out!)</p><p><a href="https://classroom.udacity.com/courses/ud855">https://classroom.udacity.com/courses/ud855</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc04704a7fc8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Libraries— Don’t reinvent the wheel!]]></title>
            <link>https://medium.com/@gadi.krn/android-libraries-dont-reinvent-the-wheel-df4ad2990148?source=rss-426b18be75af------2</link>
            <guid isPermaLink="false">https://medium.com/p/df4ad2990148</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[android-sdk]]></category>
            <category><![CDATA[libraries]]></category>
            <dc:creator><![CDATA[.]]></dc:creator>
            <pubDate>Wed, 08 Aug 2018 20:20:01 GMT</pubDate>
            <atom:updated>2018-08-08T20:23:50.952Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*UxQMWe37A0ik0urQdCUWlA.gif" /><figcaption>You shouldn’t reinvent the wheel. (Animation made by Jelio D. for 4+ Studio)</figcaption></figure><blockquote><strong>1. Intro to Libraries</strong></blockquote><p>Any community of programmers understands the <strong>importance of not reinventing the wheel</strong>, Android is the same. They do so by using libraries.</p><p>A library in the programming world is a <strong>set of classes and methods that can be reused</strong> in different projects. Libraries allow you to <strong>include complicated features and reducing boilerplate code</strong> with ease.</p><p>Example to known libraries: Android Support Library, FirebaseJobDispatcher, Google Play Services, etc.</p><blockquote>One power library for facial recognition is the Google Mobile Vision Library.<br>This library receives an image for processing using a method called Classification. Classification analyzes the image and returns probabilities that each eye is open and that the person is smiling for each face detected in the image.<br>To use it we have to make sure our Google repository installed in our SDK manager.</blockquote><blockquote>Android Support Library provides backwards compatibility for newer features of Android, so as developers we don’t need to write different code for different API levels. Additionally, it provides convenience classes and features not available in the standard Framework API for easier development and support across more devices. One example of the Support Library in action is the use of runtime Permissions.</blockquote><blockquote>Third party libraries are useful for solving problems that appear over and over again in different applications, we can find some useful ones over StackOverflow, Android Arsenal and GitHub. When your app size, including its libraries, pass the limit (64K) of the Android app build architecture — you should enable multidex on your app gradle file.</blockquote><blockquote><strong>2. Choose &amp; Explore a Library</strong></blockquote><blockquote>4 ground rules to choose a good library:</blockquote><blockquote>(1) <strong>Maintenance </strong>— <em>Android is a constantly evolving entity and we want a library yo evolve with it. Question to be asked: Who made the library (individual/company)? Is it deprecated?</em><br>(2) <strong>Known Issues </strong>— Many libraries have an issues section where user can submit problems they found. Make sure none will affect our application.<br>(3) <strong>Features </strong>— Most of the time there are several libraries to accomplish similar tasks. We should be checking their features list to find which should choose the best one to fit our app without a ton of extra functionality that will only increase our APK size. We can run a google search with the “vs.” word to check between different libraries. <br>(4) <strong>License </strong>— Check if you need to include a copyright notice in your application or any other restrictions.</blockquote><blockquote><strong>3. Useful libraries</strong></blockquote><blockquote>3 useful libraries you should know about:</blockquote><blockquote>(1) <strong>Picasso and Glide </strong>— very robust libraries that facilitate the loading, caching and displaying of Images.<br>(2) <strong>Butterknife </strong>— revolutionary library that uses annotations to make data binding much easier in code.<br>(3) <strong>Timber </strong>— cool tool for Logging. Timber provides a modifiable platform for all our logging needs, such as auto error detection and different logging logic for Debug and Release versions of our app.</blockquote><p><strong>REFERENCES:</strong></p><p>You can find much more at the free course Advanced Android App Development by Google on the Udacity website over here: (check it out!)</p><p><a href="https://classroom.udacity.com/courses/ud855">https://classroom.udacity.com/courses/ud855</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df4ad2990148" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Fragments — Modularity is key!]]></title>
            <link>https://medium.com/@gadi.krn/android-fragments-modularity-is-key-596d59b3ea62?source=rss-426b18be75af------2</link>
            <guid isPermaLink="false">https://medium.com/p/596d59b3ea62</guid>
            <category><![CDATA[fragments]]></category>
            <category><![CDATA[communication]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[responsive-design]]></category>
            <dc:creator><![CDATA[.]]></dc:creator>
            <pubDate>Wed, 20 Jun 2018 04:47:12 GMT</pubDate>
            <atom:updated>2018-06-20T04:47:12.644Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ceU0zP4fbN3mVzYChR573g.png" /><figcaption>Things gone modular!</figcaption></figure><p><strong>1. Intro to Fragments<br></strong>Fragments are Android app components that represent a self contained portion of user interface in an activity. We can refer them as mini activities.</p><p>Fragments are reusable, modular and can be dynamically changed at runtime. They can help us build responsive and flexible layouts. Fragments are reusable pieces of UI, similar to a layout or viewGroup, and can be arranged differently based on screen size.</p><p>They commonly used to create single-pane and multi-pane layouts, depends on what looks better on our given screen size (Ex: Gmail app in phone and tablet).</p><p>The layout can change based on the screen size, and it’s best to use fragments to define each layout and make the best use of the screen space to make our app user friendly.</p><p>This is a common pattern which called the master/detail flow. The master lists of items will take up an entire phone screen but only the left portion of a tablet screen. The detailed content pane will take up the entire phone screen as a separate activity but only the right portion of a larger tablet screen.</p><p>The power of using fragments is that they allow us to fully modularize our activities. We can combine multiple fragments in a single activity to build a multi-pane UI, like on a tablet. We can also reuse a single fragment in multiple activities.</p><p>Fragment has its own life cycle. It can receive its own user input events like clicks and swipes. We can dynamically add or remove them while the activity is running.</p><p>Activities are meant to be in separate screens and not embedded within one another, that’s why we use fragments, which are designed to be placed alone or in groups within a single activity. Fragments must always be embedded within activity and the fragment’s life cycle is directly affected by the activity’s life cycle.</p><p>When the activity moves through its life cycle callbacks, so does the fragments they contains.</p><p>In most cases, we can move any functionality from the activity lifecycle callbacks to their corresponding callback inside a fragment.</p><p>There are some differences — Fragment have additional lifecycle callbacks that allow them to be created or removed in an activity at runtime:<br>(1) Fragment use onCreateView() in addition to onCreate(). OnCreateView() is where a fragment inflates its UI, hooks up any data sources it needs, and then returns the created view to the host activity.<br>(2) There is also a corresponding onDestroyView() callback that can be called before the activity is destroyed.</p><p>With these additional callbacks, the fragment can cycle through its whole life cycle multiple times while its activity is running.</p><p><strong>2. Steps to dynamically display a fragment</strong><br>(1) Create a layout that defines the appearance of the fragment<br>(2) Create a new fragment class that inflates the layout<br>(3) Create a new fragment instance in a host activity<br>(4) Add the fragment to it’s host activity using the FragmentManager and a fragment transaction</p><p><strong>3. FragmentManager and transactions<br></strong>Android uses the FragmentManager to create or swap out fragments.</p><p>The FragmentManager class provides methods that allow to add, remove and replace fragments in ac activity at runtime.</p><p>Add, Remove and Replace ar all types of fragment transactions. These transactions let you create a dynamic experience and help efficiently add and remove fragments without you have to worry about the finer details of memory management.</p><p>An important rule when dealing with dynamically adding or removing fragments while an activity is running is that our activity layout must include a fragment container in which you can add each fragment, which is often an empty FrameLayout. The container is responsible for defining the size and placement of a fragment, since the fragment doesn’t have to take up the entire screen like an activity.</p><p>When we add or replace a fragment at runtime, we need to tell the fragment transaction the container to place the updated fragment in. Containers are needed if we plan on performing fragment transactions.</p><p>The only case we won’t need a fragment container is when we know our fragment will remain static, which means it won’t change during runtime. Then it will not need a container layout because a static fragment size, content and location can be defined and will stay the same for the duration of an activity. In this case we can place the fragment in a layout using the &lt;fragment&gt; tag instead of a transaction. The &lt;fragment&gt; should have a name, width and height. The name of the fragment should point to the type of fragment we want to be.</p><p>To get our FragmentManager we need to call getSupportFragmentManager(). This gives as a fragment manager using the support library APIs. The manager is responsible for starting and completing fragment transactions. When we ready to complete the transaction we must call commit().</p><p><strong>4. User interactions on fragments<br></strong>One common user interaction is to update the image display when the user clicks on a fragment or a view in a fragment.</p><p>We can achieve that by creating a clickListener, so fragments can respond to clicks by changing the image they’re displaying.</p><p>It’s a good practice to handle the click interaction within the fragment class for re-usability and modularity.</p><p>We have to remember when we rotate the phone the configurations change and we would probably would like to save using onSaveInstanceState().</p><p><strong>5. Communication between fragments<br></strong>To build fragments for maximum reusability, we should make each fragment self contained. It means that a single fragment will also contain code that defines its layout and behavior, when it comes to user interaction. It also means that generally, fragments can never directly communicate with one another.</p><p>All fragment to fragment communication can be done through a shared activity.</p><p>To give a fragment the ability to communicate up to its host activity, it’s good practice to define an interface in the fragment class, and implement it within the activity.</p><p>To define an interface we can create a listener in the master fragment, this interface will be implemented in the host activity, and there we can program it to perform some action whenever a fragment is clicked. To define this interface we specify the method it triggers. We have to make sure in our fragment’s onAttach() method that the host activity implements the callback.</p><p>To keep fragments modular and reusable, we cannot have them communicate directly with one another or directly tied to the host activity. An interface gives you a way to communicate but also stay modular because it can be implemented by any host activity. This way the fragment is not tied directly to an activity.</p><p>To transfer information from our main activity to our fragment we need to use our implemented interface method on main activity and then pass the wanted values to a new activity using intent.</p><p>In some cases we would like to make a flexible UI to support both phone and tablet — one and two pane views.</p><p><strong>REFERENCES:</strong></p><p>You can find much more at the free course Advanced Android App Development by Google on the Udacity website over here: (check it out!)</p><p><a href="https://classroom.udacity.com/courses/ud855">https://classroom.udacity.com/courses/ud855</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=596d59b3ea62" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android User Interface — User Friendly Design :)]]></title>
            <link>https://medium.com/@gadi.krn/android-user-interface-user-friendly-design-251e33c1d222?source=rss-426b18be75af------2</link>
            <guid isPermaLink="false">https://medium.com/p/251e33c1d222</guid>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[responsive-design]]></category>
            <dc:creator><![CDATA[.]]></dc:creator>
            <pubDate>Wed, 13 Jun 2018 10:45:48 GMT</pubDate>
            <atom:updated>2018-06-13T10:45:48.366Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eYL6OC6d6D9BRSt_dM38Dw.jpeg" /><figcaption>Happy users - Happy programmers :)</figcaption></figure><p><strong>1. Android design Principles<br></strong>Enchant me. Simplify my life. Make me amazing.</p><p>Those are the 3 key principles underlying the Android team’s creative vision for any app platform. Our goal is to empower our users by amazing design and friendly UI.</p><p>Users judge the quality of an app within the first 30 seconds, most of it based on the visual aesthetics. User Experience (UX) is also really important. It should be fun to use and customize for our users.</p><p>One common way to go from a starting concept to a polished final app is to have a visual model in mind.</p><p>We can do so by creating a model of what we want our final app to look like. In companies that mostly the job of the designers team, and they refer as mockups.</p><p>A mockup is a model of an app used for design evaluation. It’s usually a picture or animation of the final app. Detail mockups include specific colors to use and marking called keylines.</p><p>Keylines specify the exact size and spacing of app components in the layout. For every detail that’s provided in a mockup it’s our job as developers to develop it in the code.</p><p>Designers follow the android material design, which is a set of principles for creating useful and beautiful visuals and interactions across different devices and platforms.</p><p><strong>2. Colors and Fonts<br></strong>Colors are a big part of app design both for branding and visual consistency.</p><p>Most apps use a few colors and use contrast to highlight different components within the app. Colors should always work together and help to distinguish between views and interactive components.</p><p>Android material design guidelines recommend having a primary color and an accent color. The primary color is the main color base for our app. Views and components like the menu bar will generally include this color. Accent color is typically brighter and use to draw attention to key elements like buttons in an app.</p><p>It’s common to choose 3 slightly different shades of the primary color to use and one near opposite accent color. It gives the interactive components a high contrast that’s important for visibility. Always keep in mind which colors will add clarity and consistency.<br>Another way to add consistency and distinguish different views in our app is by using different fonts and text sizes.</p><p>The default font for android is a Roboto, which designed to work across a range of different sized platforms, and with a variety of font families.</p><p>Font families are groups of fonts that share similar design characteristics, like <em>serif</em> and <em>sans-serif</em>. <em>Sans-serif</em> is the default in android.</p><p>The android material design site has recommendations for sizes and font families to use for reliability.</p><p>It’s good to stick with one font family in our app and change the color, weight or size when text need to stand out. It’s also good to have only a few consistent styles for different text components and not just change the style at random (like enlarge text size of titles).</p><p>Text size is measured in units of sp, which are Scale-Independent Pixels. They keep the same physical size across different resolution screens.</p><p>Scale-Independent Pixels will stay the same physical size in different resolutions.</p><p>Unlike dp, sp are also used for accessibility purposes. If someone changes their text size settings to be larger for visibility, then android will enlarge any view whose size is in sp.</p><p>Using units of sp for text makes sure that the text in our app will respond to accessibility settings and will be readable across devices.</p><p><strong>3. Styles and Themes<br></strong>Most views in android will stick to a few simple text styles and colors that will repeat throughout the code.</p><p>Android gives as a way to group properties like the color and size of a view, as a style or theme.</p><p>A style is an xml resource file, separate from the layouts, where you can set all these properties in one place. Then later, we can apply that style to any view we want.</p><p>Theme is created in the same way, and is just a style that’s applied to an entire activity or application and not just one view.</p><p>Different styles can inheritance from one another using the parent attribute. Styles and themes use inheritance similar to classes. If a style has a parent, it will inherit all the properties that the parent style includes. Then it can define only the properties that we want to add to that style or override in the parent class.</p><p>Android comes with both light and dark themes we can choose from. To change the theme of our app or for individual activity, we just need to set its theme attribute in our android manifest file.</p><p><strong>4. Responsive Layouts<br></strong>It is important to design our app to look good across different devices. Same layout in one device will most likely look different on another screen size.</p><p>There are tools to optimize the user experience across different devices. It calls responsive design.</p><p>Responsive design is the act of creating designs that respond to and work well on a variety of screen sizes, shapes and orientations.</p><p>Android categorizes the device screen using two general properties:<br>(1) Size<br>(2) Pixel density</p><p>We have to take both into consideration when we design our app’s layouts and include image resources.</p><p>Density is the number of pixels in the physical area of the screen, and it’s often measured in dots per inch — dpi.</p><p>There are 5 density rangers in android known as density buckets which most android devices fall into:<br>(1) mdpi (medium) — 160dpi<br>(2) hdpi (high) — 240dpi<br>(3) xhdpi (extra-high) — 320dpi<br>(4) xxhdpi (extra-extra-high) — 480dpi<br>(5) xxxhdpi (extra-extra-extra-high) — 640dpi</p><p>A greater number of smaller pixels allow for a sharper and better image quality on those high density displays.</p><p>The same physical area on one of those high density devices will take up more pixels than that same area on a smaller density screen.</p><p>We have to use Density-Independent pixels (dp) to show same physical size views on different devices.<br>We want to use dp for spacing and images so we can design for size and not by pixels.</p><p>If we include images in our app, we should provide multiple image resources that are appropriately scaled for each of the generalized density buckets. If we only provide one size of image android might have to scale that image for each device. This takes processing power and might distort the image. Providing multiple image resources help achieve good graphical quality and performance across different devices.</p><p>We need to create layouts and assets optimized for different screen pixel densities and sizes.</p><p>All externalized android resources, from Strings to layouts, are all stored within our project’s res folder.</p><p>Android allows us to create alternative versions of every resource by placing them into folders with different qualifiers, separated by ‘-’. We can add those qualifiers based on anything, from language, dialect, pixel density, orientation, type of touch screen or if the devices is docked. Most importantly, for a responsive design, the smallest available screen width which we can support with that layout.</p><p>Android will check the current device configuration at runtime and load the right layouts.</p><p>We can chain these qualifiers together, like a combination of screen size and device configuration. These values can change in runtime, the most common change is the orientation. For this reason activities are destroyed and recreated whenever the device configuration changes.</p><p>To optimize our user experience on different screen sizes, probably the most useful resource would be the smallest width or sw qualifier. -sw&lt;size in dp&gt;</p><p>This allows us to create different resources for devices based on the smallest dimension.</p><p>By using the smallest width qualifier on new layout folders,android let’s us create alternate layout resources for different devices based on their size and it’s let’s us pick which default layout resources to override. We can also use the smallest width qualifier to create alternate values resource folders.</p><p><strong>5. Touch Selectors<br></strong>Touch selectors can be added to list items in recyclerview, so when we click them, they turn different color and react to our touch.</p><p>By responding to a user’s touch selectors provide important interactive feedback, which enhances the overall user experience.</p><p>To build a touch selector we need to create a new drawable resource, which is basically something that can be drawn on screen, like a colored background.</p><p>The root element for our new drawable have to be a selector. Inside the selector we will add 4 items: 3 items with attributes for both the drawable color and for state pressed, activated and selected which should be set to true. By including all 3 of these states we cover all scenarios when a user has clicked on a list item. Then we also need to include a default item for unselected state with the drawable color of the default background.</p><p>Next we need to apply it to the list item layout, by adding it as a background attribute to the root element of this xml.</p><p><strong>REFERENCES:</strong></p><p>You can find much more at the free course Developing Android Apps by Google on the Udacity website over here: (check it out!)</p><p><a href="https://www.udacity.com/course/new-android-fundamentals--ud851">https://www.udacity.com/course/new-android-fundamentals--ud851</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=251e33c1d222" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android User Interface — Make your app looks professional!]]></title>
            <link>https://medium.com/@gadi.krn/android-user-interface-make-your-app-looks-professional-c585330719d7?source=rss-426b18be75af------2</link>
            <guid isPermaLink="false">https://medium.com/p/c585330719d7</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[responsive-design]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ui]]></category>
            <dc:creator><![CDATA[.]]></dc:creator>
            <pubDate>Tue, 12 Jun 2018 12:36:52 GMT</pubDate>
            <atom:updated>2018-06-12T12:36:52.272Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TMZBI59FyHd6BFyLcgj4qw.jpeg" /><figcaption>Be professional</figcaption></figure><p><strong>1. Views and View Groups<br></strong>Views are rectangles that appear on the screen. View handles drawing and event handling and all the basic widgets in Android extend from the base View class.</p><p>When we want to style and design the view widgets we should do it according to Android Material design guide.</p><p>To display multiple view together, we need a ViewGroup, a container for children views and its the base class for all the layouts in Android. ViewGroup extends from View.</p><p>Android layouts:<br>(1) FrameLayout — Used to block out an area on the screen to display one single item. If there is more than one item, they will overlap.<br>(2) LinearLAyout — Organizes its children either vertically or horizontally. We can use here the weight attribute.<br>(3) RelativeLayout — Specify alignment of views to the parents or to other views. It doesn’t fill up the entire screen space.<br>(4) GridLayout — Views fills up cells in a grid and we can also have views that span multiple cells.<br>(5) ConstraintLayout — Allows us to place child views relative to the parent or each other. Uses constraints to specify how each view should be positioned and scaled relative to other views. Enable us to create complicated layouts without nest layouts within each other.</p><p>We can nest ViewGroups and layouts within each other. Nesting too many layouts in one another, may affect the overall performance when rendered.</p><p>View width/height — Could be wrap_content, match_parent, or a number ends with dp.</p><p>Layout_gravity — Could change the place of our views on the screen. Gravity — Change alignment of the text in its container.</p><p>Padding/Margin — Padding uses inner space and margin outer space.</p><p>Visibility — Views can be visible, invisible or gone.</p><p>When we want to give a TextView a fake data text we should always use <em>tools:text</em> attribute instead of <em>android:text</em>. Using tools will show the default text only on our design mode but not in our real app.</p><p>We can add shapes using the shape tag as an xml file in the drawable folder. We can think of it as typical image.</p><p>Vector images like SVG files are the best to use in our app, because they can resize easily to work with any phone size and resolution without affecting the quality of our image. We can add those files to our app by using new vector asset and uses override to use its correct dimensions and enable auto mirroring for right to left layouts. We should add it to the drawable folder and then can change its attributes like its color.</p><p><strong>2. Data Binding</strong><br>Data binding library help us link any UI with actual data without having to call the findViewById for every view item.</p><p>Steps for using data binding:<br>(1) Enable data binding in build.gradle — By adding dataBinding.enabled = true in the Android section<br>(2) Add &lt;layout&gt; as the root tag to our layout xml that represent the UI we want to bind<br>(3) Create a binding instance — By creating an ActivityMainBinding variable type in our main activity. (the name changes according to the layout xml file)<br>(4) Set the content view using DatabindingUtil and passing the layout xml<br>(5) Bind each attribute in the views to the corresponding data — By going through the attributes in the binding object and set their text.</p><p><strong>3. Accessibility</strong><br>Accessibility refers to the design of products, devices, services, or environments for people who experience disabilities.</p><p>Some accessibility features:<br>(1) TalkBack — pre-installed screen reader service provided by Google. It uses spoken feedback to describe the results of actions such as launching an app, and events such as notifications.<br>(2) Explore by touch — system feature that works with TalkBack, allowing you to touch your device’s screen and hear what’s under your finger via spoken feedback.<br>(3) Accessibility settings — let you modify your device’s display and sound options, such as increasing the text size, changing the speed at which text is spoken, and more.</p><p>ContentDescription attribute can be added to views and it describe what any view actually presents, this description text is not displayed anywhere on the screen, but if the user enables accessibility services that provide audible prompts, then when the user navigates to that control, the text is spoken. Ideally, in any app, you would want to describe all ImageViews, ImageButtons and all Checkboxes.</p><p>More accessibility tools:<br>(1) Enable focus based navigation — Help users navigate the app using external hardware like bluetooth keyboard<br>(2) No audio only feedback — Any audio feedback should always have a secondary feedback to support users who are deaf or have trouble hearing</p><p><strong>4. Localization<br></strong>Localization (or Internalization) is the adaptation of a product or service to meet the needs of a particular language, culture or desired population’s “look-and-feel”.</p><p>(1) Translation — Our app should always be easily translated to other languages. To easily do so all translatable strings should be defined in strings.xml. We can also create another versions of strings.xml for other languages. Strings that should not be translated should be added the attribute translated=false.<br>(2) RTL support — To support other RTL languages we can add:<br>(2A) autoMirrored=”true” attribute to vector images<br>(2B) layout_marginStart and layout_marginEnd that correspond to layout_marginLeft and layout_marginRight respectively. For RTL languages — start is mapped to right and end mapped to left instead. The idea behind it is auto mirroring of the text in case we are using a RTL language.</p><p><strong>5. Responsive Design<br></strong>Responsive design is a UI that react to the amount of available space in the screen.</p><p>When we turn our phone to landscape mode our screen configuration changes and we would like to match it to a new layout to fit better on the screen and avoid white spaces.</p><p>Alternate layouts are xml layout file only for landscape mode. To do that, we can create a new folder called <em>layout-land</em> for landscape, and then copy the activity_main and place a copy inside <em>layout-land</em>. This will appear as another new XML file with the label <em>land</em>. We can modify this XML to fit everything in the same screen when it’s in landscape mode.</p><p>Some viewGroups will stay the same in both layouts, so we can move each of them into a separate small layout themselves, and then use android’s &lt;include&gt; tag to combine them in the default and landscape layout, so in case we need to update them we can do it in one location. We have to make sure we didn’t broke any previous constraints.</p><p><strong>REFERENCES:</strong></p><p>You can find much more at the free course Developing Android Apps by Google on the Udacity website over here: (check it out!)</p><p><a href="https://www.udacity.com/course/new-android-fundamentals--ud851">https://www.udacity.com/course/new-android-fundamentals--ud851</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c585330719d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>