티스토리 뷰

반응형

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

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

 

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

How to get package name from anywhere?

어디서든 패키지 이름을 가져오는 방법은 무엇인가요?

 문제 내용 

I am aware of the availability of Context.getApplicationContext() and View.getContext(), through which I can actually call Context.getPackageName() to retrieve the package name of an application.

Context.getApplicationContext()와 View.getContext()의 가용성을 알고 있습니다. 이를 통해 애플리케이션의 패키지 이름을 검색하려면 Context.getPackageName()을 호출할 수 있습니다.

 

They work if I call from a method to which a View or an Activity object is available, but if I want to find the package name from a totally independent class with no View or Activity, is there a way to do that (directly or indirectly)?

그러나 이들은 View나 Activity 객체를 사용할 수 있는 메서드에서 호출하는 경우에만 작동합니다. 만약 완전히 독립적인 클래스에서 View나 Activity가 없는 경우 패키지 이름을 찾으려면 (직접적으로든 간접적으로든) 방법이 있을까요?

 

 

 

 높은 점수를 받은 Solution 

An idea is to have a static variable in your main activity, instantiated to be the package name. Then just reference that variable.

클래스에서 패키지 이름을 참조하려면, 메인 액티비티에 static 변수를 가지고 있어야 합니다. 그런 다음 그 변수를 참조하기만 하면 됩니다.

 

You will have to initialize it in the main activity's onCreate() method:

메인 액티비티의 onCreate() 메서드에서 이를 초기화해야 합니다.

 

Global to the class:

클래스 전역에 아래와 같이 선언하세요:
public static String PACKAGE_NAME;

 

Then..

그 다음...
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    PACKAGE_NAME = getApplicationContext().getPackageName();
}

 

You can then access it via Main.PACKAGE_NAME.

이제 Main.PACKAGE_NAME을 통해 액세스할 수 있습니다.

 

 

 

 가장 최근 달린 Solution 

Just use this code

그냥 이 코드를 사용하세요.
val packageName = context.packageName 

 

 

출처 : https://stackoverflow.com/questions/6589797/how-to-get-package-name-from-anywhere

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