ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Android Background Service 예제
    안드로이드 학습/Android 기술면접 대비 코드 2023. 12. 22. 17:44

    안드로이드 Background Service를 공부하다가 놀란 부분이 있었다.

     

    다른 블로그들을 찾아봤었을때는 분명이 앱이 종료되도 작업이 계속 수행된다고 적혀있었는데 

     

    새로 찾아보니 앱이 API 레벨 26 이상을 대상으로 전용 앱이 포그라운드에 있지 않을 때 시스템에서 백그라운드 서비스 실행에 대한 서비스 실행에 대한 제한을 적용한다고 합니다.

     

    앞으로는 앱에 실행과 무관하게 실행되는 것은 무조건 Foreground를 쓰던가 아니면 예약해서 코드를 실행시키려면 알림매니저나 워크 매니저를 사용해야 하는 것 같다.

     

    그러면 Background Service는 이제 왜 사용하는지 잘 모르겠지만 그래도 알아보자!

     

    아래 예제는 링크에 있는 블로그 예제를 따라 했습니다.

     

    AndroidManifest.xml

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <service
        android:name=".BackgroundService"
        android:enabled="true"
        android:exported="true"
        android:process=":ServiceProcess"/>

     

    url을 이용해 mp3 파일을 불러오기 때문에 internet permisson 추가. 

     

    그리고 Service 등록

     

     

    MainActivity.kt

    class MainActivity : AppCompatActivity() {
    
        private var startBtn: Button? = null
        private var stopBtn: Button? = null
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
            startBtn = findViewById(R.id.idBtnStartService)
            stopBtn = findViewById(R.id.idBtnStopService)
    
            startBtn?.setOnClickListener {
                startService(Intent(this@MainActivity, BackgroundService::class.java))
                Toast.makeText(this@MainActivity, "Audio started playing..", Toast.LENGTH_SHORT).show()
            }
    
            stopBtn?.setOnClickListener {
                stopService(Intent(this@MainActivity, BackgroundService::class.java))
                Toast.makeText(this@MainActivity, "Audio stopped playing..", Toast.LENGTH_SHORT).show()
            }
    
        }
    }

     

    MainActivity.kt 에서 Intent 추가후 startService() 로 전송

     

     

    BackgroundService.kt

    class BackgroundService : Service() {
    
        private var mediaPlayer: MediaPlayer? = null
    
        override fun onCreate() {
            super.onCreate()
            Log.d("BackgroudnService", "onCreate")
        }
    
        override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
            val mediaUrl = "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3"
            mediaPlayer = MediaPlayer()
            mediaPlayer!!.setAudioAttributes(
                AudioAttributes.Builder()
                    .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                    .build()
            )
            try {
                mediaPlayer!!.setDataSource(mediaUrl)
                mediaPlayer!!.prepare()
                mediaPlayer!!.start()
            } catch (e: IOException) {
                e.printStackTrace()
            }
            Toast.makeText(this, "Audio started playing..", Toast.LENGTH_SHORT).show()
            return START_STICKY
        }
    
        override fun onDestroy() {
            super.onDestroy()
            Log.d("BackgroudnService", "onDestroy")
            mediaPlayer!!.stop()
        }
    
        @Nullable
        override fun onBind(intent: Intent?): IBinder? {
            return null
        }
    }
    

     

    MainActivity.kt에서 Intent가 보내지면 onStartCommand 가 실행되고 안에 audio player가 mp3 파일 실행시킴

     

    activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    
        <!--text view for adding a simple heading-->
        <TextView
            android:id="@+id/idTVHeading"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="100dp"
            android:gravity="center"
            android:text="Services in Android"
            android:textAlignment="center"
            android:textColor="@color/black"
            android:textSize="20sp" />
    
        <!--linear layout for aligning the buttons horizontally-->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/idTVHeading"
            android:layout_marginStart="10dp"
            android:layout_marginTop="100dp"
            android:layout_marginEnd="10dp"
            android:orientation="horizontal"
            android:weightSum="2">
    
            <!--button for starting our service-->
            <Button
                android:id="@+id/idBtnStartService"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_margin="8dp"
                android:layout_weight="1"
                android:text="Start Service"
                android:textAllCaps="false" />
    
            <!--button for stopping our service-->
            <Button
                android:id="@+id/idBtnStopService"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_margin="8dp"
                android:layout_weight="1"
                android:text="Stop Service"
                android:textAllCaps="false" />
        </LinearLayout>
    </RelativeLayout>

     

     

    앱이 종료되면 활성화된 Background Service도 종료 된다. 

    앱이 Background에 가면 바로 종료되진 않고 조금의 시간이 지나서 종료 된다.

    '안드로이드 학습 > Android 기술면접 대비 코드' 카테고리의 다른 글

    안드로이드 Rxjava 사용하기 (1)  (0) 2024.03.06
    Anr 예제  (0) 2024.01.23
    Android Foreground Service 예제  (0) 2023.12.22
    MVC 패턴 예제  (0) 2023.12.14
    안드로이드 Bound Service 예제  (0) 2023.07.03
Designed by Tistory.