Пример #1
0
  private void connect() {
    boolean tryConnecting = true;
    while (tryConnecting) {
      try {
        MqttClient mqttClient = confac.getMqttClient();
        mqttClient.connect();
        setParams(params);
        setMsg(msg);
        setMqttSyncCallback(confac);
        listener1 = new InboundRequestProcessorFactoryImpl();

        if (mqttClient.isConnected()) {
          if (confac.getTopic() != null) {
            mqttClient.subscribe(confac.getTopic());
            log.info("Subscribed to the remote server.");
          }
          tryConnecting = false;
          injectHandler.invoke(msg);
          return;
        }
      } catch (Exception e1) {
        log.error("Connection attempt failed with '" + e1.getCause() + "'. Retrying.");
        pause();
      }
    }
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.inject(this);

    mapView.addLayer(
        new ArcGISTiledMapServiceLayer(
            "http://cache1.arcgisonline.cn/ArcGIS/rest/services/ChinaOnlineCommunity/MapServer"));

    layer = new GraphicsLayer();
    mapView.addLayer(layer);

    mapView.getLocationDisplayManager().start();
    mapView.getLocationDisplayManager().setLocationListener(this);

    try {
      client =
          new MqttAndroidClient(
              this, "tcp://broker.mqttdashboard.com:1883", "Likaci/MqttMap/" + id);
      client.setCallback(this);
      MqttConnectOptions options = new MqttConnectOptions();
      options.setKeepAliveInterval(10);
      options.setConnectionTimeout(1000);
      options.setCleanSession(false);
      client.connect(options, null, this);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 // region LocationListener
 @Override
 public void onLocationChanged(Location location) {
   String msg =
       String.format(
           "{\"id\":\"%s\",\"x\":%.9f,\"y\":%.9f}",
           id, location.getLongitude(), location.getLatitude());
   try {
     client.publish("Likaci/MqttMap", msg.getBytes(), 0, false);
   } catch (Exception e) {
     e.printStackTrace();
   }
 }