public void wait_ble(int i) { try { Thread.sleep(i); } catch (Exception e) { // ignore } }
/** Method that reads the requested file. */ private void writeFile() { try { // Configure the writer AsyncWriter writer = new AsyncWriter(); // Create the writable command WriteExecutable cmd = CommandHelper.write(this, this.mFso.getFullPath(), writer, null); // Obtain access to the buffer (IMP! don't close the buffer here, it's manage // by the command) OutputStream os = cmd.createOutputStream(); try { // Retrieve the text from the editor String text = this.mEditor.getText().toString(); ByteArrayInputStream bais = new ByteArrayInputStream(text.getBytes()); text = null; try { // Buffered write byte[] data = new byte[this.mBufferSize]; int read = 0; while ((read = bais.read(data, 0, this.mBufferSize)) != -1) { os.write(data, 0, read); } } finally { try { bais.close(); } catch (Exception e) { /** NON BLOCK* */ } } } finally { // Ok. Data is written or ensure buffer close cmd.end(); } // Sleep a bit Thread.sleep(150L); // Is error? if (writer.mCause != null) { // Something was wrong. The file probably is corrupted DialogHelper.showToast(this, R.string.msgs_operation_failure, Toast.LENGTH_SHORT); } else { // Success. The file was saved DialogHelper.showToast(this, R.string.editor_successfully_saved, Toast.LENGTH_SHORT); setDirty(false); // Send a message that allow other activities to update his data Intent intent = new Intent(FileManagerSettings.INTENT_FILE_CHANGED); intent.putExtra(FileManagerSettings.EXTRA_FILE_CHANGED_KEY, this.mFso.getFullPath()); sendBroadcast(intent); } } catch (Exception e) { // Something was wrong, but the file was NOT written DialogHelper.showToast(this, R.string.msgs_operation_failure, Toast.LENGTH_SHORT); return; } }
@Override public void run() { while (flag) { myDraw(); try { Thread.sleep(50); } catch (InterruptedException e) { } } }
/** 线程运行的方法,当线程start后执行 */ @Override public void run() { while (flag) { mDraw(); // 调用自定义的绘图方法 mGameLogic(); // 调用自定义的逻辑方法 try { Thread.sleep(50); // 让线程休息50毫秒 } catch (InterruptedException e) { e.printStackTrace(); } } }
public void handleMessage(Message msg) { mValue++; mText.setText(Integer.toString(mValue)); try { Thread.sleep(50); } catch (InterruptedException e) {; } if (mValue < 100 && mQuit == false) { mProgress.setProgress(mValue); mHandler.sendEmptyMessage(0); } else { dismissDialog(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; } } }
@Override protected Boolean doInBackground(String... params) { try { if (stop) return true; String maxText = "Disconnected....."; // strProgressTextSrc + "...."; int len = maxText.length(); playerStatusText.getPaint().getTextBounds(maxText, 0, len, bounds); strProgressText = strProgressTextSrc + "..."; Runnable uiRunnable = null; uiRunnable = new Runnable() { public void run() { if (stop) return; playerStatusText.setText(strProgressText); RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) playerStatusText.getLayoutParams(); layoutParams.width = bounds.width(); playerStatusText.setLayoutParams(layoutParams); playerStatusText.setGravity(Gravity.NO_GRAVITY); synchronized (this) { this.notify(); } } }; int nCount = 4; do { try { Thread.sleep(300); } catch (InterruptedException e) { stop = true; } if (stop) break; if (nCount <= 3) { strProgressText = strProgressTextSrc; for (int i = 0; i < nCount; i++) strProgressText = strProgressText + "."; } synchronized (uiRunnable) { runOnUiThread(uiRunnable); try { uiRunnable.wait(); } catch (InterruptedException e) { stop = true; } } if (stop) break; nCount++; if (nCount > 3) { nCount = 1; strProgressText = strProgressTextSrc; } } while (!isCancelled()); } catch (Exception e) { } return true; }
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); }
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 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)"); }