728x90
Service에서 Activity의 UI 업데이트하기
BroadcastRecevier 활용
- Service에서 UI 업데이트를 위한 브로드캐스팅 메시지를 송신한다.
- Activity에서 BroadcastReceiver를 등록 후 브로드캐스팅 메시지를 분기 처리하여 UI를 업데이트한다.
activity_main.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"
>
<TextView
android:id="@+id/tv"
android:text="0"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</androidx.constraintlayout.widget.ConstraintLayout>
MyService.kt
package org.techtown.test
import android.app.Service
import android.content.Intent
import android.os.IBinder
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.core.ObservableEmitter
import io.reactivex.rxjava3.core.Observer
class MyService : Service() {
override fun onBind(p0: Intent?): IBinder? {
return null
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
var thread = Thread(Runnable {
for(i in 0..100)
{
var intent = Intent()
intent.setAction("test")
intent.putExtra("value", i)
sendBroadcast(intent)
Thread.sleep(50)
}
}).start()
return super.onStartCommand(intent, flags, startId)
}
}
MainActivity.kt
package org.techtown.test
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var br = MyBR()
var filter = IntentFilter()
//수신할 action 종류 넣기
filter.addAction("test")
//브로드캐스트리시버 등록
registerReceiver(br, filter)
//서비스 시작
var intent = Intent(this, MyService::class.java)
startService(intent)
}
inner class MyBR : BroadcastReceiver()
{
override fun onReceive(context: Context?, intent: Intent?) {
if(intent?.action == "test")
tv.setText(intent?.getIntExtra("value", 0).toString()?:"")
}
}
}
결과
728x90
'Android' 카테고리의 다른 글
[안드로이드] Handler와 Looper (0) | 2020.11.04 |
---|---|
[안드로이드] Bundle (0) | 2020.10.22 |
[안드로이드] BroadcastReceiver (0) | 2020.10.21 |
[안드로이드] Context (0) | 2020.10.21 |
[안드로이드] 안드로이드 앱 성능 개선 (feat. 네이버 테크 콘서트) (0) | 2020.10.19 |
댓글