私のマニフェストには次の内容が記載されています:
<application
android:name=".MyApp"
android:icon="@drawable/ic_launcher_icon"
android:label="@string/app_name"
android:debuggable="true">
ラベル要素を取得するにはどうすればよいですか?
注: 私のコードは他の誰かのコード内で実行されているため、@string/app_name にアクセスできません。
ベストアンサー1
他の回答よりも簡単な方法があり、リソースに明示的に名前を付けたり、パッケージ名に関する例外を心配したりする必要はありません。リソースの代わりに文字列を直接使用した場合にも機能します。
ただこうしてください:
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 の場合は ID を解決しないように上記を変更しました。代わりに、nonLocalizedLabel
バックオフとして使用します。try/catch でラップする必要はありません。