728x90
반응형
Service를 통한 Activity 전환
안드로이드 공부를 하면서 Activity 간 전환을 하거나, Activity에서 Service를 호출 하는 방법은 많이 본 것 같은데 Service를 통해서 Activity 전환을 할 때마다 검색을 한 것 같아서 내가 정리해서 작성한다.
전체 흐름 요약
1. 첫 번째 Activity에서 서비스 시작
2. 서비스 내부에서 두 번째 Activity 실행(Intent + FLAG)
예제 코드
1. 첫 번째 Activity(MainActivity)
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// 버튼 등으로 서비스 시작
val intent = Intent(this, MyService::class.java)
startService(intent)
}
}
2. 서비스 (MyService)
서비스에서 Activity를 띄우려면 새 task로 실행해야 하므로 Intent.FLAG_ACTIVITY_NEW_TASK 플래그를 추가해야 한다.
class MyService : Service() {
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
// 예: 3초 후 액티비티 실행
Handler(Looper.getMainLooper()).postDelayed({
val activityIntent = Intent(this, SecondActivity::class.java)
activityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(activityIntent)
}, 3000)
return START_NOT_STICKY
}
override fun onBind(intent: Intent?): IBinder? {
return null
}
}
3. 두 번째 Activity (SecondActivity)
class SecondActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_second)
}
}
중요사항
- startActivity()를 서비스에서 직접 사용할 때는 Intent.FLAG_ACTIVITY_NEW_TASK를 꼭 추가해야 한다.
- 서비스에서 UI를 띄우는 건 사용자 경험상 자연스럽지 않을 수 있으니 알림 클릭 시 전환하는 방식이 더 권장된다.
- Android 10(API 29)+ 이상에서는 백그라운드에서 바로 Activity 띄우는 것이 제한 될 수 있다. -> 이럴 땐 포그라운드 서비스나 알림클릭방식으로 우회해야 한다
728x90
반응형
'개발 > Android' 카테고리의 다른 글
| [Android] LayoutParams 정리 (0) | 2025.05.26 |
|---|---|
| [Android] Preference 정리 (0) | 2025.05.12 |
| [Android] Annotaion 개념 정리 및 예제 (0) | 2025.05.07 |
| [Android] Room 개념 정리 및 예제 (1) | 2025.04.23 |
| [Android] RecyclerView ? (0) | 2025.04.11 |