目的
AndroidアプリのKotlin言語にて
http通信の時に使われるfuel
ライブラリを利用する時のメモです。
環境
- Android Studio 3.5.3
- Kotlin 1.3
参照サイト
kittinunf/fuel
GitHubでの公式ページ
Qiita Androidで現在のスレッドがUIスレッドか調べる方法
メインスレッドかどうか確認したかったため。
実装メモ
以下に使い方メモを記載します。
build.gradle
Module: app
のbuild.gradle
に、以下を記載しました。
バージョン(今回は2.2.0)はそれぞれのタイミングで変更してください。
dependencies {
//....
//core
implementation 'com.github.kittinunf.fuel:fuel:2.2.0'
//packages
implementation 'com.github.kittinunf.fuel:fuel-android:2.2.0'
//....
}
core
のほかにもpackages
も設定しました。
今回は
fuel-android
を設定しまして、効果としては以下なります。
Android: Automatically invoke handler on Main Thread when using Android Module
AndroidManifest.xml
AndroidManifestでhttp通信の許可設定を行います。
設定しないと、うまく通信できません。
<uses-permission android:name="android.permission.INTERNET" />
xmlレイアウト
レイアウトは以下にしました。ほぼテンプレートです。
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/resulttext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
ktファイル上で利用する
実際の使用例は以下です。GETプロトコルでの通信です。
URLは公式ページのものをそのまま記載しています。
あと、メインスレッドで実行出来ているかどうかのチェックも入れました。
//...
import com.github.kittinunf.fuel.httpGet
import com.github.kittinunf.result.Result
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val httpAsync = "https://httpbin.org/get"
.httpGet()
.responseString { _, _, result ->
when (result) {
is Result.Failure -> {
val ex = result.getException()
println(ex)
}
is Result.Success -> {
val data = result.get()
val isUiThread = Thread.currentThread() == Looper.getMainLooper().thread
println("IS_TREAD: $isUiThread")
val resulttext = findViewById<TextView>(R.id.resulttext)
resulttext.text = data
}
}
}
httpAsync.join()
}
}
実行結果
実行した結果、以下のようにパラメータを受け取れてました。
コンソールにも以下が出力されています。
I/System.out: IS_TREAD: true
ちなみに1
ちなみに上記のbuild.gradle
で設定したpackagesを記載しないで実行してみると、以下になりました。
I/System.out: IS_TREAD: false
ちなみに2
kotlinでのhttp通信ライブラリといえば、以前okhttp3
を使ったメモを掲載しました。
で、okhttp3だと
受け取り時のhandlerをメインスレッドにするには、ひと工夫必要な思いがあります。
I am 初心者 about Android.
なので、今後はfuel
を使っていきたいと思います。