服务构造函数中的上下文为空?

Context is null in service constructor?

我的目标是拥有一个后台服务,每天两次更新相当大量的数据(约 5 分钟更新,可能更多)。

所以我有一个启动此服务的 GcmTaskService:

public class SyncOfflineCoursesService extends Service {

    private final IBinder mBinder = new MonBinder();
    private final SharedPreferenceManagerToReplace sharedPreferenceManager;

    public SyncOfflineCoursesService() {

        sharedPreferenceManager = new SharedPreferenceManagerToReplace(this); //crash on this line

    }

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

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    public class MonBinder extends Binder {
        SyncOfflineCoursesService getService() {
            return SyncOfflineCoursesService.this;
        }
    }

}

SharedPreferenceManagerToReplace :

public class SharedPreferenceManagerToReplace {
    private final SharedPreferences prefs;

    public SharedPreferenceManagerToReplace(Context context) {
        this.prefs = PreferenceManager.getDefaultSharedPreferences(context);//crash here
    }
}

但是当我实例化 SharedPreferenceManager

时,这似乎是空的
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference

这就是我在清单中声明我的两项服务的方式:

<service
    android:name=".service.offline.SyncOfflineCoursesService"
    android:exported="false" />

<service
    android:name=".service.offline.SyncOfflineContentService"
    android:exported="true"
    android:permission="com.google.android.gms.permission.BIND_NETWORK_TASK_SERVICE">

    <intent-filter>
        <action android:name="com.google.android.gms.gcm.ACTION_TASK_READY" />
    </intent-filter>
</service>

你有什么想法吗?

谢谢!

您应该有 activity 的上下文。服务上下文将不起作用。 在构造函数中传递上下文并使用该上下文传递下一个构造函数。

public SyncOfflineCoursesService(Context mContext) {

     sharedPreferenceManager = new SharedPreferenceManagerToReplace(mContext); 

}

NullPointerException is thrown when an application attempts to use an object reference that has the null value.

您应该在 onStartCommand() 部分调用它。

 Context context;  //Public  

 @Override
    public int onStartCommand(Intent intent, int flags, int startId) 
    {
    context= getApplicationContext();
    sharedPreferenceManager = new SharedPreferenceManagerToReplace(context); 
    return super.onStartCommand(intent, flags, startId);
    }