Android-애플리케이션 이름을 얻는 방법? (패키지 이름 아님) android:icon=”@drawable/ic_launcher_icon” android:label=”@string/app_name”

내 매니페스트에는 다음이 있습니다.

  <application
    android:name=".MyApp"
    android:icon="@drawable/ic_launcher_icon"
    android:label="@string/app_name"
    android:debuggable="true">

라벨 요소는 어떻게 얻나요?

참고 : 내 코드가 다른 사람의 내부에서 실행 중이므로 @ string / app_name에 액세스 할 수 없습니다.



답변

리소스의 이름을 명시 적으로 지정하거나 패키지 이름이있는 예외에 대해 걱정할 필요가없는 다른 답변보다 쉬운 방법이 있습니다. 리소스 대신 문자열을 직접 사용한 경우에도 작동합니다.

그냥 해:

public static String getApplicationName(Context context) {
    ApplicationInfo applicationInfo = context.getApplicationInfo();
    int stringId = applicationInfo.labelRes;
    return stringId == 0 ? applicationInfo.nonLocalizedLabel.toString() : context.getString(stringId);
}

도움이 되었기를 바랍니다.

편집하다

Snicolas의 의견에 비추어 위의 내용을 수정하여 ID가 ​​0 인 경우 확인을 시도하지 않습니다. 대신 nonLocalizedLabel백오 프로 사용합니다. try / catch로 래핑 할 필요가 없습니다.


답변

android : label = “MyApp”과 같은 이유로 AndroidManifest.xml의 strings.xml / hardcoded에 언급되지 않은 경우

public String getAppLable(Context context) {
    PackageManager packageManager = context.getPackageManager();
    ApplicationInfo applicationInfo = null;
    try {
        applicationInfo = packageManager.getApplicationInfo(context.getApplicationInfo().packageName, 0);
    } catch (final NameNotFoundException e) {
    }
    return (String) (applicationInfo != null ? packageManager.getApplicationLabel(applicationInfo) : "Unknown");
}

또는 문자열 리소스 ID를 알고있는 경우 다음을 통해 직접 가져올 수 있습니다.

getString(R.string.appNameID);

답변

public static String getApplicationName(Context context) {
    return context.getApplicationInfo().loadLabel(context.getPackageManager());
}

답변

모든 컨텍스트 사용에서 :

getApplicationInfo().loadLabel(getPackageManager()).toString();

답변

패키지 이름을 알고 있다면 다음 스 니펫을 사용하십시오.

ApplicationInfo ai;
try {
    ai = pm.getApplicationInfo(packageName, 0);
} catch (final NameNotFoundException e) {
    ai = null;
}
final String applicationName = (String) (ai != null ? pm.getApplicationLabel(ai) : "(unknown)");

답변

패키지 이름이 아닌 애플리케이션 이름 만 필요하면이 코드를 작성하십시오.

 String app_name = packageInfo.applicationInfo.loadLabel(getPackageManager()).toString();

답변

에서 코 틀린 , 응용 프로그램 이름을 얻기 위해 다음과 같은 코드를 사용 :

        // Get App Name
        var appName: String = ""
        val applicationInfo = this.getApplicationInfo()
        val stringId = applicationInfo.labelRes
        if (stringId == 0) {
            appName = applicationInfo.nonLocalizedLabel.toString()
        }
        else {
            appName = this.getString(stringId)
        }