티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

Get Context in a Service

서비스에서 컨텍스트 가져오기

 문제 내용 

Is there any reliable way to get a Context from a Service?

서비스에서 컨텍스트를 가져올 수 있는 신뢰할 수 있는 방법이 있습니까?

 

I want to register a broadcast receiver for ACTION_PHONE_STATE_CHANGED but I don't need my app to always get this information, so I don't put it in the Manifest.

ACTION_PHONE_STATE_CHANGED에 브로드캐스트 리시버를 등록하고 싶지만 항상 이 정보를 얻기 위해 앱이 필요하지 않기 때문에 매니페스트에 넣지 않습니다.

 

However, I can't have the broadcast receiver be killed by the GC when I need this information so I'm registering the broadcast receiver in a Service.

하지만, 이 정보가 필요할 때 브로드캐스트 리시버를 GC에 의해 죽이게 할 수 없어서 그 리시버를 서비스에 등록합니다.

 

Hence, I need a Context to to call registerReceiver(). When I no longer need the ACTION_PHONE_STATE_CHANGED I unregister it.

따라서 registerReceiver()를 호출하려면 컨텍스트가 필요합니다. 더 이상 ACTION_PHONE_STATE_CHANGED가 필요하지 않으면 등록을 취소합니다.

 

Any tips?

팁이 있나요?

 

 

 

 높은 점수를 받은 Solution 

Service is a Context

서비스는 컨텍스트입니다.

 

 

 

 가장 최근 달린 Solution 

just in case someone is getting NullPointerException, you need to get the context inside onCreate().

누군가 NullPointer를 받을 경우를 대비하여 예외적으로 onCreate()에서 컨텍스트를 가져와야 합니다.

 

Service is a Context, so do this:

서비스는 컨텍스트이므로 다음을 수행합니다.
private Context context;

@Override
public void onCreate() {
    super.onCreate();
    context = this;
}

 

Note:

참고:

 

Read: "Do not place Android context classes in static fields; this is a memory leak (and also breaks Instant Run)" Do you know what context classes are? Activity is one of them, and you should not store Activity as a static field, (or it will leak memory). However, you can store Context (as long as it is the application context) as a static field, since it outlives everything.

읽기: "안드로이드 컨텍스트 클래스를 정적 필드에 배치하지 마십시오. 이는 메모리 누수입니다(그리고 인스턴트 실행도 중단됩니다)." 컨텍스트 클래스가 무엇인지 알고 있습니까? 액티비티는 그 중 하나이며, 액티비티를 정적 필드로 저장해서는 안 됩니다. 그렇지 않으면 메모리가 누수됩니다. 그러나 컨텍스트(응용프로그램 컨텍스트인 경우)는 모든 것보다 오래되기 때문에 정적 필드로 저장할 수 있습니다.

 

 

 

출처 : https://stackoverflow.com/questions/6446221/get-context-in-a-service

반응형
댓글
공지사항
최근에 올라온 글