gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 12:03:49 25 4
gpt4 key购买 nike

我的目标是拥有一个后台服务,每天两次更新相当大量的数据(约 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

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

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

<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>

你有什么想法吗?

谢谢!

最佳答案

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);
}

关于android - 服务构造函数中的上下文为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42949832/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com