Android - 如何获取应用程序名称? (不是包名)

标签 android

在我的 list 中,我有:

  <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 的评论,我修改了上面的内容,以便它不会尝试解析 0 的 id。而是使用 nonLocalizedLabel 作为退避。无需包装在 try/catch 中。

关于Android - 如何获取应用程序名称? (不是包名),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11229219/

相关文章:

Android 设计自定义 View

android - 使用 viewpager 滑动图像(不是布局)

java - 在字符串之间搜索文本 android

android:在设备旋转时禁用 opengl ES 上下文切换

android - com.google.android.material.tabs.TabLayout 的自定义样式

android - 按顺序将动画应用到多个 View

安卓 - 安卓模拟器的任何替代品

javascript - 使用 WebView Javascript Android 进行网站登录

java - 如何创建闪光灯和频闪效果。需要帮助来修复频闪效应

android - 在ndk级别创建位图并显示