【问题标题】:Data communication between service and activity服务和活动之间的数据通信
【发布时间】: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


【解决方案1】:

在您的onCreate() 方法中,您尝试记录变量id,但在运行onStartCommand 方法之前它没有被初始化,这发生在`onCreate() 之后:

Service lifecycle

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多