从不同的 IntentService 访问 SharedPreferences

Accesing SharedPreferences from different IntentService

我在从 IntentService 内部访问 shredPreferences 时遇到问题

这是我得到的错误:

java.lang.RuntimeException: Unable to instantiate service com.androidbook.btdt.hour6.QuizSettingsActivity$UploaderService: java.lang.NullPointerException

出现空指针异常
mGameSettings = getSharedPreferences(GAME_PREFERENCES,Context.MODE_PRIVATE);

这是代码:

public static  class UploaderService extends IntentService{

String DEBUG_TAG = UploaderService.class.getSimpleName();

SharedPreferences mGameSettings;



private UpLoadUserData upLoadUserData;

/**
 * Creates an IntentService.  Invoked by your subclass's constructor.
 *
 * @param name Used to name the worker thread, important only for debugging.
 */
public UploaderService(String name) {
    super(name);
    mGameSettings = getSharedPreferences(GAME_PREFERENCES,Context.MODE_PRIVATE);
}

public UploaderService(){
    super("");
    mGameSettings = getSharedPreferences(GAME_PREFERENCES,Context.MODE_PRIVATE);
}

这是我启动 IntentService 的方式:

    Intent uploadService = new Intent(this,UploaderService.class);
    startService(uploadService);

我认为您需要在 startService 函数而不是构造函数中执行该行。我知道至少对于构造时的活动,上下文没有完全设置,所以很多调用都会失败。我相信服务也是一样的。