Android
Kotlin
RaspberryPi
IoT
AndroidThings

Android Thingsの起動時にSlackへ自身のIPアドレスを送る

昔作った Raspberry PiのIPアドレスを起動時に送るスクリプトAndroid Things版です。
http://qiita.com/narikei/items/4b1cfff650676a1c7d66

1. Android Thingsがオンラインかどうか確認する

fun isOnline(): Boolean {
    val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    val activeNetworkInfo = connectivityManager.activeNetworkInfo

    if (activeNetworkInfo == null) {
        return false
    }

    return activeNetworkInfo.isConnected
}

2. 自身のIPアドレスを取得する

fun getIpAddress(): String {
    var text = ""

    try {
        val interfaces = NetworkInterface.getNetworkInterfaces()
        while (interfaces.hasMoreElements()) {
            val network = interfaces.nextElement()
            val addresses = network.inetAddresses

            while (addresses.hasMoreElements()) {
                val address = addresses.nextElement()
                text += address.toString() + System.lineSeparator()
            }
        }
    } catch (e: SocketException) {
        e.printStackTrace()
    }

    return text
}

3. GradleでFuelを入れる

app/build.gradle
dependencies {
    compile 'com.github.kittinunf.fuel:fuel:1.8.0'
}

4. SlackへIPアドレスを送る

var webhookUrl: String = "https://hooks.slack.com/services/xxxxx/xxxxx/xxxxx"

fun sendToSlack(context: Context, text: String) {
    var body = "{ \"text\" : \"$text\" }"

    Fuel.post(webhookUrl).body(body).responseString { _, _, result ->
        result.fold({ _ ->
        }, { _ ->
            Toast.makeText(context, "error: sendToSlack", Toast.LENGTH_SHORT).show()
        })
    }
}

5. おわり

Slackで表示されればOK!便利!
image.png

全部まとめるとこんな感じ

実際に使うときは起動時に欲しいので MainActivity.konResume とかで読み込ませる

MainActivity.k
import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.widget.TextView
import java.net.NetworkInterface
import java.net.SocketException
import android.net.ConnectivityManager
import android.widget.Toast
import com.github.kittinunf.fuel.Fuel


class MainActivity : Activity() {

    var webhookUrl: String = "https://hooks.slack.com/services/xxxxx/xxxxx/xxxxx"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    override fun onResume() {
        super.onResume()

        val context = this.applicationContext
        val textView = findViewById<TextView>(R.id.ipAddressText)

        if (!isOnline(context)) {
            textView.text = "Android Things is Offline"
            return
        }

        val text = getIpAddress()
        textView.text = text

        sendToSlack(context, text)
    }

    private fun isOnline(context: Context): Boolean {
        val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val activeNetworkInfo = connectivityManager.activeNetworkInfo

        if (activeNetworkInfo == null) {
            return false
        }

        return activeNetworkInfo.isConnected
    }

    private fun getIpAddress(): String {
        var text = ""

        try {
            val interfaces = NetworkInterface.getNetworkInterfaces()
            while (interfaces.hasMoreElements()) {
                val network = interfaces.nextElement()
                val addresses = network.inetAddresses

                while (addresses.hasMoreElements()) {
                    val address = addresses.nextElement()
                    text += address.toString() + System.lineSeparator()
                }
            }
        } catch (e: SocketException) {
            e.printStackTrace()
        }

        return text
    }

    private fun sendToSlack(context: Context, text: String) {
        val body = "{ \"text\" : \"$text\" }"

        Fuel.post(webhookUrl).body(body).responseString { _, _, result ->
            result.fold({ _ ->
            }, { _ ->
                Toast.makeText(context, "error: sendToSlack", Toast.LENGTH_SHORT).show()
            })
        }
    }
}