[Android Error] Calling startActivity() from outside of an Activity 에러 발생시
Android

[Android Error] Calling startActivity() from outside of an Activity 에러 발생시

반응형

들어가기


android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

startActivity를 사용할 때 위와같은 에러를 마주한다면

 

비 액티비티에서 startActivity를 호출할 때 위 에러 로그를 발견할 수 있다.

 

 

 

해결


Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag

 

비 액티비티 컨텍스트(나는 viewModel에서 startActivity를 호출하니 발생했다) 

 

찾아보니 StackOverflow에

 

FLAG_ACTIVITY_NEW_TASK requirement is now enforced
With Android 9, you cannot start an activity from a non-activity context unless you pass the intent flag FLAG_ACTIVITY_NEW_TASK. If you attempt to start an activity without passing this flag, the activity does not start, and the system prints a message to the log.
Note: The flag requirement has always been the intended behavior, and was enforced on versions lower than Android 7.0 (API level 24). A bug in Android 7.0 prevented the flag requirement from being enforced.

 

즉, Activity나 fragment가 아닌 비 액티비티 컨텍스트에서 startActivity를 사용하기 위해서는

intent flag에

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

처리를 해주어야 한다.

 

안드로이드 DOCS에도

 

FLAG_ACTIVITY_NEW_TASK 요구사항이 이제 적용됨
Android 9에서는 인텐트 플래그 FLAG_ACTIVITY_NEW_TASK를 전달하지 않을 경우 비 액티비티 컨텍스트에서 액티비티를 시작할 수 없습니다. 이 플래그를 전달하지 않고 액티비티를 시작하려고 하면 액티비티가 시작되지 않고, 시스템이 로그에 메시지를 출력합니다.
참고: 플래그 요구사항은 언제나 의도된 동작이며, Android 7.0(API 레벨 24) 이전 버전부터 적용되었습니다. Android 7.0의 버그로 인해 플래그 요구사항이 적용되지 않았습니다.

 

라고 나와있다.

 

그래서 

 

Intent intent = ExampleActivity.newIntent(App.instance);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
App.instance.startActivity(intent);

라고 하면 해결.

 

 

 

 

참조


https://stackoverflow.com/questions/3689581/calling-startactivity-from-outside-of-an-activity

 

Calling startActivity() from outside of an Activity?

I'm using an AlarmManager to trigger an intent that broadcasts a signal. The following is my code: AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE); Intent i = new Intent(...

stackoverflow.com

반응형