Android Application
Kotlin 스레드(Thread) : 음악 듣기와 SeekBar를 이용한 Thread
작성자 임베디드코리아
작성일 23-10-23 23:29
조회1,691회
댓글0건
Kotlin 스레드(Thread) : 음악 듣기와 SeekBar를 이용한 Thread
-------------------------------------------------------------------------------------
activity_main.xml
-------------------------------------------------------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Switch
android:id="@+id/switch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:text="음악듣기" />
<SeekBar
android:id="@+id/pbMP3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"/>
</LinearLayout>
------------------------------------------------------------------------------------
MainActivity.kt
------------------------------------------------------------------------------------
class MainActivity : AppCompatActivity() {
lateinit var mPlayer: MediaPlayer
lateinit var pbMP3: SeekBar
lateinit var switch1: Switch
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
pbMP3 = findViewById<SeekBar>(R.id.pbMP3)
switch1 = findViewById<Switch>(R.id.switch1)
switch1.setOnClickListener {
if (switch1.isChecked == true) {
mPlayer = MediaPlayer.create(applicationContext, R.raw.song1)
mPlayer.start()
makeThread()
} else {
mPlayer.stop()
}
}
pbMP3.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onStopTrackingTouch(seekBar: SeekBar) {}
override fun onStartTrackingTouch(seekBar: SeekBar) {}
override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
if (fromUser) {
mPlayer.seekTo(progress)
}
}
})
}
fun makeThread() {
object : Thread() {
override fun run() {
// ۵ ̶
while (mPlayer.isPlaying) {
pbMP3.max = mPlayer.duration // ð ִ
pbMP3.progress = mPlayer.currentPosition // ġ
SystemClock.sleep(100)
}
pbMP3.progress = 0
}
}.start()
}
}
------------------------------------------------------------------------------------
themes.xml
------------------------------------------------------------------------------------
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Base.Theme.ThreadMusicSeekBar" parent="Theme.AppCompat.Light">
<item name="colorPrimary">#FFC107</item>
<item name="colorPrimaryDark">#E91E63</item>
</style>
<style name="Theme.ThreadMusicSeekBar" parent="Base.Theme.ThreadMusicSeekBar" />
</resources>
158-840 서울시 양천구 남부순환로 571(신월동, 영남타운 307호) l 대표: 박길성 ㅣ Tel:02-2695-1114 ㅣ Fax:02-2695-1113
Copyright © 2015 Embedded Korea. All Rights Reserved.