問題は、単一のクラス内でアプリケーション コンテキストを取得する方法です。
Android ドキュメントから:
通常、Application をサブクラス化する必要はありません。ほとんどの場合、静的シングルトンは、よりモジュール化された方法で同じ機能を提供できます。シングルトンにグローバル コンテキストが必要な場合 (ブロードキャスト レシーバーを登録する場合など)、それを取得する関数に、シングルトンを最初に構築するときに Context.getApplicationContext() を内部的に使用する Context を指定できます。
次のようにシングルトンを作成します。
// ...
private Context mAppContext = null;
private static MySingleton mSingleton = null;
// ...
private MySingleton(Context context) {
mAppContext = context;
// ... other initialization
}
public static MySingleton get(Context context) {
if (mSingleton == null) {
/*
* Get the global application context since this is an
* application-wide singleton
*/
mSingleton = new MySingleton(
context.getApplicationContext());
}
return mSingleton;
}
アクティビティからシングルトンを取得するたびに、グローバル アプリケーション コンテキストにアクセスできます。
次のように、シングルトン内でファイルを作成するために使用できます。
public void createFile(String filename) {
File file = new File(mAppContext.getFilesDir(), filename);
}
または、ここに記載されている他の方法を使用することもできます