Exemple #1
0
 @Override
 public void surfaceCreated(SurfaceHolder holder) {
   Thread thread = null;
   thread = new Thread(this);
   flag = true;
   thread.start();
 }
Exemple #2
0
  @Override
  protected synchronized void onSizeChanged(int w, int h, int oldw, int oldh) {

    // update pixel conversion values
    PixelUtils.init(getContext());

    // disable hardware acceleration if it's not explicitly supported
    // by the current Plot implementation. this check only applies to
    // honeycomb and later environments.
    if (Build.VERSION.SDK_INT >= 11) {
      if (!isHwAccelerationSupported() && isHardwareAccelerated()) {
        setLayerType(View.LAYER_TYPE_SOFTWARE, null);
      }
    }

    // pingPong is only used in background rendering mode.
    if (renderMode == RenderMode.USE_BACKGROUND_THREAD) {
      pingPong.resize(h, w);
    }

    RectF cRect = new RectF(0, 0, w, h);
    RectF mRect = boxModel.getMarginatedRect(cRect);
    RectF pRect = boxModel.getPaddedRect(mRect);

    layout(new DisplayDimensions(cRect, mRect, pRect));
    super.onSizeChanged(w, h, oldw, oldh);
    if (renderThread != null && !renderThread.isAlive()) {
      renderThread.start();
    }
  }
  public void onDestroy() {
    running = false;
    if (scanThread != null) scanThread.interrupt();

    if (myWLocate != null) myWLocate.doPause();

    sensorManager.unregisterListener(
        this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER));

    if (scanData.getmView() != null) {
      ((WindowManager) getSystemService(WINDOW_SERVICE)).removeView(scanData.getmView());
      scanData.setmView(null);
    }
    try {
      if (wl != null) wl.release();
    } catch (RuntimeException re) {
    }
    wl = null;
    try {
      scanThread.join(1000);
    } catch (InterruptedException ie) {

    }
    System.exit(0);
  }
 private void downloadImageThread() {
   Thread thread = new Thread(null, runInBackground, "Background");
   thread.start();
   try {
     thread.join();
   } catch (InterruptedException e) {
     e.printStackTrace();
   }
 }
  private void restartMap() {
    breakMapThread = true;
    postInvalidate();
    if (mapThread != null)
      try {
        mapThread.join(1500);
      } catch (InterruptedException ie) {

      }
    mapThread = new Thread(this);
    mapThread.start();
  }
Exemple #6
0
  public static void audioStartThread() {
    mAudioThread =
        new Thread(
            new Runnable() {
              public void run() {
                mAudioTrack.play();
                nativeRunAudioThread();
              }
            });

    // I'd take REALTIME if I could get it!
    mAudioThread.setPriority(Thread.MAX_PRIORITY);
    mAudioThread.start();
  }
 public void setOverlay(MapOverlay overlay) {
   useOverlay = overlay;
   if (!mapThreadRunning) {
     mapThread = new Thread(this);
     mapThread.start();
   }
 }
Exemple #8
0
  // Called when the surface is resized
  public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    // Log.v("SDL", "surfaceChanged()");

    int sdlFormat = 0x85151002; // SDL_PIXELFORMAT_RGB565 by default
    switch (format) {
      case PixelFormat.A_8:
        Log.v("SDL", "pixel format A_8");
        break;
      case PixelFormat.LA_88:
        Log.v("SDL", "pixel format LA_88");
        break;
      case PixelFormat.L_8:
        Log.v("SDL", "pixel format L_8");
        break;
      case PixelFormat.RGBA_4444:
        Log.v("SDL", "pixel format RGBA_4444");
        sdlFormat = 0x85421002; // SDL_PIXELFORMAT_RGBA4444
        break;
      case PixelFormat.RGBA_5551:
        Log.v("SDL", "pixel format RGBA_5551");
        sdlFormat = 0x85441002; // SDL_PIXELFORMAT_RGBA5551
        break;
      case PixelFormat.RGBA_8888:
        Log.v("SDL", "pixel format RGBA_8888");
        sdlFormat = 0x86462004; // SDL_PIXELFORMAT_RGBA8888
        break;
      case PixelFormat.RGBX_8888:
        Log.v("SDL", "pixel format RGBX_8888");
        sdlFormat = 0x86262004; // SDL_PIXELFORMAT_RGBX8888
        break;
      case PixelFormat.RGB_332:
        Log.v("SDL", "pixel format RGB_332");
        sdlFormat = 0x84110801; // SDL_PIXELFORMAT_RGB332
        break;
      case PixelFormat.RGB_565:
        Log.v("SDL", "pixel format RGB_565");
        sdlFormat = 0x85151002; // SDL_PIXELFORMAT_RGB565
        break;
      case PixelFormat.RGB_888:
        Log.v("SDL", "pixel format RGB_888");
        // Not sure this is right, maybe SDL_PIXELFORMAT_RGB24 instead?
        sdlFormat = 0x86161804; // SDL_PIXELFORMAT_RGB888
        break;
      default:
        Log.v("SDL", "pixel format unknown " + format);
        break;
    }
    SDLActivity.onNativeResize(width, height, sdlFormat);

    // Now start up the C app thread
    if (mSDLThread == null) {
      mSDLThread = new Thread(new SDLMain(), "SDLThread");
      mSDLThread.start();
    }
  }
Exemple #9
0
  @Override
  public void run() {
    while (flag) {
      myDraw();
      try {
        Thread.sleep(50);
      } catch (InterruptedException e) {

      }
    }
  }
 public void start() {
   if (myThread == null) {
     Log.i(getClass().getName(), "Main thread.start()");
     myThread = new Thread(this);
     myThread.start();
   } else {
     Log.w(
         getClass().getName(),
         "Requested a thread.start(), but the thread is already running - ignoring this request! (myThread = "
             + myThread);
   }
 }
Exemple #11
0
  /** 线程运行的方法,当线程start后执行 */
  @Override
  public void run() {

    while (flag) {
      mDraw(); // 调用自定义的绘图方法
      mGameLogic(); // 调用自定义的逻辑方法
      try {
        Thread.sleep(50); // 让线程休息50毫秒
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }
Exemple #12
0
 public static void startApp() {
   // Start up the C app thread
   if (mSDLThread == null) {
     mSDLThread = new Thread(new SDLMain(), "SDLThread");
     mSDLThread.start();
   } else {
     /*
      * Some Android variants may send multiple surfaceChanged events, so we don't need to resume every time
      * every time we get one of those events, only if it comes after surfaceDestroyed
      */
     if (mIsPaused) {
       SDLActivity.nativeResume();
       SDLActivity.mIsPaused = false;
     }
   }
 }
Exemple #13
0
  public static void audioQuit() {
    if (mAudioThread != null) {
      try {
        mAudioThread.join();
      } catch (Exception e) {
        Log.v("SDL", "Problem stopping audio thread: " + e);
      }
      mAudioThread = null;

      // Log.v("SDL", "Finished waiting for audio thread");
    }

    if (mAudioTrack != null) {
      mAudioTrack.stop();
      mAudioTrack = null;
    }
  }
Exemple #14
0
 public static void audioWriteByteBuffer(byte[] buffer) {
   for (int i = 0; i < buffer.length; ) {
     int result = mAudioTrack.write(buffer, i, buffer.length - i);
     if (result > 0) {
       i += result;
     } else if (result == 0) {
       try {
         Thread.sleep(1);
       } catch (InterruptedException e) {
         // Nom nom
       }
     } else {
       Log.w("SDL", "SDL audio: error return from write(byte)");
       return;
     }
   }
 }
Exemple #15
0
  @Override
  protected void onDestroy() {
    super.onDestroy();
    Log.v("SDL", "onDestroy()");
    // Send a quit message to the application
    SDLActivity.nativeQuit();

    // Now wait for the SDL thread to quit
    if (mSDLThread != null) {
      try {
        mSDLThread.join();
      } catch (Exception e) {
        Log.v("SDL", "Problem stopping thread: " + e);
      }
      mSDLThread = null;

      // Log.v("SDL", "Finished waiting for SDL thread");
    }
  }
Exemple #16
0
  /** 当SurfaceView创建的时候调用 */
  @Override
  public void surfaceCreated(SurfaceHolder holder) {

    // 获得屏幕的宽和高
    screenW = this.getWidth();
    screenH = this.getHeight();

    qEndX = screenW - 10; // 设置贝塞尔曲线的终点横坐标为屏幕宽度减10
    qEndY = qStartY; // 设置贝塞尔曲线的终点纵坐标和起点纵坐标一样

    // 设置贝塞尔曲线的控制点坐标为终点坐标与起点坐标对应的差值的一半,注意这里不是曲线的中点
    qControlX = (qEndX - qStartX) / 2;
    qCOntrolY = (qEndY - qStartY) / 2;

    mThread = new Thread(this); // 创建线程对象
    flag = true; // 设置线程标识为true
    xReturn = false; // 设置图形坐标不返回
    cReturn = false; // 设置贝塞尔曲线控制点坐标不返回
    mThread.start(); // 启动线程
  }
Exemple #17
0
  // Called when we lose the surface
  public void surfaceDestroyed(SurfaceHolder holder) {
    // Log.v("SDL", "surfaceDestroyed()");

    // Send a quit message to the application
    SDLActivity.nativeQuit();

    // Now wait for the SDL thread to quit
    if (mSDLThread != null) {
      try {
        mSDLThread.join();
      } catch (Exception e) {
        Log.v("SDL", "Problem stopping thread: " + e);
      }
      mSDLThread = null;

      // Log.v("SDL", "Finished waiting for SDL thread");
    }

    enableSensor(Sensor.TYPE_ACCELEROMETER, false);
  }
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    mAppContext = this;
    mMainHandler = new Handler();

    if (!sTryCatchAttached) {
      sTryCatchAttached = true;
      mMainHandler.post(
          new Runnable() {
            public void run() {
              try {
                Looper.loop();
              } catch (Exception e) {
                Log.e(LOG_FILE_NAME, "top level exception", e);
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                e.printStackTrace(pw);
                pw.flush();
                GeckoAppShell.reportJavaCrash(sw.toString());
              }
              // resetting this is kinda pointless, but oh well
              sTryCatchAttached = false;
            }
          });
    }

    SharedPreferences settings = getPreferences(Activity.MODE_PRIVATE);
    String localeCode = settings.getString(getPackageName() + ".locale", "");
    if (localeCode != null && localeCode.length() > 0) GeckoAppShell.setSelectedLocale(localeCode);

    Log.i(LOG_FILE_NAME, "create");
    super.onCreate(savedInstanceState);

    if (sGREDir == null) sGREDir = new File(this.getApplicationInfo().dataDir);

    getWindow()
        .setFlags(
            mFullscreen ? WindowManager.LayoutParams.FLAG_FULLSCREEN : 0,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);

    if (cameraView == null) {
      cameraView = new SurfaceView(this);
      cameraView.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    if (surfaceView == null) surfaceView = new GeckoSurfaceView(this);
    else mainLayout.removeAllViews();

    mainLayout = new AbsoluteLayout(this);
    mainLayout.addView(
        surfaceView,
        new AbsoluteLayout.LayoutParams(
            AbsoluteLayout.LayoutParams.MATCH_PARENT, // level 8
            AbsoluteLayout.LayoutParams.MATCH_PARENT,
            0,
            0));

    setContentView(
        mainLayout,
        new ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));

    mConnectivityFilter = new IntentFilter();
    mConnectivityFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    mConnectivityReceiver = new GeckoConnectivityReceiver();

    IntentFilter batteryFilter = new IntentFilter();
    batteryFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
    mBatteryReceiver = new GeckoBatteryManager();
    registerReceiver(mBatteryReceiver, batteryFilter);

    if (SmsManager.getInstance() != null) {
      SmsManager.getInstance().start();
    }

    GeckoNetworkManager.getInstance().init();

    if (!checkAndSetLaunchState(LaunchState.PreLaunch, LaunchState.Launching)) return;

    checkAndLaunchUpdate();
    mLibLoadThread =
        new Thread(
            new Runnable() {
              public void run() {
                // At some point while loading the gecko libs our default locale gets set
                // so just save it to locale here and reset it as default after the join
                Locale locale = Locale.getDefault();
                GeckoAppShell.loadGeckoLibs(getApplication().getPackageResourcePath());
                Locale.setDefault(locale);
                Resources res = getBaseContext().getResources();
                Configuration config = res.getConfiguration();
                config.locale = locale;
                res.updateConfiguration(config, res.getDisplayMetrics());
              }
            });
    mLibLoadThread.start();
  }
Exemple #19
0
  // Called when the surface is resized
  @Override
  public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    Log.v("SDL", "surfaceChanged()");

    int sdlFormat = 0x15151002; // SDL_PIXELFORMAT_RGB565 by default
    switch (format) {
      case PixelFormat.A_8:
        Log.v("SDL", "pixel format A_8");
        break;
      case PixelFormat.LA_88:
        Log.v("SDL", "pixel format LA_88");
        break;
      case PixelFormat.L_8:
        Log.v("SDL", "pixel format L_8");
        break;
      case PixelFormat.RGBA_4444:
        Log.v("SDL", "pixel format RGBA_4444");
        sdlFormat = 0x15421002; // SDL_PIXELFORMAT_RGBA4444
        break;
      case PixelFormat.RGBA_5551:
        Log.v("SDL", "pixel format RGBA_5551");
        sdlFormat = 0x15441002; // SDL_PIXELFORMAT_RGBA5551
        break;
      case PixelFormat.RGBA_8888:
        Log.v("SDL", "pixel format RGBA_8888");
        sdlFormat = 0x16462004; // SDL_PIXELFORMAT_RGBA8888
        break;
      case PixelFormat.RGBX_8888:
        Log.v("SDL", "pixel format RGBX_8888");
        sdlFormat = 0x16261804; // SDL_PIXELFORMAT_RGBX8888
        break;
      case PixelFormat.RGB_332:
        Log.v("SDL", "pixel format RGB_332");
        sdlFormat = 0x14110801; // SDL_PIXELFORMAT_RGB332
        break;
      case PixelFormat.RGB_565:
        Log.v("SDL", "pixel format RGB_565");
        sdlFormat = 0x15151002; // SDL_PIXELFORMAT_RGB565
        break;
      case PixelFormat.RGB_888:
        Log.v("SDL", "pixel format RGB_888");
        // Not sure this is right, maybe SDL_PIXELFORMAT_RGB24 instead?
        sdlFormat = 0x16161804; // SDL_PIXELFORMAT_RGB888
        break;
      default:
        Log.v("SDL", "pixel format unknown " + format);
        break;
    }

    mWidth = width;
    mHeight = height;
    SDLActivity.onNativeResize(width, height, sdlFormat, mDisplay.getRefreshRate());
    Log.v("SDL", "Window size:" + width + "x" + height);

    // Set mIsSurfaceReady to 'true' *before* making a call to handleResume
    SDLActivity.mIsSurfaceReady = true;
    SDLActivity.onNativeSurfaceChanged();

    if (SDLActivity.mSDLThread == null) {
      // This is the entry point to the C app.
      // Start up the C app thread and enable sensor input for the first time

      final Thread sdlThread = new Thread(new SDLMain(), "SDLThread");
      enableSensor(Sensor.TYPE_ACCELEROMETER, true);
      sdlThread.start();

      // Set up a listener thread to catch when the native thread ends
      SDLActivity.mSDLThread =
          new Thread(
              new Runnable() {
                @Override
                public void run() {
                  try {
                    sdlThread.join();
                  } catch (Exception e) {
                  } finally {
                    // Native thread has finished
                    if (!SDLActivity.mExitCalledFromJava) {
                      SDLActivity.handleNativeExit();
                    }
                  }
                }
              },
              "SDLThreadListener");
      SDLActivity.mSDLThread.start();
    }
  }
  public void run() {
    Log.i(getClass().getSimpleName(), "Starting thread (run method started)");

    boolean gameOverTriggered = false;
    long currentFrameIndex = 0;
    long currentFrameTimesAccumulated = 0;
    long lastLoopStartTime = System.currentTimeMillis();
    // Debug.startMethodTracing( "escapePitTrace" );

    // gameResult.status = GameResultStatus.RUNNING;

    loadFirstLevel();

    if (orderedSubSystems == null)
      throw new IllegalStateException(
          "Cannot start a MainRunThread until you've loaded all SubSystems; try calling loadAllCoreSubSystems() first");

    /**
     * ********************************************************************* START OF MAIN BODY OF
     * RUN LOOP **********************************************************************
     */
    while (myThread != null) {
      long loopStartTime = System.currentTimeMillis();
      long lastFrameTime = loopStartTime - lastLoopStartTime;
      currentFrameTimesAccumulated += lastFrameTime;

      Canvas c = surfaceView.getHolder().lockCanvas(null);
      try {
        /**
         * Critical: lots of things in rendering depend on the size / shape of the Canvas; => we
         * must make sure the renderingSystem has the latest, current, correct Canvas before we do
         * anything else
         */
        renderingSystem.canvas = c;

        for (SubSystem system : orderedSubSystems) {
          system.processOneGameTick(lastFrameTime);
        }

        synchronized (surfaceView.getHolder()) {
          renderingSystem.drawBackground();
          renderingSystem.processOneGameTick(lastFrameTime);
        }

        Thread.sleep(5);
      } catch (GameOverError goe) {
        Log.i(getClass().getSimpleName(), "GameOver; killing thread");

        myThread = null;

        Log.i(getClass().getSimpleName(), "GameOver; locking Entity System");
        es.freeze();

        gameOverTriggered = true;
      } catch (Throwable t) {
        Log.e(
            getClass().getSimpleName(),
            "Inside main draw loop, a major exception, killing draw thread:" + t);
        t.printStackTrace();
        myThread = null;
      } finally {
        // ANDROID EXAMPLE CODE COMMENT:
        // do this in a finally so that if an exception is thrown
        // during the above, we don't leave the Surface in an
        // inconsistent state
        if (c != null) {
          surfaceView.getHolder().unlockCanvasAndPost(c);
        }

        currentFrameIndex++;
        lastLoopStartTime = loopStartTime;
        int frameTimesPerSample = 25;
        if (currentFrameIndex % frameTimesPerSample == 0) {
          // DEBUG: Log.i( getClass().getSimpleName(), "Averaged frame rate = " +
          // frameTimesPerSample * 1000 / currentFrameTimesAccumulated + " fps" );
          currentFrameTimesAccumulated = 0;
        }
      }
    }
    // Debug.stopMethodTracing();

    if (gameOverTriggered) {
      /**
       * Another bad design decision from the Android authors? This is not a great way to manage
       * inter-Activity communication (is there a better way?)
       */
      Intent i = parentActivity.getIntent();
      parentActivity.setResult(Activity.RESULT_OK, i);
      parentActivity.finish();
    }

    Log.i(
        getClass().getSimpleName(),
        "Thread-stop COMPLETE: (run method expired; mythread was set to null)");
  }
 public int onStartCommand(Intent intent, int flags, int startId) {
   scanThread = new Thread(this);
   scanThread.start();
   return START_STICKY;
 }
  public void run() {
    int i,
        j,
        storedValues,
        sleepTime = 3000,
        timeoutCtr = 0,
        lastFlags = -1,
        trackCnt = 0,
        lastLocMethod = -5;
    String bssid;
    WMapEntry currEntry;
    DataOutputStream out;
    FileInputStream in;

    while (running) {
      try {
        if (scanData.getNoGPSExitInterval() > 0) {
          if (System.currentTimeMillis() > lastGPSTime + scanData.getNoGPSExitInterval()) {
            break;
          }
        }
        if (ScanService.scanData.getThreadMode() == OWMapAtAndroid.THREAD_MODE_UPLOAD) {
          if ((m_uploadThread != null) && (m_uploadThread.isUploading()))
            OWMapAtAndroid.sendMessage(
                ScannerHandler.MSG_SIMPLE_ALERT,
                0,
                0,
                getResources().getText(R.string.upload_in_progress));
          else m_uploadThread = new UploadThread(scanData, this, SP, false, notification, null);
          ScanService.scanData.setThreadMode(OWMapAtAndroid.THREAD_MODE_SCAN);
        } else {
          if ((posState == 0) && (scanData != null) && (scanData.isScanningEnabled())) {
            posState = 1;
            timeoutCtr = 0;
            if (scanData.getFlags() != lastFlags) {
              if ((scanData.getFlags() & OWMapAtAndroid.FLAG_NO_NET_ACCESS) == 0)
                scanData.getWifiManager().createWifiLock(WifiManager.WIFI_MODE_FULL, "OpenWLANMap");
              else
                scanData
                    .getWifiManager()
                    .createWifiLock(WifiManager.WIFI_MODE_SCAN_ONLY, "OpenWLANMap");
              lastFlags = scanData.getFlags();
            }
            if ((scanData.getFlags() & OWMapAtAndroid.FLAG_NO_NET_ACCESS) == 0)
              myWLocate.wloc_request_position(WLocate.FLAG_NO_IP_LOCATION);
            else {
              myWLocate.wloc_request_position(
                  WLocate.FLAG_NO_NET_ACCESS | WLocate.FLAG_NO_IP_LOCATION);
              //                  stopGoogleLocation();
            }
          } else if (!scanData.isScanningEnabled()) {
            try {
              trackCnt += 1500;
              Thread.sleep(1500);
            } catch (InterruptedException ie) {

            }
          }
          if (posState == 1) {
            // sleep while waiting for result
            try {
              trackCnt += 2500;
              java.lang.Thread.sleep(2500); // is interrupted from result handler
              timeoutCtr++;
              if (timeoutCtr > 3) {
                timeoutCtr = 0;
                posState = 0;
              }
            } catch (InterruptedException ie) {
            }
          }
          if ((posState == 2) || (posState == 100)) {
            loc_info locationInfo;
            NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

            locationInfo = myWLocate.last_location_info();
            if (lastLocMethod != locationInfo.lastLocMethod) {
              scanData.getmView().setMode(locationInfo.lastLocMethod);
              scanData.getmView().postInvalidate();
              lastLocMethod = locationInfo.lastLocMethod;
            }
            if (posState == 100) locationInfo.lastLocMethod = -1;
            OWMapAtAndroid.sendMessage(
                OWMapAtAndroid.ScannerHandler.MSG_UPD_LOC_STATE,
                (int) (lastRadius * 1000),
                locationInfo.lastLocMethod,
                locationInfo);

            if (SP.getBoolean("autoConnect", false)) {
              if (!mWifi.isConnected()) {
                for (i = 0; i < locationInfo.wifiScanResult.size(); i++) {
                  ScanResult result;

                  result = locationInfo.wifiScanResult.get(i);
                  result.capabilities = result.capabilities.toUpperCase(Locale.US);
                  if ((isFreeHotspot(result) & WMapEntry.FLAG_IS_FREIFUNK) != 0) {
                    // auto-connect to this open network

                    WifiConfiguration wifiConfig = new WifiConfiguration();
                    wifiConfig.BSSID = result.BSSID;
                    wifiConfig.priority = 1;
                    wifiConfig.allowedKeyManagement.set(KeyMgmt.NONE);
                    wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
                    wifiConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
                    wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                    wifiConfig.status = WifiConfiguration.Status.ENABLED;

                    int netId = scanData.getWifiManager().addNetwork(wifiConfig);
                    scanData.getWifiManager().enableNetwork(netId, true);
                  }
                }
              }
            }
            if ((posValid)
                && (locationInfo.wifiScanResult != null)
                && (locationInfo.wifiScanResult.size() > 0)) {
              boolean foundExisting;

              for (i = 0; i < locationInfo.wifiScanResult.size(); i++) {
                ScanResult result;

                result = locationInfo.wifiScanResult.get(i);
                bssid = result.BSSID.replace(":", "").replace(".", "").toUpperCase(Locale.US);
                if (bssid.equalsIgnoreCase("000000000000")) break;
                foundExisting = false;
                scanData.getLock().lock();
                for (j = 0; j < scanData.getWmapList().size(); j++) {
                  currEntry = scanData.getWmapList().elementAt(j);
                  if (currEntry.getBSSID().equalsIgnoreCase(bssid)) {
                    currEntry.setPos(lastLat, lastLon);
                    foundExisting = true;
                    break;
                  }
                }
                if (!foundExisting) {
                  String lowerSSID;

                  storedValues = scanData.incStoredValues();
                  scanData.getmView().setValue(storedValues);
                  scanData.getmView().postInvalidate();
                  currEntry = new WMapEntry(bssid, result.SSID, lastLat, lastLon, storedValues);
                  lowerSSID = result.SSID.toLowerCase(Locale.US);
                  if ((lowerSSID.endsWith("_nomap"))
                      || // Google unsubscibe option
                      (lowerSSID.contains("iphone"))
                      || // mobile AP
                      (lowerSSID.contains("android"))
                      || // mobile AP
                      (lowerSSID.contains("motorola"))
                      || // mobile AP
                      (lowerSSID.contains("deinbus.de"))
                      || // WLAN network on board of German bus
                      (lowerSSID.contains("fernbus"))
                      || // WLAN network on board of German bus
                      (lowerSSID.contains("flixbus"))
                      || // WLAN network on board of German bus
                      (lowerSSID.contains("ecolines"))
                      || // WLAN network on board of German bus
                      (lowerSSID.contains("eurolines_wifi"))
                      || // WLAN network on board of German bus
                      (lowerSSID.contains("contiki-wifi"))
                      || // WLAN network on board of bus
                      (lowerSSID.contains("guest@ms "))
                      || // WLAN network on Hurtigruten ships
                      (lowerSSID.contains("admin@ms "))
                      || // WLAN network on Hurtigruten ships
                      (lowerSSID.contains("nsb_interakti"))
                      || // WLAN network in NSB trains
                      (lowerSSID.equals("southwestwifi"))) // WLAN network on Southwest flights
                  currEntry.setFlags(currEntry.getFlags() | WMapEntry.FLAG_IS_NOMAP);
                  else currEntry.setFlags(currEntry.getFlags() | isFreeHotspot(result));
                  if (isFreeHotspot(currEntry.getFlags())) scanData.incFreeHotspotWLANs();
                  scanData.getWmapList().add(currEntry);
                  if ((scanData.getUploadThres() > 0)
                      && (storedValues > scanData.getUploadThres())) {
                    if ((m_uploadThread == null) || (!m_uploadThread.isUploading())) {
                      if (mWifi.isConnected()) {
                        m_uploadThread =
                            new UploadThread(scanData, this, SP, true, notification, mWifi);
                      }
                    }
                  }
                }
                result.capabilities = result.capabilities.toUpperCase(Locale.US);
                scanData.getLock().unlock();
              }
            }
            scanData.getLock().lock();
            for (j = 0; j < scanData.getWmapList().size(); j++) {
              currEntry = scanData.getWmapList().elementAt(j);
              if ((currEntry.getLastUpdate() + OWMapAtAndroid.RECV_TIMEOUT
                      < System.currentTimeMillis())
                  && ((currEntry.getFlags() & WMapEntry.FLAG_IS_VISIBLE) == 0)) {
                scanData.getWmapList().remove(j);
                if (currEntry.posIsValid()) {
                  int padBytes = 0, k;

                  try {
                    in = scanData.getCtx().openFileInput(OWMapAtAndroid.WSCAN_FILE);
                    padBytes = in.available() % 28;
                    in.close();
                    if (padBytes > 0) padBytes = 28 - padBytes;
                  } catch (IOException ioe) {
                    ioe.printStackTrace();
                  }
                  try {
                    out =
                        new DataOutputStream(
                            scanData
                                .getCtx()
                                .openFileOutput(
                                    OWMapAtAndroid.WSCAN_FILE,
                                    Context.MODE_PRIVATE | Context.MODE_APPEND));
                    if (padBytes > 0) for (k = 0; k < padBytes; k++) out.writeByte(0);
                    out.write(currEntry.getBSSID().getBytes(), 0, 12);
                    if ((currEntry.getFlags() & WMapEntry.FLAG_IS_NOMAP) != 0) {
                      out.writeDouble(0.0);
                      out.writeDouble(0.0);
                    } else {
                      out.writeDouble(currEntry.getLat());
                      out.writeDouble(currEntry.getLon());
                    }
                    out.close();
                  } catch (IOException ioe) {
                    ioe.printStackTrace();
                  }

                  if ((currEntry.getFlags()
                          & (WMapEntry.FLAG_IS_FREIFUNK | WMapEntry.FLAG_IS_NOMAP))
                      == WMapEntry.FLAG_IS_FREIFUNK) {
                    padBytes = 0;
                    try {
                      in = scanData.getCtx().openFileInput(OWMapAtAndroid.WFREI_FILE);
                      padBytes = in.available() % 12;
                      in.close();
                      if (padBytes > 0) padBytes = 12 - padBytes;
                    } catch (IOException ioe) {
                      ioe.printStackTrace();
                    }
                    try {
                      out =
                          new DataOutputStream(
                              scanData
                                  .getCtx()
                                  .openFileOutput(
                                      OWMapAtAndroid.WFREI_FILE,
                                      Context.MODE_PRIVATE | Context.MODE_APPEND));
                      if (padBytes > 0) for (k = 0; k < padBytes; k++) out.writeByte(0);
                      out.write(currEntry.getBSSID().getBytes(), 0, 12);
                      out.close();
                    } catch (IOException ioe) {
                      ioe.printStackTrace();
                    }
                  }
                }
              }
              //               flushData(false);
            }
            scanData.getLock().unlock();
            m_lastSpeed = locationInfo.lastSpeed;
            if (!SP.getBoolean("adaptiveScanning", true)) sleepTime = 500;
            else if (locationInfo.lastSpeed > 90) sleepTime = 350;
            else if (locationInfo.lastSpeed < 0)
              sleepTime = 1300; // no speed information, may be because of WLAN localisation
            else if (locationInfo.lastSpeed < 6) sleepTime = 2500; // user seems to walk
            else {
              double f;

              f = 1.0 - (locationInfo.lastSpeed / 90.0);
              sleepTime = (int) ((1000.0 * f) + 350);
            }

            try {
              trackCnt += sleepTime;
              java.lang.Thread.sleep(sleepTime); // sleep between scans
            } catch (InterruptedException ie) {

            }
            posState = 0;
          }
        }
      } catch (NullPointerException npe) // in case the parent activity dies too fast
      {
        npe.printStackTrace();
      }
      if ((trackCnt > 500000) && (lastLat != 0) && (lastLon != 0)) {
        if (SP.getBoolean("track", false)) new UploadPositionTask().execute(null, null, null);
        trackCnt = 0;
      }
    }
    onDestroy(); // remove all resources (in case the thread was stopped due to some other reason
  }
  public void onCreate() {
    int flags, screenLightVal = 1;
    Sensor mSensor;
    List<Sensor> sensors;

    if (scanData == null) return; // no ScanData, not possible to run correctly...

    PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
    SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    try {
      screenLightVal = Integer.parseInt(SP.getString("screenLight", "2"));
    } catch (NumberFormatException nfe) {
    }
    if (screenLightVal == 1) flags = PowerManager.PARTIAL_WAKE_LOCK;
    else if (screenLightVal == 3) flags = PowerManager.FULL_WAKE_LOCK;
    else flags = PowerManager.SCREEN_DIM_WAKE_LOCK;
    wl = pm.newWakeLock(flags, "OpenWLANMap");
    wl.acquire();
    while (myWLocate == null) {
      try {
        myWLocate = new MyWLocate(this);
        break;
      } catch (IllegalArgumentException iae) {
        myWLocate = null;
      }
      try {
        Thread.sleep(100);
      } catch (InterruptedException ie) {
      }
    }

    try {
      scanData.setUploadThres(Integer.parseInt(SP.getString("autoUpload", "0")));
    } catch (NumberFormatException nfe) {
    }
    try {
      scanData.setNoGPSExitInterval(
          Integer.parseInt(SP.getString("noGPSExitInterval", "0")) * 60 * 1000);
    } catch (NumberFormatException nfe) {
    }

    Intent intent = new Intent(this, OWMapAtAndroid.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent pendIntent = PendingIntent.getActivity(this, 0, intent, 0);

    notification =
        new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.icon)
            .setContentTitle(getResources().getText(R.string.app_name))
            .setContentText("")
            .setContentIntent(pendIntent)
            .build();

    notification.flags |= Notification.FLAG_NO_CLEAR;
    notification.flags |= Notification.FLAG_ONGOING_EVENT;
    startForeground(1703, notification);

    getScanData().setService(this);
    getScanData().setmView(new HUDView(this));
    getScanData().getmView().setValue(getScanData().incStoredValues());
    WindowManager.LayoutParams params =
        new WindowManager.LayoutParams(
            WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
            WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
                | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
            PixelFormat.TRANSLUCENT);
    params.gravity = Gravity.LEFT | Gravity.BOTTOM;
    params.setTitle("Load Average");
    WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
    wm.addView(getScanData().getmView(), params);

    sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);

    sensorManager.registerListener(
        this,
        sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
        SensorManager.SENSOR_DELAY_GAME);
    sensorManager.registerListener(
        this,
        sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
        SensorManager.SENSOR_DELAY_GAME);
    sensors = sensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER);
    mSensor = sensors.get(0);
    getScanData().getTelemetryData().setAccelMax(mSensor.getMaximumRange());
    telemetryDir = Environment.getExternalStorageDirectory().getPath() + "/telemetry/";
    File dir = new File(telemetryDir);
    dir.mkdir();

    connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
  }
 @Override
 public void start() {
   // TODO: Implement this method
   super.start();
 }
  @Override
  public void run() {
    // TODO: Implement this method
    super.run();
    start = 0;
    end = 0;

    LoadPageImage imp;
    HashMap<String, Object> map = new HashMap<String, Object>();
    try {

      start = html.indexOf("page-submission", 0);
      start = html.indexOf("small_url =", start);
      end = html.indexOf("var full_url", start);
      s = "http:" + html.substring(start + 13, end - 3);
      final String img = s;
      map.put("img", s);
      end = html.indexOf(">Download<", end);
      start = html.lastIndexOf("href=", end);
      s = "http:" + html.substring(start + 6, end - 1);
      map.put("download", s);
      int std = s.lastIndexOf("/");
      String name = PageActivity.HOME_PATH + s.substring(std + 1, s.length());
      File f = new File(name);
      if (f.exists()) {
        Bitmap b;
        b = BitmapFactory.decodeFile(f.getPath());
        map.put("bitmap", b);
      } else {
        name = PageActivity.HOME_PATH + "s-" + s.substring(std + 1, s.length());
        f = new File(name);
        if (f.exists()) {
          Bitmap b;
          b = BitmapFactory.decodeFile(f.getPath());
          map.put("bitmap", b);
        } else {
          imp = new LoadPageImage();
          imp.start(img, -1, now);
        }
      }
      end = html.indexOf("Main Gallery", end);
      start = html.lastIndexOf("href=", end);
      end = html.indexOf("class=", start);
      s = html.substring(start + 6, end - 2);
      map.put("gallery", s);
      start = html.indexOf("<tr>\n<td", end);
      start = html.indexOf("<b>", start);
      end = html.indexOf("</b>", start);
      s = html.substring(start + 3, end);
      map.put("title", s);
      start = html.indexOf("href=", start);
      end = html.indexOf("><img", start);
      s = "http://www.furaffinity.net" + html.substring(start + 6, end - 1);
      map.put("userlink", s);
      start = html.indexOf("alt=", end);
      end = html.indexOf("\" src", start);
      s = html.substring(start + 5, end);
      map.put("username", s);
      start = html.indexOf("src=", end);
      end = html.indexOf("></a>", start);
      s = "http:" + html.substring(start + 5, end - 1);
      imp = new LoadPageImage();
      imp.start(s, -2, now);
      map.put("usericon", s);
      start = html.indexOf("<br/><br/>", end);
      end = html.indexOf("</td>\n</tr>", start);
      int st = start;
      int ed = start - 2;
      String t = "";
      s = "";
      while (html.indexOf("<br/>", st + 1) < end - 6) {
        st = html.indexOf("<br/>", ed);
        ed = html.indexOf("<br/>", st + 1);
        t = html.substring(st + 5, ed);
        if (t.indexOf("href=") != -1) {
          int i1;
          int i2;
          i1 = t.indexOf("alt=\"", 0);
          i2 = t.indexOf("\"/>", i1);
          try {
            t = " @ " + t.substring(i1 + 5, i2) + " ";
          } catch (Exception e) {
            t = "";
          }
        }
        t = t.replace("</td>", "");
        t = t.replace("<td>", "");
        t = t.replace("</tr>", "");
        t = t.replace("<tr>", "");
        t = t.replace("</table>", "");
        t = t.replace("<table>", "");
        t = t.replace("<br>", "");
        t = t.replace("</br>", "");
        if (t.indexOf("bbcode") != -1) {
          t = "";
        }
        s += t;
      }

      map.put("info", s);
      if (now == PageActivity.now) {
        Message msg = Message.obtain();
        msg.arg2 = now;
        msg.obj = map;
        msg.what = 5;
        PageActivity.hander.sendMessage(msg);
      }
    } catch (Exception e) {
      File f = new File(PageActivity.HOME_PATH + "LOG/lastPage.html");
      if (f.exists()) {
        f.renameTo(new File(PageActivity.HOME_PATH + "LOG/lastErrorPage.html"));
      }
      Message msg = Message.obtain();
      msg.arg2 = now;
      msg.obj = map;
      msg.what = 998;
      PageActivity.hander.sendMessage(msg);
    }
  }