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

自定義 Application 全域變數出現 ClassCastException?別忘了在 AndroidManifest 註冊

編輯:關於 Android 程式設計

今天寫了一個全域變數類別 AppContext,卻一直出現以下的錯誤:

java.lang.RuntimeException: Unable to start activity ComponentInfo
{com.langteng.shiliao/com.langteng.shiliao.activity.MainActivity}:
java.lang.ClassCastException: android.app.Application cannot be cast to
com.langteng.shiliao.until.AppContext

類別本身寫得沒問題:

public class AppContext extends Application {

    public static final int NETTYPE_WIFI = 0x01;
    public static final int NETTYPE_CMWAP = 0x02;
    public static final int NETTYPE_CMNET = 0x03;

    public static final int PAGE_SIZE = 20;          // 預設分頁大小
    private static final int CACHE_TIME = 10 * 60000; // 快取失效時間

    // ... 其他成員
}

接著在 Activity 中透過 getApplication() 取得 Application 型別的物件,再轉型成自訂的 AppContext:

appContext = (AppContext) getApplication();

結果一執行就丟出型別轉換錯誤。

原因

網路上查了一輪才找到癥結:自訂的 Application 必須在 AndroidManifest.xml 中註冊,否則系統只會建立原始的 android.app.Application 物件,當然無法轉型成你的子類別。

解法

在 <application> 節點上補上 android:name,指向你的類別全名(或相對路徑):

<application
    android:name=".AppContext"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme">
    ...
</application>

觀念釐清

Application 是整個 Process 的唯一實例,所有 Activity、Service 共用同一個物件,因此很適合放全域狀態。但要記住兩個重點:

  1. 一定要在 Manifest 註冊,否則系統不會替你建立子類別。
  2. 類別名稱要寫對。.AppContext 是相對寫法,代表與 manifest 的 package 同名的套件;若類別放在子套件(例如 com.langteng.shiliao.until.AppContext),就必須寫完整路徑,這也是不少人明明註冊了卻仍然失敗的原因。

另外提醒,全域變數雖然方便,但不適合存放大量資料或需要嚴格生命週期管理的資源。Process 隨時可能被系統回收重建,把關鍵狀態寄存在 Application 上,記得要有從 PersistentStorage 還原的機制。

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