protected synchronized void stop() {
   _stop = true;
   try {
     // Close the connection so the thread will return.
     _notify.close();
   } catch (IOException e) {
     System.err.println(e.toString());
   } catch (NullPointerException e) {
     // The notify object likely failed to open, due to an IOException.
   }
 }
  protected BTGPSLocationProvider() throws LocationException {

    // TODO: Move this to searchConnect method?
    // TODO: The problem here is that it searches every time. Slow. Need to try Properties?
    // TODO: BIG ONE: Should only connect to GPS that isPaired() (from menu). Will
    // allow some degree of control over which GPS is connects to in classroom.
    try {
      da = LocalDevice.getLocalDevice().getDiscoveryAgent();
      da.startInquiry(DiscoveryAgent.GIAC, this);
    } catch (BluetoothStateException e) {
      throw new LocationException(e.getMessage());
    }

    while (!doneInq) {
      Thread.yield();
    }

    if (btDevice == null) throw new LocationException("No device found");

    String address = btDevice.getBluetoothAddress();
    String btaddy = "btspp://" + address;

    try {
      StreamConnectionNotifier scn = (StreamConnectionNotifier) Connector.open(btaddy);

      if (scn == null) throw new LocationException("Bad BT address");
      StreamConnection c = scn.acceptAndOpen();

      /* This problem below occurred one time for my Holux GPS. The solution was to
       * remove the device from the Bluetooth menu, then find and pair again.
       */
      if (c == null) throw new LocationException("Failed. Try pairing at menu again");
      InputStream in = c.openInputStream();

      if (in != null) {
        gps = new SimpleGPS(in);
        // c.close(); // TODO: Clean up when done. HOW TO HANDLE IN LOCATION?
      }
    } catch (IOException e) {
      throw new LocationException(e.getMessage());
    }
    // Add itself to SimpleGPS as listener
    SimpleGPS.addListener(this);
  }
  /** Handle incoming response here */
  public void notifyResponse(SipClientConnection scc) {
    int statusCode = 0;
    boolean received = false;
    try {
      scc.receive(0); // <i><b>fetch resent response</b></i>
      statusCode = scc.getStatusCode();
      str = new StringItem("Response: ", statusCode + " " + scc.getReasonPhrase());
      form.append(str);
      if (statusCode < 200) {
        dialog = scc.getDialog();
        form.append("Early-Dialog state: " + dialog.getState());
      }
      if (statusCode == 200) {
        String contentType = scc.getHeader("Content-Type");
        String contentLength = scc.getHeader("Content-Length");
        int length = Integer.parseInt(contentLength);
        if (contentType.equals("application/sdp")) {
          //
          // <i><b>handle SDP here</b></i>
          //
        }
        dialog = scc.getDialog(); // <i><b>save dialog info</b></i>
        form.append("Dialog state: " + dialog.getState());

        scc.initAck(); // <i><b>initialize and send ACK</b></i>
        scc.send();
        str = new StringItem("Session established: ", scc.getHeader("Call-ID"));
        form.append(str);
        scc.close();
      } else if (statusCode >= 300) {
        str = new StringItem("Session failed: ", scc.getHeader("Call-ID"));
        form.append(str);
        form.removeCommand(byeCmd);
        form.addCommand(restartCmd);
        scc.close();
      }
    } catch (IOException ioe) {
      // <i><b>handle e.g. transaction timeout here</b></i>
      str = new StringItem("No answer: ", ioe.getMessage());
      form.append(str);
      form.removeCommand(byeCmd);
      form.addCommand(restartCmd);
    }
  }
 /** end session with BYE */
 private void sendBYE() {
   if (dialog != null) {
     try {
       SipClientConnection sc = dialog.getNewClientConnection("BYE");
       sc.send();
       str = new StringItem("user hang-up: ", "BYE sent...");
       form.append(str);
       boolean gotit = sc.receive(10000);
       if (gotit) {
         if (sc.getStatusCode() == 200) {
           form.append("Session closed successfully...");
           form.append("Dialog state: " + dialog.getState());
         } else form.append("Error: " + sc.getReasonPhrase());
       }
       sc.close();
     } catch (IOException iox) {
       form.append("Exception: " + iox.getMessage());
     }
   } else {
     form.append("No dialog information!");
   }
 }
  public void run() {

    StreamConnection stream = null;
    InputStream input = null;
    MDSPushInputStream pushInputStream = null;

    while (!_stop) {
      try {

        // Synchronize here so that we don't end up creating a connection that is never closed.
        synchronized (this) {
          // Open the connection once (or re-open after an IOException),  so we don't end up
          // in a race condition, where a push is lost if it comes in before the connection
          // is open again. We open the url with a parameter that indicates that we should
          // always use MDS when attempting to connect.
          int port = RhoConf.getInstance().getInt("push_port");
          if (port == 0) port = 100;
          _notify = (StreamConnectionNotifier) Connector.open(URL + port + ";deviceside=false");
        }

        while (!_stop) {

          // NOTE: the following will block until data is received.
          LOG.TRACE("Block push thread until data is recieved");
          stream = _notify.acceptAndOpen();
          LOG.TRACE("Recieved push data");

          try {
            input = stream.openInputStream();
            pushInputStream = new MDSPushInputStream((HttpServerConnection) stream, input);

            // Extract the data from the input stream.

            DataBuffer db = new DataBuffer();
            byte[] data = new byte[CHUNK_SIZE];
            int chunk = 0;

            while (-1 != (chunk = input.read(data))) {
              db.write(data, 0, chunk);
            }

            processPushMessage(data);

            // This method is called to accept the push.
            pushInputStream.accept();

            input.close();
            stream.close();

            data = db.getArray();

          } catch (IOException e1) {
            // A problem occurred with the input stream , however, the original
            // StreamConnectionNotifier is still valid.
            System.err.println(e1.toString());

            if (input != null) {
              try {
                input.close();
              } catch (IOException e2) {
              }
            }

            if (stream != null) {
              try {
                stream.close();
              } catch (IOException e2) {
              }
            }
          }
        }

        _notify.close();
        _notify = null;

      } catch (IOException ioe) {
        LOG.TRACE("Exception thrown by _notify.acceptAndOpen() - exiting push thread");

        // Likely the stream was closed. Catches the exception thrown by
        // _notify.acceptAndOpen() when this program exits.

        _stop = true;

        if (_notify != null) {
          try {
            _notify.close();
            _notify = null;
          } catch (IOException e) {
          }
        }
      }
    }
  }
  /**
   * Task execution code: <br>
   * ---------- <br>
   * Performed operations: <br>
   *
   * <ul type="disc">
   *   <li>Add alarm to position strings, if necessary;
   *   <li>Send string;
   *   <li>Check the number of sent strings.
   * </ul>
   */
  public void run() {

    list = new BCListenerCustom();
    list.addInfoStato(infoS);
    BearerControl.addListener(list);

    while (!infoS.isCloseUDPSocketTask()) {

      // if(false){
      if ((infoS.getInfoFileString(TrkState).equals("ON")
              || (infoS.getInfoFileString(TrkState)).equalsIgnoreCase("ON,FMS"))
          && infoS.getInfoFileString(GPRSProtocol).equals("UDP")
          && ((infoS.getInfoFileInt(TrkIN) != infoS.getInfoFileInt(TrkOUT))
              || !infoS.getDataRAM().equals(""))) {

        exitTRKON = false;

        try {

          // Indicates if GPRS SOCKET is ACTIVE
          // System.out.println("TT*UDPSocketTask: START");
          infoS.setIfsocketAttivo(true);
          destAddressUDP =
              "datagram://"
                  + infoS.getInfoFileString(DestHost)
                  + ":"
                  + infoS.getInfoFileString(DestPort);

          /*
           * Once this task has been started, it is completely
           * finished before proceeding to a re-use, even if the
           * timeout expires (so there may be a FIX GPRS timeout
           * expired!)
           */
          try {
            try {
              while (!InfoStato.getCoda()) Thread.sleep(1L);
            } catch (InterruptedException e) {
            }

            if (infoS.getInfoFileInt(TrkIN) == infoS.getInfoFileInt(TrkOUT)) {
              outText = infoS.getDataRAM();
              ram = true;
            } else {
              ram = false;
              temp = infoS.getInfoFileInt("TrkOUT");
              System.out.println("TT*UDPSocketTask: pointer out - " + temp);
              if ((temp >= codaSize) || (temp < 0)) temp = 0;
              outText = infoS.getRecord(temp);
              new LogError("TT*UDPSocketTask: pointer out - " + temp + " " + outText);
              System.out.println("TT*UDPSocketTask: data in queue: " + outText);
            }

            System.out.println("TT*UDPSocketTask: string to send through GPRS:\r\n" + this.outText);

            ctrlSpeed = infoS.getSpeedForTrk();
            if (debug_speed) {
              ctrlSpeed = infoS.getSpeedGree();
              System.out.println("SPEED " + ctrlSpeed);
            }
            try {
              val_insensibgps = Integer.parseInt(infoS.getInfoFileString(InsensibilitaGPS));
            } catch (NumberFormatException e) {
              val_insensibgps = 0;
            }
            // new LogError("Actual speed: " + ctrlSpeed + ". Val insens: " + val_insensibgps);

            if (ram) {

              // System.out.println("ACTUAL SPEED: " + this.ctrlSpeed);
              // System.out.println("outText.indexOf(ALARM) " + (this.outText.indexOf("ALARM") >
              // 0));
              // System.out.println("outText.indexOf(ALIVE) " + (this.outText.indexOf("ALIVE") >
              // 0));
              // System.out.println("SPEED LIMIT: " + this.val_insensibgps);
              // System.out.println("PREVIOUS MESSAGE IS ALIVE: " + this.infoS.getPreAlive());
              // System.out.println("SPEED LIMIT: " + this.val_insensibgps);
              // System.out.println("PREVIOUS SPEED: " + this.infoS.getPreSpeedDFS());

              if (this.ctrlSpeed > this.val_insensibgps) {
                System.out.println("Speed check ok.");
                infoS.settrasmetti(true);
                if (this.infoS.getInvioStop()) {
                  infoS.setApriGPRS(true);
                }
                infoS.setInvioStop(false);
              } else {
                if ((outText.indexOf("ALARM") > 0) || (outText.indexOf("ALIVE") > 0)) {
                  System.out.println("Alarm");
                  infoS.settrasmetti(true);
                  infoS.setApriGPRS(true);
                } else {

                  if ((!infoS.getPreAlive())
                      && (ctrlSpeed <= val_insensibgps)
                      && (infoS.getPreSpeedDFS() > val_insensibgps)) {

                    System.out.println(
                        "Speed check less then insensitivity, previous speed is greater");
                    infoS.settrasmetti(true);
                    if (infoS.getInvioStop() == true) {
                      infoS.setApriGPRS(true);
                    }
                    infoS.setInvioStop(false);

                  } else {

                    System.out.println("Speed check failed.");
                    if (infoS.getInvioStop() == false) {
                      System.out.println("Send stop coordinate.");
                      infoS.settrasmetti(true);
                      infoS.setInvioStop(true);
                      infoS.setChiudiGPRS(true);

                      // new LogError("Send stop.");
                    }
                  }
                }
              }
              if (this.outText.indexOf("ALIVE") > 0) {
                System.out.println("ALIVE MESSAGE");
                infoS.setPreAlive(true);
              } else {
                infoS.setPreAlive(false);
                System.out.println("NO ALIVE MESSAGE");
              }
            } else {
              // new LogError("From store.");

              infoS.settrasmetti(true);

              infoS.setChiudiGPRS(false);
            }

            // new LogError("Transmission status: " + infoS.gettrasmetti());

            if (infoS.gettrasmetti() == true) {

              infoS.settrasmetti(false);

              if (infoS.getApriGPRS() == true) {

                close = false;
                infoS.setTRKstate(true);
                try {
                  semAT.getCoin(5);
                  infoS.setATexec(true);
                  mbox2.write("at^smong\r");
                  while (infoS.getATexec()) {
                    Thread.sleep(whileSleep);
                  }
                  infoS.setATexec(true);
                  mbox2.write("at+cgatt=1\r");
                  while (infoS.getATexec()) {
                    Thread.sleep(whileSleep);
                  }
                  semAT.putCoin();
                } catch (Exception e) {
                }

                // Open GPRS Channel
                try {
                  udpConn = (UDPDatagramConnection) Connector.open(destAddressUDP);
                } catch (Exception e) {
                  System.out.println("TT*UDPSocketTask: Connector.open");
                }
                infoS.setApriGPRS(false);
              }

              try {
                // mem2 = r.freeMemory();
                // System.out.println("Free memory after allocation: " + mem2);
                if ((outText == null) || (outText.indexOf("null") >= 0)) {
                  outText =
                      infoS.getInfoFileString(Header)
                          + ","
                          + infoS.getInfoFileString(IDtraker)
                          + defaultGPS
                          + ",<ERROR>*00";
                  buff = outText.getBytes();
                }
                System.out.println("OPEN DATAGRAM");
                System.out.println(outText);
                dgram = udpConn.newDatagram(outText.length());
                buff = new byte[outText.length()];
                System.out.println("SEND DATAGRAM");
                buff = outText.getBytes();
                new LogError("outText = " + outText);
                dgram.setData(buff, 0, buff.length);
                udpConn.send(dgram);
                int gprsCount = 0;
                answer = "";
                String ack = infoS.getInfoFileString(Ackn);
                if (!infoS.getInfoFileString(Ackn).equals("")) {
                  while (true) {
                    dgram.reset();
                    dgram.setLength(infoS.getInfoFileString(Ackn).length() + 1);
                    udpConn.receive(dgram);
                    byte[] data = dgram.getData();
                    answer = new String(data);
                    answer = answer.substring(0, ack.length());
                    if (debug) {
                      System.out.println("ACK: " + answer);
                    }
                    if (answer.equals(ack)) {
                      new LogError("ACK");
                      if (debug) System.out.println("ACK RECEIVED");
                      break;
                    } else {
                      if (debug) System.out.println("WAITING ACK");
                      try {
                        Thread.sleep(1000);
                      } catch (InterruptedException e) {
                      }
                      gprsCount++;
                    }
                    if (gprsCount > 15) {
                      new LogError("NACK");
                      infoS.setReboot();
                      errorSent = true;
                      break;
                    }
                  }
                }

              } catch (Exception err) {
                System.out.println("TT*UDPSocketTask: Exception err");
                new LogError("TT*UDPSocketTask: Exception during out text" + err.getMessage());
                infoS.setReboot();
                errorSent = true;
                break;
              }
              // new LogError(outText);
              if (debug) System.out.println(outText);

              if (infoS.getChiudiGPRS() == true) {

                infoS.setTRKstate(false);
                try {
                  System.out.println("TT*UDPSocketTask: close UDP");
                  udpConn.close();
                } catch (NullPointerException e) {
                  infoS.setChiudiGPRS(false);
                }
                infoS.setChiudiGPRS(false);
              }
            }

            System.out.println("BEARER: " + infoS.getGprsState());
            if (!infoS.getGprsState()) {
              errorSent = true;
              System.out.println("BEARER ERROR");
              new LogError("BEARER ERROR");
            }

            if (ram) {
              if (!errorSent) {
                infoS.setDataRAM("");
              }
            } else {
              if (!errorSent) {
                temp++;
                if (temp >= codaSize || temp < 0) temp = 0;
                infoS.setInfoFileInt(TrkOUT, "" + temp);
                file.setImpostazione(TrkOUT, "" + temp);
                InfoStato.getFile();
                file.writeSettings();
                InfoStato.freeFile();
              }
              errorSent = false;
            }
            InfoStato.freeCoda();

            infoS.setIfsocketAttivo(false);
            Thread.sleep(100);
            if (errorSent) {
              close = true;
              semAT.putCoin(); // release AT interface
              infoS.setIfsocketAttivo(false);
              infoS.setApriGPRS(false);
              infoS.setChiudiGPRS(false);
            }
            // r.gc(); // request garbage collection

            // mem2 = r.freeMemory();
            // System.out.println("Free memory after collecting" + " discarded Integers: " + mem2);

          } catch (IOException e) {
            close = true;
            String msgExcept = e.getMessage();
            System.out.println("TT*UDPSocketTask: exception: " + msgExcept);

            // new LogError("SocketGPRStask IOException: " + e);
            infoS.setIfsocketAttivo(false);

            infoS.setApriGPRS(false);
            infoS.setChiudiGPRS(false);

          } catch (EmptyStackException e) {
            close = true;
            // System.out.println("exception: " + e.getMessage());
            e.printStackTrace();

            // new LogError("SocketGPRStask EmptyStackException");
            infoS.setIfsocketAttivo(false);

            infoS.setApriGPRS(false);
            infoS.setChiudiGPRS(false);
          } // catch

        } catch (Exception e) {
          close = true;
          // new LogError("SocketGPRSTask generic Exception");
          infoS.setIfsocketAttivo(false);

          infoS.setApriGPRS(false);
          infoS.setChiudiGPRS(false);
        }

        if (close) {

          try {
            semAT.getCoin(5);
            infoS.setATexec(true);
            mbox2.write("at^smong\r");
            while (infoS.getATexec()) {
              Thread.sleep(whileSleep);
            }
            semAT.putCoin();
          } catch (Exception e) {
          }

          try {
            // System.out.println("***************CLOSE******************");
            try {
              udpConn.close();
            } catch (NullPointerException e) {

            }
            // System.out.println("***************CLOSED******************");

            infoS.setTRKstate(false);
            infoS.setEnableCSD(true);

            semAT.getCoin(5);
            // Close GPRS channel
            // System.out.println("SocketGPRSTask: KILL GPRS");
            infoS.setATexec(true);
            mbox2.write("at+cgatt=0\r");
            while (infoS.getATexec()) {
              Thread.sleep(whileSleep);
            }

            semAT.putCoin();

            Thread.sleep(5000);
          } catch (InterruptedException e) {

          } catch (IOException e) {

          } catch (Exception e) {

          }
          System.out.println("WAIT - DISCONNECT GPRS");
          for (countDownException = 0; countDownException < 100; countDownException++) {
            if (infoS.isCloseUDPSocketTask()) break;
            try {
              Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
          }
          infoS.setApriGPRS(true);
        }
      } else {

        try {
          if (infoS.getInfoFileString(TrkState).equals("OFF")) {

            infoS.setTRKstate(false);
            infoS.setEnableCSD(true);
            semAT.putCoin(); // release AT interface
            try {
              semAT.getCoin(5);
              // Close GPRS channel
              // System.out.println("SocketGPRSTask: TRK OFF KILL GPRS");
              infoS.setATexec(true);
              mbox2.write("at+cgatt=0\r");
              while (infoS.getATexec()) {
                Thread.sleep(whileSleep);
              }
              semAT.putCoin();
            } catch (InterruptedException e) {
            }
          }
          Thread.sleep(2000);
        } catch (InterruptedException e) {
        }
      }
    } // while
  } // run
  /** Implementation of Thread. */
  public void run() {
    StreamConnection connection = null;

    try {
      _screen.updateDisplay("Opening Connection...");
      String url =
          "socket://"
              + _screen.getHostFieldText()
              + ":44444;interface=wifi"
              + (_screen.isDirectTCP() ? ";deviceside=true" : "");
      connection = (StreamConnection) Connector.open(url);
      _screen.updateDisplay("Connection with " + _screen.getHostFieldText() + " established.");

      _in = connection.openInputStream();
      _out = new OutputStreamWriter(connection.openOutputStream());

      // Send the HELLO string.
      // send("Hello from BlackBerry 9860.");
      // send("Hello from BlackBerry 9860.");
      send(AzrRP_Screen.getMsg());

      // Execute further data exchange here...

      // send("Bye");

      _screen.updateDisplay("Done!");
    } catch (IOException e) {
      System.err.println(e.toString());
    } finally {
      _screen.setThreadRunning(false);

      try {
        _in.close();
      } catch (IOException ioe) {
      }
      try {
        _out.close();
        AzrRP_Screen.setMsg(null);

      } catch (IOException ioe) {
      }
      try {
        connection.close();

      } catch (IOException ioe) {
      }
    }
  }