Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 怎麼取得自己的 App 名稱?PackageManager 應用實作

編輯:關於 Android 程式設計

App 名稱(ApplicationName)看起來只是顯示用的字串,但實際上它藏在/AndroidManifest.xml 的 android:label 裡,可能是直接寫的字面值,也可能指向 @string/app_name。要在執行期把它讀出來,得繞 PackageManager 一圈。

取得名稱的關鍵兩步

先用 getApplicationInfo(getPackageName(), 0) 拿到這個 App 的 ApplicationInfo,再把它丟進 getApplicationLabel(),回傳的 CharSequence 就是最終顯示的名稱。之所以要經過 PackageManager,是因為 label 可能是一個資源引用,只有系統解析過才知道真正的文字。

package cn.testapplicationname;

import android.os.Bundle;
import android.widget.TextView;
import android.app.Activity;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;

public class MainActivity extends Activity {

    private TextView mTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        init();
    }

    private void init() {
        mTextView = (TextView) findViewById(R.id.textView);
        String applicationName = getApplicationName();
        mTextView.setText("該應用名字:" + applicationName);
    }

    public String getApplicationName() {
        PackageManager packageManager = null;
        ApplicationInfo applicationInfo = null;
        try {
            packageManager = getApplicationContext().getPackageManager();
            applicationInfo = packageManager.getApplicationInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            applicationInfo = null;
        }
        CharSequence label = packageManager.getApplicationLabel(applicationInfo);
        return label == null ? "" : label.toString();
    }
}

版面配置 main.xml

<RelativeLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />

</RelativeLayout>

兩個容易踩到的細節

原始寫法在例外發生時把 applicationInfo 設為 null,卻仍然呼叫 getApplicationLabel(null),這會得到空字串甚至在某些版本上出問題;更穩健的做法是例外時直接回傳預設名稱,不要繼續往下走。另外 getApplicationLabel() 回傳的是 CharSequence,別忘了轉成 String 再交給 TextView 或做字串比對。

順帶一提,如果你要的其實是「目前這個 Activity」的標題,用 getTitle() 就好;要的是 launcher 底下顯示的那個名字,才是這裡的 ApplicationLabel。兩者在設定 android:label 於 Activity 節點時會不一樣。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved