<?xml version="1.0" encoding="utf-8"?>
<!-- generator="Kirby" -->
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom">

  <channel>
    <title>Tag: kotlin &#183; Blog &#183; Liip</title>
    <link>https://www.liip.ch/de/blog/tags/kotlin</link>
    <generator>Kirby</generator>
    <lastBuildDate>Tue, 09 Oct 2018 00:00:00 +0200</lastBuildDate>
    <atom:link href="https://www.liip.ch" rel="self" type="application/rss+xml" />

        <description>Liip Blog Artikel mit dem Tag &#8220;kotlin&#8221;</description>
    
        <language>de</language>
    
        <item>
      <title>Add syntactic sugar to your Android Preferences</title>
      <link>https://www.liip.ch/de/blog/syntactic-sugar-android-preferences-kotlin</link>
      <guid>https://www.liip.ch/de/blog/syntactic-sugar-android-preferences-kotlin</guid>
      <pubDate>Tue, 09 Oct 2018 00:00:00 +0200</pubDate>
      <description><![CDATA[<h2>TL;DR</h2>
<p>You can find <a href="https://github.com/liip/SweetPreferences">SweetPreferences on Github</a>.</p>
<pre><code class="language-kotlin">// Define a class that will hold the preferences
class UserPreferences(sweetPreferences: SweetPreferences) {
    // Default key is "counter"
    // Default value is "0"
    var counter: Int by sweetPreferences.delegate(0)

    // Key is hardcoded to "usernameKey"
    // Default value is "James"
    var username: String? by sweetPreferences.delegate("James", "usernameKey") 
}

// Obtain a SweetPreferences instance with default SharedPreferences
val sweetPreferences = SweetPreferences.Builder().withDefaultSharedPreferences(context).build()

// Build a UserPreferences instance
val preferences = UserPreferences(sweetPreferences)

// Use the preferences in a type-safe manner
preference.username = "John Doe"
preference.counter = 34</code></pre>
<h2>Kotlin magic</h2>
<p>The most important part of the library is to define properties that run code instead of just holding a value.</p>
<p>From the example above, when you do:</p>
<pre><code class="language-kotlin">val name = preference.username</code></pre>
<p>what really happening is:</p>
<pre><code class="language-kotlin">val name = sweetPreferences.get("username", "James", String::class)</code></pre>
<p>The <em>username</em> property is converted from a property name to a string, the <code>"James"</code> string is taken from the property definition and the <code>String</code> class is automatically inferred. </p>
<p>To write this simple library, we used constructs offered by Kotlin such as <a href="https://kotlinlang.org/docs/reference/inline-functions.html">Inline Functions</a>, <a href="https://kotlinlang.org/docs/reference/inline-functions.html#reified-type-parameters">Reified type parameters</a>, <a href="https://kotlinlang.org/docs/reference/delegated-properties.html">Delegated Properties</a>, <a href="https://kotlinlang.org/docs/reference/extensions.html#extension-functions">Extension Functions</a> and <a href="https://kotlinlang.org/docs/reference/lambdas.html#function-literals-with-receiver">Function literals with receiver</a>. If you are starting with Kotlin, I warmly encourage you to go check those. It's only a small part of what Kotlin has to offer to ease app development, but already allows you to create great APIs. </p>
<p>Next time you need to store preferences in your Android app, give <a href="https://github.com/liip/SweetPreferences">SweetPreferences</a> a try and share what you have built with it. We’d like to know your feedback!</p>]]></description>
                  <enclosure url="http://liip.rokka.io/www_card_2/7d1c08/blogpost-sugar.jpg" length="1447202" type="image/jpeg" />
          </item>
        <item>
      <title>Experimenting With Android Things</title>
      <link>https://www.liip.ch/de/blog/experimenting-android-things</link>
      <guid>https://www.liip.ch/de/blog/experimenting-android-things</guid>
      <pubDate>Fri, 07 Sep 2018 00:00:00 +0200</pubDate>
      <description><![CDATA[<h2>Context</h2>
<p>At Liip we have the great opportunity to experiment in new technologies when working on innovation projects. Within the last two years we developed <a href="https://www.liip.ch/en/blog/houston-replaces-radio-system" rel="noopener noreferrer" target="_blank">Houston: a VOIP communication system for buses</a>. The system includes an Android app which  takes  VOIP calls and collects sensor information like the GPS position. When I heard about the release of Android Things, I thought it’d be interesting to investigate if we could use it to make the app run on IoT devices like the Raspberry PI. Therefore I experimented with the platform for a few days. And I discovered an amazing operating system bringing all the benefits of Android to IoT devices.</p>
<h2>How to start</h2>
<p>The best thing about Android Things is that it is built for Android developers and comes with standard development tools, the ones you are used to. You will develop inside Android Studio. And being able to debug code using adb, like for a normal Android device, is great. Android Things extends the core Android framework with additional APIs provided by the Things Support Library (<a href="https://developer.android.com/things/sdk/index.html" rel="noopener noreferrer" target="_blank">reference</a>,  <a href="https://developer.android.com/things/get-started/platform-differences" rel="noopener noreferrer" target="_blank">platform differences</a>). That means it will be easy to use the Android API to develop a user interface, communicate with a server, etc. It is also possible to use Android libraries like Google Firebase (real time datababe, push notifications, ...) or  Tensorflow (machine learning). </p>
<p>To start developing for Android Things, you need a development board. Google supports different hardware among the well-known <a href="https://www.raspberrypi.org/" rel="noopener noreferrer" target="_blank">Raspberry Pi 3 Model B</a>. In 2017, more boards where supported, such as the Intel Edison, but it seems they stopped supporting them (at least officially, <a href="https://developer.android.com/things/hardware/index.html" rel="noopener noreferrer" target="_blank">list of supported platforms</a>). </p>
<p>If you don’t have a Raspberry Pi 3 already, you can buy a starter kit like this <a href="https://shop.pimoroni.com/products/rainbow-hat-for-android-things" rel="noopener noreferrer" target="_blank">one</a> or this <a href="https://www.adafruit.com/product/3292" rel="noopener noreferrer" target="_blank">one</a>.  You will get a Raspberry Pi 3 with a power supply with the first kit. Furthermore there will be a SD card with the Android Things OS flashed and the Rainbow Hat. The hat is easy to plug on the Raspberry and contains a buffet of sensors (temperature, pressure, etc.), LEDs, alphanumeric display, etc.. To explore the platform, I wanted to be able to do my own electronic schemes. Therefore I bought the Raspberry itself  and this <a href="https://www.adafruit.com/product/3227" rel="noopener noreferrer" target="_blank">kit</a> that contains a breadboard (thin plastic board used to hold electronic components) with cables, resistors, LEDs and few sensors. Something you shouldn’t forget is buying a cable which  allows you to connect the breadboard to the GPIO connector on the Raspberry (like this <a href="https://www.pi-shop.ch/raspberry-pi-40-pin-gpio-socket-connector-to-labelled-pins-female-150mm" rel="noopener noreferrer" target="_blank">one</a>).</p>
<figure><img src="https://liip.rokka.io/www_resize/resize-width-500/18373c/img-3502.jpg" alt="" width="500"></figure>
<p>If you want to use Android Things with a specific sensor or peripheral, be aware that usage  without a driver is impossible. Therefore it is better to look at the list of available drivers first (available <a href="https://github.com/amitshekhariitbhu/awesome-android-things" rel="noopener noreferrer" target="_blank">here</a>, <a href="https://github.com/androidthings/contrib-drivers">here</a> and <a href="https://github.com/androidthings/drivers-samples" rel="noopener noreferrer" target="_blank">here</a>). It is also possible to write a driver yourself. You’ll find a tutorial <a href="https://www.novoda.com/blog/writing-your-first-android-things-driver-p1/" rel="noopener noreferrer" target="_blank">here</a>. Once you have a Raspberry PI, it is easy to get Android Things running on it.  You can follow this <a href="https://developer.android.com/things/hardware/raspberrypi.html" rel="noopener noreferrer" target="_blank">tutorial</a> to flash the OS on a Micro SD card and connect the hardware. </p>
<h2>Prototype 1:  Weather station</h2>
<p>The first prototype I built is a small weather station. The temperature in the office was high and my idea was to measure the temperature of the room. Furthermore I wanted to light up a led if the temperature reaches a given threshold. A next step would be to switch on a fan for example .</p>
<figure><img src="https://liip.rokka.io/www_resize/resize-width-300/3a6bae/img-2383.jpg" alt="the weather station" width="300"><figcaption>the weather station</figcaption></figure>
<p>To build the electronic circuit on the development breadboard, you’ll need a bit of electronic knowledge. This feels like becoming an electronic engineer, which is great!   Reading a tutorial is great as a memory refresher. This <a href="https://riggaroo.co.za/android-things-hardware-basics/" rel="noopener noreferrer" target="_blank">one</a> was very helpful to me. </p>
<p>One import thing to remember is Ohm’s Law <code>U = RI</code> , to know which resistance you have to put between the Raspberry PI and the LED. The resistance needs to respect the intensity of the LED that switches on automatically . It was also not easy to understand how the <a href="https://developer.android.com/things/sdk/pio/index.html" rel="noopener noreferrer" target="_blank">Peripheral I/O</a> interface works at the beginning (where is the ground (-), power (+), functionality of the different pins, etc.). I printed the scheme <a href="https://developer.android.com/things/hardware/raspberrypi-io.html" rel="noopener noreferrer" target="_blank">here</a> to have it next to me at all times.</p>
<p><a href="https://developer.android.com/things/sdk/pio/gpio" rel="noopener noreferrer" target="_blank">General Purpose Input/Output</a> (GPIO) provides a programmable interface to read the state of a binary input device or control the on/off state of a binary output device (such as an LED). The red LED was connected on pin BCM6 and the green LED was connected on pin BMC 5, for example. To get the temperature via the sensor and display it on the alphanumeric display, I used BCM2 and BMC3 (<a href="https://developer.android.com/things/sdk/pio/i2c" rel="noopener noreferrer" target="_blank">inter-integrated circuit bus</a>).</p>
<p>The steps to create the Android Things app are the following:</p>
<ol>
<li>Create a Android project with a blank Activity in Android Studio and add the Android Things library and drivers in <em>build.gradle</em></li>
</ol>
<pre><code class="language-kotlin">provided ‘com.google.android.things:androidthings:&lt;version&gt;'
implementation 'com.google.android.things.contrib:driver-bmx280:&lt;version&gt;'
implementation 'com.google.android.things.contrib:driver-ht16k33:&lt;version&gt;'</code></pre>
<ol start="2">
<li>Add the following line in the <em>AndroidManifest.xml</em> under the <em>application</em> tag</li>
</ol>
<pre><code class="language-kotlin">&lt;uses-library android:name="com.google.android.things"/&gt;</code></pre>
<ol start="3">
<li>In <em>OnCreate</em> of the <em>MainActivity</em>, register the peripherals</li>
</ol>
<pre><code class="language-kotlin">val service = PeripheralManagerService()
mSensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager

//Temperature sensor
try {
    mEnvironmentalSensorDriver = Bmx280SensorDriver("I2C1")
    mSensorManager.registerDynamicSensorCallback(mDynamicSensorCallback)
    mEnvironmentalSensorDriver.registerTemperatureSensor()
    mEnvironmentalSensorDriver.registerPressureSensor()
    Log.d(TAG, "Initialized I2C BMP280")
} catch (e: IOException) {
    throw RuntimeException("Error initializing BMP280", e)
}

//Alphanumeric display
try {
    mDisplay = AlphanumericDisplay("I2C2")
    mDisplay.setEnabled(true)
    mDisplay.clear()
    Log.d(TAG, "Initialized I2C Display")
} catch (e: IOException) {
    Log.e(TAG, "Error initializing display", e)
    Log.d(TAG, "Display disabled")
    mDisplay = null
}

//Green LED
try {
    mGreenLedGpio = service.openGpio("BCM5")
    mGreenLedGpio.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW)

} catch (e: IOException) {
    throw RuntimeException("Problem connecting to IO Port", e)
}

//Red LED
try {
    mRedLedGpio = service.openGpio("BCM6")
    mRedLedGpio.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW)
} catch (e: IOException) {
    throw RuntimeException("Problem connecting to IO Port", e)
}</code></pre>
<ol start="4">
<li>And finally register for sensor events: </li>
</ol>
<pre><code class="language-kotlin">private val mTemperatureListener = object : SensorEventListener {
    override fun onSensorChanged(event: SensorEvent) {

        mTempCount++
        if (mTempCount % 100 !== 0) {
            return
        }

        val temperature = Temperature(System.currentTimeMillis(), event.values[0])
        Log.i(FragmentActivity.TAG, "Temperature: " + temperature.getTemperature())

        mTemperatureTexView.setText(String.valueOf(temperature.getTemperature()))
        updateDisplay(temperature.getTemperature())

        try {
            if (temperature.getTemperature() &gt;= TEMPERATURE_THRESHOLD) {
                mRedLedGpio.setValue(true)
                mGreenLedGpio.setValue(false)
            } else {
                mRedLedGpio.setValue(false)
                mGreenLedGpio.setValue(true)
            }
        } catch (e: IOException) {
            Log.e(TAG, "Error", e)
        }
    }

    override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) {
        Log.d(TAG, "accuracy changed: $accuracy")
    }
}

private fun updateDisplay(value: Float) {
    if (mDisplay != null) {
        try {
            mDisplay.display(value)
        } catch (e: IOException) {
            Log.e(TAG, "Error setting display", e)
        }
    }
}</code></pre>
<p>In the <em>onSensorChanged</em> callback for the temperature sensor, we filter events (otherwise we receive too many temperature changes) and display the value on the display with <em>updateDisplay()</em> . Once the value reached a certain threshold (<em>TEMPERATURE_THRESHOLD</em>), we switch the red or the green LED with <em>setValue(true)/setValue(false)</em>.</p>
<p>And that’s pretty much it. Thanks to the Android framework and the implemented drivers it is very simple to communicate with the Raspberry PI using simple interfaces and without the need for low level programming.</p>
<h2>Prototype 2: GPS tracker</h2>
<p>In the next prototype, I wanted to test Android Things with a GPS antenna. If we come back to the Houston project, the idea would be to have an embedded device that is able to track the positions of the buses. </p>
<figure><img src="https://liip.rokka.io/www_resize/resize-width-400/fc265c/img-3555.jpg" alt="the Raspberry PI with the Grove GPS" width="400"><figcaption>the Raspberry PI with the Grove GPS</figcaption></figure>
<p>It was laborious to find out which GPS sensor to buy. There are many models so I decided to use the <a href="http://wiki.seeedstudio.com/Grove-GPS/" rel="noopener noreferrer" target="_blank">Grove GPS</a> with <a href="https://www.dexterindustries.com/grovepi-starter-kit/" rel="noopener noreferrer" target="_blank">GrovePi+</a>. GrovePi+ offers a plug-and-play module for the Raspberry PI. You can connect Grove sensors without cables and breadboards. </p>
<p>It is possible to use the Grove Pi+ with Android Things, but I am not sure if it will work with all Grove sensors. I guess it depends on the connection interface you have (I2C, UART, …) and if there is a driver available for it. In my case, I needed a UART connection and it was enough to connect the Grove GPS to the RPISER port of the GrovePi+.</p>
<p>To create the Android Things app, the steps are the following:</p>
<ol>
<li>Create a Android project with a blank Activity in Android Studio and add the Android Things library and drivers in <em>build.gradle</em></li>
</ol>
<pre><code class="language-kotlin">provided ‘com.google.android.things:androidthings:&lt;version&gt;'
implementation 'com.google.android.things.contrib:driver-gps:&lt;version&gt;'</code></pre>
<ol start="2">
<li>Add the following line in the <em>AndroidManifest.xml</em> under the <em>application</em> tag</li>
</ol>
<pre><code class="language-kotlin">&lt;uses-library android:name="com.google.android.things"/&gt;</code></pre>
<ol start="3">
<li>In <em>onCreate</em> of the <em>MainActivity</em>, register the GPS sensor</li>
</ol>
<pre><code class="language-kotlin">// Callback when SensorManager delivers temperature data.
val I2C_BUS = "I2C1"
val UART_BUS = "UART0"
val UART_BAUD = 9600
val ACCURACY = 2.5f // From GPS datasheet

...

mLocationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager

// We need permission to get location updates
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
    // A problem occurred auto-granting the permission
    Log.e(TAG, "No ACCESS_FINE_LOCATION permission")
    return
}

try {
    // Register the GPS driver
    mGpsDriver = NmeaGpsDriver(this, UART_BUS, UART_BAUD, ACCURACY)
    mGpsDriver.register()

} catch (e: Exception) {
    Log.e(TAG, "Unable to open GPS UART", e)
}</code></pre>
<ol start="4">
<li>Then, register the listener to receive location updates, just like for a standard Android code base.</li>
</ol>
<pre><code class="language-kotlin"> ...

// Register for location updates
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2, 0, mLocationListener)

...

val mLocationListener = object : LocationListener {
    override fun onLocationChanged(location: Location) {
        Log.v(TAG, "Location update: $location")
    }

    override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {}
    override fun onProviderEnabled(provider: String) {}
    override fun onProviderDisabled(provider: String) {}
}</code></pre>
<p>When you are running the app, you will see the current locations displayed in logcat. We can imagine to collect the locations in a Firebase Firestore database or display them on a map. We have seen, that it is very simple to build an Android Things prototype. As long as you have a bit of Android development experience and the correct driver and hardware setup, you’ll be okay.</p>
<h2>Next steps</h2>
<p>The goal of this innovation project was to experiment with the Android Things platform and discover if we could use it in our projects. It was great fun to build the electronic circuits and interact with the hardware via the Android framework. The setup is simple and the framework allows us to easily build a lot of amazing apps for IoT devices. You’ll find a lot of interesting use cases on the Web such as <a href="https://github.com/kevalpatel2106/smartswitch" rel="noopener noreferrer" target="_blank">controlling you home switches remotely</a>. Or even funnier examples like  <a href="https://androidthings.rocks/how-to-build-a-high-five-machine-with-android-things-and-firebase/" rel="noopener noreferrer" target="_blank">building an high five machine</a>.  Google insists on their website that the platform is not meant just for quick prototyping, but also for real products. Android Things is definitely a platform that was worth a try.  The next step is to start integrating some of the Android code bases we have developed for Houston or other projects. We have a lot of ideas already!</p>]]></description>
                  <enclosure url="http://liip.rokka.io/www_card_2/eaddd3/1525778000-android-things.jpg" length="168478" type="image/jpeg" />
          </item>
        <item>
      <title>Meet Kotlin &#8212; or why I will never go back to Java!</title>
      <link>https://www.liip.ch/de/blog/kotlin-why-i-will-never-go-back-to-java</link>
      <guid>https://www.liip.ch/de/blog/kotlin-why-i-will-never-go-back-to-java</guid>
      <pubDate>Fri, 09 Mar 2018 00:00:00 +0100</pubDate>
      <description><![CDATA[<p>When Google and JetBrains <a href="https://blog.jetbrains.com/kotlin/2017/05/kotlin-on-android-now-official/">announced</a> first-class support for Kotlin on Android last year, I could not wait to use it on our next project. Java is an OK language, but when you are used to Swift on iOS and C# on Xamarin, it's sometimes hard to go back to the limited Java that Android has to offer.</p>
<p>Within this past year, we successfully shipped two applications using Kotlin exclusively, with another one to follow soon. We decided to also use Kotlin for previous Java apps that we keep updating.</p>
<p>I took my chance when the <a href="https://www.meetup.com/Mobile-Romandie-Beer">Mobile Romandie Beer</a> meetup was looking for speakers. I knew that I had to show others how easy and fun this language is. </p>
<p>It turned out great. We had people from various backgrounds: from people just curious about it, UX/UI designers, iOS developers, Java developers to people using Kotlin in production already.</p>
<p>You can find my slides below:</p>
<script async class="speakerdeck-embed" data-id="1504188547254400bb81fd9f30f2e701" data-ratio="1.77777777777778" src="//speakerdeck.com/assets/embed.js"></script>
<p>I would like to share a few links that helped me learn about Kotlin:</p>
<ul>
<li><a href="https://try.kotlinlang.org">Kotlin Koans</a>: a step by step tutorial that directly executes your code in the browser</li>
<li><a href="https://developer.android.com/kotlin/">Kotlin and Android</a>: the official Android page to get started with Kotlin on Android</li>
<li><a href="https://github.com/android/android-ktx">Android KTX</a>: a useful library to help with Android development, released by Google</li>
</ul>
<p>See you at the <a href="https://www.meetup.com/Mobile-Romandie-Beer/events/246118655/">next meetup</a>!</p>]]></description>
                  <enclosure url="http://liip.rokka.io/www_card_2/cb1695/meetup.jpg" length="366348" type="image/jpeg" />
          </item>
    
  </channel>
</rss>
