1

我正在尝试在 android 应用程序中创建一个内部文件。我已经生成了适用于 java 的代码,但是为了创建内部文件,我相信我必须具备这样做的上下文。

示例:文件 file = new File(Context.getFilesDir(), "somefile.txt");

我遇到的问题是文件创建和检查是否创建在我创建的单例类中维护。使用以下内容时

示例:文件 file = new File("somefile.txt");

一切似乎都可以编译和工作,但在关闭应用程序后,似乎没有创建文件。这使我相信我需要使用给出的第一个示例的应用程序目录。问题是如何在单个类中获取应用程序上下文?

4

3 回答 3

1

问题是如何在单个类中获取应用程序上下文?

来自Android 文档

通常不需要子类化 Application。在大多数情况下,静态单例可以以更模块化的方式提供相同的功能。如果您的单例需要全局上下文(例如注册广播接收器),则可以为检索它的函数提供一个 Context,该上下文在首次构造单例时在内部使用 Context.getApplicationContext()。

像这样创建你的单例:

// ...
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);
}

或者您可以使用此处提到的其他方式

于 2014-09-23T18:43:38.647 回答
0

方法:

new File("filename")

不在磁盘上创建文件。

您需要打开文件并写入文件以创建文件,或使用

File.createNewFile

于 2014-09-23T18:56:40.073 回答
0

或者您可以扩展已经是 Singleton 的 Application 类。它可能相当有用:)

package com.example.myapp;

import android.app.Application;
import android.content.Context;

public class MyApp extends Application {
    private static Context context;
    private static MyApp my_instance;

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        my_instance = this;
        context = this;
    }

    public static synchronized MyApp getInstance() {
        return my_instance;
    }

    public static synchronized Context getContext() {
        return context;
    }
}
于 2014-09-23T18:52:57.093 回答