Service的构造函数中的NullPointerException

Lee*_*fin 4 android android-service

在我的Android项目中,我有一个Service:

public class MyService extends Service{

    //I defined a explicite contructor 
    public MyService(){
       //NullPointerException here, why?
       File dir = getDir("my_dir", Context.MODE_PRIVATE);
    }

    @Override
    public void onCreate(){
      super.onCreate();
      ...
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);
        ...
    }

}
Run Code Online (Sandbox Code Playgroud)

我通常知道,我不应该为Android明确定义构造函数Service.但就我而言,我想使用构造函数在我的内部存储中创建一个目录.

当我尝试它时,我得到了NullPointerException,我不明白为什么?任何人都可以向我解释为什么在我的explicite构造函数中调用时出现NullPoineterExceptiongetDir(...)

laa*_*lto 6

getDir()是一种方法Context.

该服务未设置为用作Context直到onCreate().

基本上,框架通过以下方式设置服务(以及相关活动):

  1. 创建对象
  2. 建立Context,以适当的资源为当前配置
  3. 呼吁onCreate()对象

您无法执行任何需要Context在步骤1中正确设置对象的操作,即在成员变量初始化或构造函数期间.