服务和活动之间的数据通信

时间:2018-03-08 08:32:10

标签: android android-intent service location

我正在努力提供活动和服务之间的沟通,但我遇到了问题。尽管在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(79.875303 - latitude) <= 0.001 || Math.abs(72.879980 - 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) {

        }
    });
}

}

1 个答案:

答案 0 :(得分:0)

onCreate()方法中,您尝试记录变量id,但在运行onStartCommand方法之前未对其进行初始化,这在`onCreate()之后发生:

Service lifecycle

将您的日志记录移至id初始化之后,它应该可以正常工作。