您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

openFileOutput在单例类中不能正常工作-想法/解决方法?

openFileOutput在单例类中不能正常工作-想法/解决方法?

您将单例基于未作为活动开始的活动。因此,它没有有效的上下文,这对于IO调用是必需的。请参阅Blundell的答案以获得更好的单例,但有一个更改:根据android.app.Application javadoc,您的单例应通过Context.getApplicationContext()从给定上下文中获取应用程序上下文。

您应该编写一个单例类,如下所示:

 import android.content.Context;
 import android.util.Log;

 public final class SomeSingleton implements Cloneable {

private static final String TAG = "SomeSingleton";
private static SomeSingleton someSingleton ;
private static Context mContext;    

/**
 * I'm private because I'm a singleton, call getInstance()
 * @param context
 */
private SomeSingleton(){
      // Empty
}

public static synchronized SomeSingleton getInstance(Context context){
    if(someSingleton == null){
        someSingleton = new SomeSingleton();
    }
    mContext = context.getApplicationContext();
    return someSingleton;
}

public void playSomething(){
    // Do whatever
            mContext.openFileOutput("somefile", MODE_PRIVATE); // etc...
}

public Object clone() throws CloneNotSupportedException {
    throw new CloneNotSupportedException("I'm a singleton!");
}
 }

然后,您可以这样称呼它(取决于您从何处调用它):

 SomeSingleton.getInstance(context).playSomething();
 SomeSingleton.getInstance(this).playSomething();
 SomeSingleton.getInstance(getApplicationContext()).playSomething();

编辑:请注意,此单例有效,因为它不基于Activity,并且从实例化它的任何人(例如另一个正确启动的Activity)都可以获取有效的Context。您的原始单例失败,因为它从未作为活动开始,因此没有有效的上下文。-cdhabecker

其他 2022/1/1 18:27:48 有432人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶