示例#1
0
  @Override
  public void onCreate() {
    super.onCreate();

    vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

    gameDatabase = new GameDatabase(this);

    // init game DB
    if (gameDatabase.getViruses().isEmpty()) {
      Virus v = VirusFactory.createMutation(null);
      Log.d(LOG_TAG, "new virus: " + v.getId());
      gameDatabase.addVirus(v);
      EventBus.getDefault().post(new GameEvent(GameEvent.Type.NEW_VIRUS, v.getId(), 0));
    }
    clientId = gameDatabase.getSetting("clientId", null);
    if (clientId == null) {
      clientId = UUID.randomUUID().toString();
      gameDatabase.putSetting("clientId", clientId);
      Log.i(LOG_TAG, "persisted new clientId: " + clientId);
    }

    // MQTT
    mqttClient = new MqttAndroidClient(this, BROKER_URI, clientId);
    mqttClient.setCallback(this);

    // Location
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
      locationManager.requestLocationUpdates(
          LocationManager.GPS_PROVIDER,
          MIN_LOCATION_UPDATE_INTERVAL_MS,
          MIN_LOCATION_UPDATE_DISTANCE_M,
          this);
    else
      locationManager.requestLocationUpdates(
          LocationManager.NETWORK_PROVIDER,
          MIN_LOCATION_UPDATE_INTERVAL_MS,
          MIN_LOCATION_UPDATE_DISTANCE_M,
          this);

    findBestLastLocation();

    try {
      MqttConnectOptions options = new MqttConnectOptions();
      options.setKeepAliveInterval(0); // no keepalive pings
      mqttClient.connect(options, null, this);
      Log.d(LOG_TAG, "connected to MQTT broker as " + clientId);
    } catch (MqttException e) {
      Log.e(LOG_TAG, "could not connect to MQTT broker at " + BROKER_URI);
    }

    EventBus.getDefault().register(this);
  }