startActivity

오븐·2024년 10월 22일

안드로이드

목록 보기
2/9

Service에서 특정 액티비티로 이동해보자!

우선 엄청 간단한 액티비티를 하나 만들어준다.

class AlarmActivity: ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            AlarmManagerGuideTheme {
                exampleScreen()
            }
        }
    }
    
    @Composable
    fun exampleScreen(){
        Column (modifier = Modifier.fillMaxSize(),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center
        ) {
            Text(text = "Welcome to Alarm page!")
        }
    }
}

이제 이걸 manifest에 등록해준다.

        <activity
            android:name=".MainActivity"
            android:exported="true"
            android:label="@string/app_name"
            android:theme="@style/Theme.AlarmManagerGuide">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".AlarmActivity"
            android:exported="true"
            android:label="@string/app_name"
            android:theme="@style/Theme.AlarmManagerGuide">
        </activity>

launcher activity가 아니니 MainActivity에서 category를 지우고, 당장은 특정 action을 수행하지 않을 거라 action도 지워준다. 단, 다른 애플리케이션에서 접근할 수 있도록 exported는 꼭 true로 해준다!

이제 만든 service에 해당 코드를 추가해준다.

        val activityIntent = Intent(this, AlarmActivity::class.java)
        activityIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        startActivity(activityIntent)

기존 스택에서 새로운 작업을 추가하는 것이므로 FLAG_ACTIVITY_NEW_TASK를 설정해준다.
안드로이드 10 (API level 29) 이상부터 startActivity에는 제한이 있는데, 액티비티 이전에 다른 스크린이 있거나 최근에 finish()를 호출한 액티비티가 있거나 등등이다.
이 외의 다른 조건은 https://developer.android.com/guide/components/activities/background-starts 여길 참고하자.

앱을 완전히 종료했을 때의 경우를 생각해봐야겠지만, 지금 당장은 목표를 완료했다!

profile
하루에 한번 정권 찌르기

0개의 댓글