티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
Calling startActivity() from outside of an Activity context
액티비티 외부에서 startActivity() 호출하기
문제 내용
I have implemented a ListView
in my Android application. I bind to this ListView
using a custom subclass of the ArrayAdapter
class. Inside the overridden ArrayAdapter.getView(...)
method, I assign an OnClickListener
. In the onClick
method of the OnClickListener
, I want to launch a new activity. I get the exception:
나는 내 안드로이드 애플리케이션에 ListView를 구현했다. ArrayAdapter 클래스의 사용자 지정 하위 클래스를 사용하여 이 ListView에 바인딩합니다. 재정의된 ArrayAdapter.getView(...) 메서드 내에서 OnClickListener를 할당합니다. OnClickListener의 onClick 메서드에서 새 액티비티를 시작합니다. 그리고 저는 exception을 만났습니다:
Calling startActivity() from outside of an Activity context requires the
FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
How can I get the Context
that the ListView
(the current Activity
) is working under?
ListView(현재 액티비티)가 작업 중인 컨텍스트를 가져오려면 어떻게 해야 합니까?
높은 점수를 받은 Solution
Either
어느 하나
- cache the Context object via constructor in your adapter, or
- get it from your view.
어댑터의 생성자를 통해 컨텍스트 개체를 캐시하거나
당신의 View에서 그것을 얻으세요.
Or as a last resort,
아니면 최후의 수단으로
- add - FLAG_ACTIVITY_NEW_TASK flag to your intent:
인텐트에 FLAG_ACTIVE_NEW_TASK 플래그를 추가합니다.
myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Edit - i would avoid setting flags as it will interfere with normal flow of event and history stack.
편집 - 이벤트 및 기록 스택의 일반적인 흐름을 방해하므로 플래그를 설정하지 않습니다.
가장 최근 달린 Solution
At the Android 28(Android P)
startActivity
Android 28(Android P) startActivity
if ((intent.getFlags() & Intent.FLAG_ACTIVITY_NEW_TASK) == 0
&& (targetSdkVersion < Build.VERSION_CODES.N
|| targetSdkVersion >= Build.VERSION_CODES.P)
&& (options == null
|| ActivityOptions.fromBundle(options).getLaunchTaskId() == -1)) {
throw new AndroidRuntimeException(
"Calling startActivity() from outside of an Activity "
+ " context requires the FLAG_ACTIVITY_NEW_TASK flag."
+ " Is this really what you want?");
}
So the best way is add FLAG_ACTIVITY_NEW_TASK
따라서 가장 좋은 방법은 FLAG_ACTIVE_NEW_TASK를 추가하는 것입니다.
Intent intent = new Intent(context, XXXActivity.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
context.startActivity(intent);
출처 : https://stackoverflow.com/questions/3918517/calling-startactivity-from-outside-of-an-activity-context
'개발 > 안드로이드' 카테고리의 다른 글
부팅 시 서비스를 시작하기 (0) | 2022.12.02 |
---|---|
이미지에 대해 확대/축소 기능 구현하기 (0) | 2022.12.02 |
그리드 레이아웃에서 Fling 제스처 감지하기 (0) | 2022.12.02 |
URL을 클릭시 기본 브라우저 실행 문제 (0) | 2022.12.02 |
어디에서나 어플리케이션 컨텍스트 사용하기 (0) | 2022.12.02 |