【发布时间】:2018-03-08 08:32:10
【问题描述】:
我正在尝试在活动和服务之间提供通信,但我遇到了问题。尽管在 onStartCommand 方法上初始化了 id,但我收到了这个错误
java.lang.RuntimeException:无法创建服务 com.a.b.c.Services.LocationService: java.lang.NullPointerException: println 需要一条消息
public class LocationService extends Service {
Context context;
Timer timer;
Double latitude, longitude;
private String id;
public LocationService() {
}
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
Log.i("servis", "Service working...");
Log.i("id", id);
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
int isHere = isHere();
updateUserStatus(isHere);
}
}, 0, 200000);
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
id = intent.getStringExtra("id");
return START_STICKY;
}
private int isHere() {
GPSTracker gps = new GPSTracker(this);
if (!gps.canGetLocation()) {
gps.showSettingsAlert();
} else {
latitude = gps.getLatitude();
longitude = gps.getLongitude();
if(Math.abs(xxx - latitude) <= 0.001 || Math.abs(yyy - longitude) <= 0.001)
return 1;
else
return 0;
}
return 0;
}
private void updateUserStatus(int isHere){
Call<Kisi> x = ManagerAll.getInstance().updateLocation(id, isHere);
x.enqueue(new Callback<Kisi>() {
@Override
public void onResponse(Call<Kisi> call, Response<Kisi> response) {
if(response.isSuccessful())
Log.i("status", "succesful");
}
@Override
public void onFailure(Call<Kisi> call, Throwable t) {
}
});
}
}
【问题讨论】:
-
onCreate()在onStartCommand()之前运行。 -
那我该怎么办?也许所有的工作都应该在 onStartCommand 中完成?
-
不要尝试在
onCreate()中使用id。 -
我必须使用那个
-
"也许所有的工作都应该在 onStartCommand 中完成?" - 是的,这样做。
标签: android android-intent service location