Android-如何获取应用程序名称? (不是包名) [英] Android - How to get application name? (Not package name)
本文介绍了Android-如何获取应用程序名称? (不是包名)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的清单上有:
<application
android:name=".MyApp"
android:icon="@drawable/ic_launcher_icon"
android:label="@string/app_name"
android:debuggable="true">
如何获取标签元素?
注意:我的代码正在其他人的内部运行,因此我无权访问@ string/app_name
推荐答案
比其他答案有一种更简单的方法,它不需要您明确命名资源或担心包名称的异常.如果您直接使用字符串而不是资源,它也可以使用.
There's an easier way than the other answers that doesn't require you to name the resource explicitly or worry about exceptions with package names. It also works if you have used a string directly instead of a resource.
只需:
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中进行换行.
In light of the comment from Snicolas, I've modified the above so that it doesn't try to resolve the id if it is 0. Instead it uses, nonLocalizedLabel
as a backoff. No need for wrapping in try/catch.
这篇关于Android-如何获取应用程序名称? (不是包名)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文