My goal is to have a background service that update a fairly large amount of data twice a day (~5min update, possibly more).
So I have a GcmTaskService that launch this service :
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
}
}
but it seem that this is null when I instanciate SharedPreferenceManager
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
That's how I declared both of my services in my manifest :
<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>
Would you have an idea ?
Thanks !
Serviceshouldn't really have a constructor. Move that initialization to one of its lifecycle methods, likeonCreate()oronStartCommand().