@Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: mMoveOutside = false; mFingerRect = new Rect(getLeft(), getTop(), getRight(), getBottom()); mTouchPoint.set(Math.round(event.getX()), Math.round(event.getY())); mState = StateTouchDown; mStartTime = System.currentTimeMillis(); invalidate(); break; case MotionEvent.ACTION_MOVE: if (!mFingerRect.contains(getLeft() + (int) event.getX(), getTop() + (int) event.getY())) { mMoveOutside = true; mState = StateNormal; invalidate(); } break; case MotionEvent.ACTION_UP: if (!mMoveOutside) { mState = StateTouchUp; mStartTime = System.currentTimeMillis(); invalidate(); performClick(); } break; case MotionEvent.ACTION_CANCEL: mState = StateNormal; invalidate(); break; } return true; }
@Override protected void onDraw(Canvas canvas) { // draw the background and color wheel canvas.drawBitmap(mBackground, mBackgroundPosition.x, mBackgroundPosition.y, null); canvas.drawBitmap(mWheel, mWheelPosition.x, mWheelPosition.y, null); // setup paint for the gradient filling Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); paint.setStyle(Paint.Style.FILL); paint.setStrokeWidth(2.0f); // create a shader that will show the range of brightness settings float[] gradientStartColor = new float[3]; float[] gradientEndColor = new float[3]; System.arraycopy(mNewColor, 0, gradientStartColor, 0, mNewColor.length); System.arraycopy(mNewColor, 0, gradientEndColor, 0, mNewColor.length); gradientStartColor[2] = 1.0f; gradientEndColor[2] = 0.0f; Shader gradientShader = new LinearGradient( (float) (mWheelPosition.x + mRadius), mWheelPosition.y, mOuterArcRect.right, mWheelPosition.y + mWheel.getHeight(), Color.HSVToColor(gradientStartColor), Color.HSVToColor(gradientEndColor), Shader.TileMode.MIRROR); paint.setShader(gradientShader); canvas.drawPath(mArcPath, paint); drawHSCrosshairs(canvas); drawBrightnessIndicator(canvas); }
// Load the .so static { System.loadLibrary("SDL"); // System.loadLibrary("SDL_image"); // System.loadLibrary("SDL_mixer"); // System.loadLibrary("SDL_ttf"); System.loadLibrary("main"); }
// Load the .so static { System.loadLibrary("SDL2"); System.loadLibrary("SDL2_image"); // System.loadLibrary("SDL2_mixer"); // System.loadLibrary("SDL2_net"); System.loadLibrary("SDL2_ttf"); System.loadLibrary("main"); }
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); }
@Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { long start = System.currentTimeMillis(); if (changed) { buildLayout(); } // Logger.d(TAG, "onLayout in " + (System.currentTimeMillis() - start) + " ms"); }
public HSBColorPickerView(Context context, AttributeSet attrs, int defStyle, int startingColor) { super(context, attrs, defStyle); mPreviousColor = new float[3]; mNewColor = new float[3]; Color.colorToHSV(startingColor, mPreviousColor); System.arraycopy(mPreviousColor, 0, mNewColor, 0, mPreviousColor.length); mBackground = BitmapFactory.decodeResource(getResources(), R.drawable.color_picker_wheel_background); mWheel = BitmapFactory.decodeResource(getResources(), R.drawable.color_wheel); }
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { long start = System.currentTimeMillis(); if (IS_LARGE) { setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), getPx(80)); } else { setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), getPx(68)); } // Logger.d(TAG, "onMeasure in " + (System.currentTimeMillis() - start) + " ms"); }
private void checkAndLaunchUpdate() { Log.i(LOG_FILE_NAME, "Checking for an update"); int statusCode = 8; // UNEXPECTED_ERROR File baseUpdateDir = null; if (Build.VERSION.SDK_INT >= 8) baseUpdateDir = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS); else baseUpdateDir = new File(Environment.getExternalStorageDirectory().getPath(), "download"); File updateDir = new File(new File(baseUpdateDir, "updates"), "0"); File updateFile = new File(updateDir, "update.apk"); File statusFile = new File(updateDir, "update.status"); if (!statusFile.exists() || !readUpdateStatus(statusFile).equals("pending")) return; if (!updateFile.exists()) return; Log.i(LOG_FILE_NAME, "Update is available!"); // Launch APK File updateFileToRun = new File(updateDir, getPackageName() + "-update.apk"); try { if (updateFile.renameTo(updateFileToRun)) { String amCmd = "/system/bin/am start -a android.intent.action.VIEW " + "-n com.android.packageinstaller/.PackageInstallerActivity -d file://" + updateFileToRun.getPath(); Log.i(LOG_FILE_NAME, amCmd); Runtime.getRuntime().exec(amCmd); statusCode = 0; // OK } else { Log.i(LOG_FILE_NAME, "Cannot rename the update file!"); statusCode = 7; // WRITE_ERROR } } catch (Exception e) { Log.i(LOG_FILE_NAME, "error launching installer to update", e); } // Update the status file String status = statusCode == 0 ? "succeeded\n" : "failed: " + statusCode + "\n"; OutputStream outStream; try { byte[] buf = status.getBytes("UTF-8"); outStream = new FileOutputStream(statusFile); outStream.write(buf, 0, buf.length); outStream.close(); } catch (Exception e) { Log.i(LOG_FILE_NAME, "error writing status file", e); } if (statusCode == 0) System.exit(0); }
public void addEnvToIntent(Intent intent) { Map<String, String> envMap = System.getenv(); Set<Map.Entry<String, String>> envSet = envMap.entrySet(); Iterator<Map.Entry<String, String>> envIter = envSet.iterator(); int c = 0; while (envIter.hasNext()) { Map.Entry<String, String> entry = envIter.next(); intent.putExtra("env" + c, entry.getKey() + "=" + entry.getValue()); c++; } }
private void saveData(TelemetryData data) { PrintWriter out; boolean newFile = false; if (saveCnt > 25000) { File logFile; int i; logFile = new File(telemetryDir + 99 + ".log"); logFile.delete(); newFile = true; for (i = 99; i > 0; i--) { logFile = new File(telemetryDir + (i - 1) + ".log"); logFile.renameTo(new File(telemetryDir + i + ".log")); } saveCnt = 0; } try { String text = ""; SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.GERMAN); saveCnt++; out = new PrintWriter(new FileOutputStream(telemetryDir + "0.log", true)); if (newFile) { text = "Time\tLatitude\tLongitude\tSpeed\tAcceleration X\tAcceleration Y\tAcceleration Z\tCoG\tOrientation Y\tOrientation Z\n\n"; out.print(text); } text = dateFormat.format(new Date(System.currentTimeMillis())) + "\t"; if (posValid) text = text + lastLat + "\t" + lastLon + "\t" + m_lastSpeed + "\t"; else text = text + "-\t-\t-\t"; text = text + data.getAccelX() + "\t" + data.getAccelY() + "\t" + data.getAccelZ() + "\t" + data.CoG + "\t" + data.getOrientY() + "\t" + data.getOrientZ() + "\n\n"; out.print(text); out.close(); } catch (IOException ioe) { } }
public void onSensorChanged(SensorEvent event) { synchronized (this) { switch (event.sensor.getType()) { case Sensor.TYPE_ACCELEROMETER: scanData.getTelemetryData().addAccel(event.values[0], event.values[1], event.values[2]); break; case Sensor.TYPE_ORIENTATION: scanData.getTelemetryData().addOrient(event.values[0], event.values[1], event.values[2]); break; } if (lastTelemetryTime == 0) lastTelemetryTime = System.currentTimeMillis(); else if (System.currentTimeMillis() - lastTelemetryTime > 750) { TelemetryData submitData = new TelemetryData(); submitData.set(scanData.getTelemetryData()); if (scanData.isStoreTele()) saveData(submitData); scanData.getTelemetryData().reset(); OWMapAtAndroid.sendMessage(OWMapAtAndroid.ScannerHandler.MSG_TELEMETRY, 0, 0, submitData); lastTelemetryTime = System.currentTimeMillis(); } } }
@Override public boolean onKeyUp(int keyCode, KeyEvent event) { if (myKeyUnderTracking != -1) { if (myKeyUnderTracking == keyCode) { final boolean longPress = System.currentTimeMillis() > myTrackingStartTime + ViewConfiguration.getLongPressTimeout(); ZLApplication.Instance().runActionByKey(keyCode, longPress); } myKeyUnderTracking = -1; return true; } else { final ZLKeyBindings bindings = ZLApplication.Instance().keyBindings(); return bindings.hasBinding(keyCode, false) || bindings.hasBinding(keyCode, true); } }
@Override protected void onNewIntent(Intent intent) { if (checkLaunchState(LaunchState.GeckoExiting)) { // We're exiting and shouldn't try to do anything else just incase // we're hung for some reason we'll force the process to exit System.exit(0); return; } final String action = intent.getAction(); if (ACTION_DEBUG.equals(action) && checkAndSetLaunchState(LaunchState.Launching, LaunchState.WaitForDebugger)) { mMainHandler.postDelayed( new Runnable() { public void run() { Log.i(LOG_FILE_NAME, "Launching from debug intent after 5s wait"); setLaunchState(LaunchState.Launching); launch(null); } }, 1000 * 5 /* 5 seconds */); Log.i(LOG_FILE_NAME, "Intent : ACTION_DEBUG - waiting 5s before launching"); return; } if (checkLaunchState(LaunchState.WaitForDebugger) || launch(intent)) return; if (Intent.ACTION_MAIN.equals(action)) { Log.i(LOG_FILE_NAME, "Intent : ACTION_MAIN"); GeckoAppShell.sendEventToGecko(new GeckoEvent("")); } else if (Intent.ACTION_VIEW.equals(action)) { String uri = intent.getDataString(); GeckoAppShell.sendEventToGecko(new GeckoEvent(uri)); Log.i(LOG_FILE_NAME, "onNewIntent: " + uri); } else if (ACTION_WEBAPP.equals(action)) { String uri = intent.getStringExtra("args"); GeckoAppShell.sendEventToGecko(new GeckoEvent(uri)); Log.i(LOG_FILE_NAME, "Intent : WEBAPP - " + uri); } else if (ACTION_BOOKMARK.equals(action)) { String args = intent.getStringExtra("args"); GeckoAppShell.sendEventToGecko(new GeckoEvent(args)); Log.i(LOG_FILE_NAME, "Intent : BOOKMARK - " + args); } }
protected void wloc_return_position( int ret, double lat, double lon, float radius, short ccode) { posValid = false; if (ret == WLocate.WLOC_OK) { lastGPSTime = System.currentTimeMillis(); if (radius < OWMapAtAndroid.MAX_RADIUS) { if (GeoUtils.latlon2dist(lat, lon, lastLat, lastLon) < 10) { posValid = true; // use the position only when there is no too big jump in distance- elsewhere // it could be a GPS bug ScanService.getScanData().setLatLon(lastLat, lastLon); } lastLat = lat; lastLon = lon; } lastRadius = radius; } else { lastRadius = -1; } posState = 2; scanThread.interrupt(); }
@Override public boolean onKeyDown(int keyCode, KeyEvent event) { final ZLApplication application = ZLApplication.Instance(); final ZLKeyBindings bindings = application.keyBindings(); if (bindings.hasBinding(keyCode, true) || bindings.hasBinding(keyCode, false)) { if (myKeyUnderTracking != -1) { if (myKeyUnderTracking == keyCode) { return true; } else { myKeyUnderTracking = -1; } } if (bindings.hasBinding(keyCode, true)) { myKeyUnderTracking = keyCode; myTrackingStartTime = System.currentTimeMillis(); return true; } else { return application.runActionByKey(keyCode, false); } } else { return false; } }
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 }
@Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); int radius = 0; int shadowColor = changeColorAlpha(mShadowColor, MIN_SHADOW_COLOR_ALPHA); long elapsed = System.currentTimeMillis() - mStartTime; switch (mState) { case StateNormal: shadowColor = changeColorAlpha(mShadowColor, MIN_SHADOW_COLOR_ALPHA); break; case StateTouchDown: ripplePaint.setAlpha(255); if (elapsed < ANIMATION_DURATION) { radius = Math.round(elapsed * getWidth() / 2 / ANIMATION_DURATION); float shadowAlpha = (MAX_SHADOW_COLOR_ALPHA - MIN_SHADOW_COLOR_ALPHA) * elapsed / ANIMATION_DURATION + MIN_SHADOW_COLOR_ALPHA; shadowColor = changeColorAlpha(mShadowColor, shadowAlpha); } else { radius = getWidth() / 2; shadowColor = changeColorAlpha(mShadowColor, MAX_SHADOW_COLOR_ALPHA); } postInvalidate(); break; case StateTouchUp: if (elapsed < ANIMATION_DURATION) { int alpha = Math.round((ANIMATION_DURATION - elapsed) * 255 / ANIMATION_DURATION); ripplePaint.setAlpha(alpha); radius = getWidth() / 2 + Math.round(elapsed * getWidth() / 2 / ANIMATION_DURATION); float shadowAlpha = (MAX_SHADOW_COLOR_ALPHA - MIN_SHADOW_COLOR_ALPHA) * (ANIMATION_DURATION - elapsed) / ANIMATION_DURATION + MIN_SHADOW_COLOR_ALPHA; shadowColor = changeColorAlpha(mShadowColor, shadowAlpha); } else { mState = StateNormal; radius = 0; ripplePaint.setAlpha(0); shadowColor = changeColorAlpha(mShadowColor, MIN_SHADOW_COLOR_ALPHA); } postInvalidate(); break; } backgroundPaint.setShadowLayer(mShadowRadius, mShadowOffsetX, mShadowOffsetY, shadowColor); canvas.drawRoundRect(getRectF(), mCornerRadius, mCornerRadius, backgroundPaint); canvas.save(); if (mState == StateTouchDown || mState == StateTouchUp) { if (rippleClipPath == null) { rippleClipPath = new Path(); rippleClipPath.addRoundRect(getRectF(), mCornerRadius, mCornerRadius, Path.Direction.CW); } canvas.clipPath(rippleClipPath); } canvas.drawCircle(mTouchPoint.x, mTouchPoint.y, radius, ripplePaint); canvas.restore(); if (mText != null && mText.length() > 0) { int y = (int) (getHeight() / 2 - ((textPaint.descent() + textPaint.ascent()) / 2)); canvas.drawText(mText.toString(), getWidth() / 2, y, textPaint); } }
// Load the .so public void loadLibraries() { for (String lib : getLibraries()) { System.loadLibrary(lib); } }
// Setup @Override protected void onCreate(Bundle savedInstanceState) { Log.v("SDL", "Device: " + android.os.Build.DEVICE); Log.v("SDL", "Model: " + android.os.Build.MODEL); Log.v("SDL", "onCreate():" + mSingleton); super.onCreate(savedInstanceState); SDLActivity.initialize(); // So we can call stuff from static callbacks mSingleton = this; // Load shared libraries String errorMsgBrokenLib = ""; try { loadLibraries(); } catch (UnsatisfiedLinkError e) { System.err.println(e.getMessage()); mBrokenLibraries = true; errorMsgBrokenLib = e.getMessage(); } catch (Exception e) { System.err.println(e.getMessage()); mBrokenLibraries = true; errorMsgBrokenLib = e.getMessage(); } if (mBrokenLibraries) { AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this); dlgAlert.setMessage( "An error occurred while trying to start the application. Please try again and/or reinstall." + System.getProperty("line.separator") + System.getProperty("line.separator") + "Error: " + errorMsgBrokenLib); dlgAlert.setTitle("SDL Error"); dlgAlert.setPositiveButton( "Exit", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { // if this button is clicked, close current activity SDLActivity.mSingleton.finish(); } }); dlgAlert.setCancelable(false); dlgAlert.create().show(); return; } // Set up the surface mSurface = new SDLSurface(getApplication()); if (Build.VERSION.SDK_INT >= 12) { mJoystickHandler = new SDLJoystickHandler_API12(); } else { mJoystickHandler = new SDLJoystickHandler(); } mLayout = new AbsoluteLayout(this); mLayout.addView(mSurface); setContentView(mLayout); }
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)"); }
@Override protected boolean drawBubble(Canvas canvas) { if (messageLayout == null) { requestLayout(); return false; } boolean isAnimated = false; if (messageLayout.isForwarded) { canvas.drawText("Forwarded message", 0, getPx(16), messageLayout.forwardingPaint); canvas.drawText("From", 0, getPx(35), messageLayout.forwardingPaint); canvas.drawText( messageLayout.forwarderNameMeasured, messageLayout.forwardOffset, getPx(35), messageLayout.senderPaint); canvas.save(); canvas.translate(0, getPx(19) * 2); messageLayout.layout.draw(canvas); canvas.restore(); } else { if (!messageLayout.isOut & messageLayout.isGroup) { canvas.drawText(messageLayout.senderNameMeasured, 0, getPx(16), messageLayout.senderPaint); canvas.save(); canvas.translate(0, getPx(19)); messageLayout.layout.draw(canvas); canvas.restore(); } else { messageLayout.layout.draw(canvas); } } if (messageLayout.showState) { if (state == MessageState.PENDING) { canvas.save(); canvas.translate( messageLayout.layoutRealWidth - getPx(12), messageLayout.layoutHeight - getPx(12) - getPx(3)); canvas.drawCircle(getPx(6), getPx(6), getPx(6), clockIconPaint); double time = (System.currentTimeMillis() / 15.0) % (12 * 60); double angle = (time / (6 * 60)) * Math.PI; int x = (int) (Math.sin(-angle) * getPx(4)); int y = (int) (Math.cos(-angle) * getPx(4)); canvas.drawLine(getPx(6), getPx(6), getPx(6) + x, getPx(6) + y, clockIconPaint); x = (int) (Math.sin(-angle * 12) * getPx(5)); y = (int) (Math.cos(-angle * 12) * getPx(5)); canvas.drawLine(getPx(6), getPx(6), getPx(6) + x, getPx(6) + y, clockIconPaint); canvas.restore(); clockOutPaint.setColor(COLOR_NORMAL); isAnimated = true; } else if (state == MessageState.READED && prevState == MessageState.SENT && (SystemClock.uptimeMillis() - stateChangeTime < STATE_ANIMATION_TIME)) { long animationTime = SystemClock.uptimeMillis() - stateChangeTime; float progress = easeStateFade(animationTime / (float) STATE_ANIMATION_TIME); int offset = (int) (getPx(5) * progress); int alphaNew = (int) (progress * 255); bounds( stateSent, messageLayout.layoutRealWidth - stateSent.getIntrinsicWidth() - offset, messageLayout.layoutHeight - stateSent.getIntrinsicHeight() - getPx(3)); stateSent.setAlpha(255); stateSent.draw(canvas); bounds( stateHalfCheck, messageLayout.layoutRealWidth - stateHalfCheck.getIntrinsicWidth() + getPx(5) - offset, messageLayout.layoutHeight - stateHalfCheck.getIntrinsicHeight() - getPx(3)); stateHalfCheck.setAlpha(alphaNew); stateHalfCheck.draw(canvas); clockOutPaint.setColor(COLOR_NORMAL); isAnimated = true; } else { Drawable stateDrawable = getStateDrawable(state); bounds( stateDrawable, messageLayout.layoutRealWidth - stateDrawable.getIntrinsicWidth(), messageLayout.layoutHeight - stateDrawable.getIntrinsicHeight() - getPx(3)); stateDrawable.setAlpha(255); stateDrawable.draw(canvas); if (state == MessageState.READED) { bounds( stateSent, messageLayout.layoutRealWidth - stateSent.getIntrinsicWidth() - getPx(5), messageLayout.layoutHeight - stateDrawable.getIntrinsicHeight() - getPx(3)); stateSent.setAlpha(255); stateSent.draw(canvas); } if (state == MessageState.FAILURE) { clockOutPaint.setColor(COLOR_ERROR); } else { clockOutPaint.setColor(COLOR_NORMAL); } } } else { clockOutPaint.setColor(COLOR_IN); } canvas.drawText( wireframe.date, messageLayout.layoutRealWidth - messageLayout.timeWidth + getPx(6), messageLayout.layoutHeight - getPx(4), clockOutPaint); return isAnimated; }
public void forceQuit() { System.exit(0); }
public void growArray(int oldSize, int newSize) { Drawable[] newDrawables = new Drawable[newSize]; System.arraycopy(mDrawables, 0, newDrawables, 0, oldSize); mDrawables = newDrawables; }
public class ScanService extends Service implements Runnable, SensorEventListener { static boolean running = true; private MyWLocate myWLocate = null; private boolean posValid; private int posState = 0, saveCnt = 1000000; private double lastLat = 0.0, lastLon = 0.0, lastRadius; private Thread scanThread; private PowerManager.WakeLock wl = null; private ConnectivityManager connManager; private SharedPreferences SP; private static ScanData scanData = new ScanData(); private SensorManager sensorManager; private long lastTelemetryTime; private long lastGPSTime = System.currentTimeMillis(); private String telemetryDir; private float m_lastSpeed; private UploadThread m_uploadThread; private Notification notification; public static ScanData getScanData() { return scanData; } @Override public IBinder onBind(Intent arg) { return null; } 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 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 saveData(TelemetryData data) { PrintWriter out; boolean newFile = false; if (saveCnt > 25000) { File logFile; int i; logFile = new File(telemetryDir + 99 + ".log"); logFile.delete(); newFile = true; for (i = 99; i > 0; i--) { logFile = new File(telemetryDir + (i - 1) + ".log"); logFile.renameTo(new File(telemetryDir + i + ".log")); } saveCnt = 0; } try { String text = ""; SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.GERMAN); saveCnt++; out = new PrintWriter(new FileOutputStream(telemetryDir + "0.log", true)); if (newFile) { text = "Time\tLatitude\tLongitude\tSpeed\tAcceleration X\tAcceleration Y\tAcceleration Z\tCoG\tOrientation Y\tOrientation Z\n\n"; out.print(text); } text = dateFormat.format(new Date(System.currentTimeMillis())) + "\t"; if (posValid) text = text + lastLat + "\t" + lastLon + "\t" + m_lastSpeed + "\t"; else text = text + "-\t-\t-\t"; text = text + data.getAccelX() + "\t" + data.getAccelY() + "\t" + data.getAccelZ() + "\t" + data.CoG + "\t" + data.getOrientY() + "\t" + data.getOrientZ() + "\n\n"; out.print(text); out.close(); } catch (IOException ioe) { } } public void onSensorChanged(SensorEvent event) { synchronized (this) { switch (event.sensor.getType()) { case Sensor.TYPE_ACCELEROMETER: scanData.getTelemetryData().addAccel(event.values[0], event.values[1], event.values[2]); break; case Sensor.TYPE_ORIENTATION: scanData.getTelemetryData().addOrient(event.values[0], event.values[1], event.values[2]); break; } if (lastTelemetryTime == 0) lastTelemetryTime = System.currentTimeMillis(); else if (System.currentTimeMillis() - lastTelemetryTime > 750) { TelemetryData submitData = new TelemetryData(); submitData.set(scanData.getTelemetryData()); if (scanData.isStoreTele()) saveData(submitData); scanData.getTelemetryData().reset(); OWMapAtAndroid.sendMessage(OWMapAtAndroid.ScannerHandler.MSG_TELEMETRY, 0, 0, submitData); lastTelemetryTime = System.currentTimeMillis(); } } } public void onAccuracyChanged(Sensor sensor, int accuracy) {} public int onStartCommand(Intent intent, int flags, int startId) { scanThread = new Thread(this); scanThread.start(); return START_STICKY; } class MyWLocate extends WLocate { public MyWLocate(Context ctx) { super(ctx); } protected void wloc_return_position( int ret, double lat, double lon, float radius, short ccode) { posValid = false; if (ret == WLocate.WLOC_OK) { lastGPSTime = System.currentTimeMillis(); if (radius < OWMapAtAndroid.MAX_RADIUS) { if (GeoUtils.latlon2dist(lat, lon, lastLat, lastLon) < 10) { posValid = true; // use the position only when there is no too big jump in distance- elsewhere // it could be a GPS bug ScanService.getScanData().setLatLon(lastLat, lastLon); } lastLat = lat; lastLon = lon; } lastRadius = radius; } else { lastRadius = -1; } posState = 2; scanThread.interrupt(); } } /* private class GoogleLocationListener implements LocationListener { public void onLocationChanged(Location location) { if (location == null) return; lastLocationMillis = SystemClock.elapsedRealtime(); m_lat=location.getLatitude(); m_lon=location.getLongitude(); if (location.hasSpeed()) m_speed=location.getSpeed(); //m/sec else m_speed=-1; if (location.hasAccuracy()) m_radius=location.getAccuracy(); else m_radius=-1; } public void onStatusChanged(String provider, int status, Bundle extras) { int i=0; } public void onProviderEnabled(String provider) { int i=0; } public void onProviderDisabled(String provider) { int i=0; } }; private void startGoogleLocation() { if (locationListener!=null) return; Looper.prepare(); locationListener = new GoogleLocationListener(); location.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,250,0,(LocationListener)locationListener); } private void stopGoogleLocation() { if (locationListener==null) return; location.removeUpdates(locationListener); locationListener=null; } */ private static final String HEXES = "0123456789ABCDEF"; public static String getHex(byte[] raw) { if (raw == null) return null; final StringBuilder hex = new StringBuilder(2 * raw.length); for (final byte b : raw) hex.append(HEXES.charAt((b & 0xF0) >> 4)).append(HEXES.charAt((b & 0x0F))); return hex.toString(); } private boolean isOpenWLAN(ScanResult result) { if ((!result.capabilities.contains("WEP")) && (!result.capabilities.contains("WPA")) && (!result.capabilities.contains("TKIP")) && (!result.capabilities.contains("CCMP")) && (!result.capabilities.contains("PSK"))) return true; return false; } private int isFreeHotspot(ScanResult result) { if (isOpenWLAN(result)) { if (result.SSID.toLowerCase(Locale.US).contains("freifunk")) return WMapEntry.FLAG_IS_FREIFUNK; if (result.SSID.toLowerCase(Locale.US).compareTo("mesh") == 0) return WMapEntry.FLAG_IS_FREIFUNK; if (result.SSID.toLowerCase(Locale.US).compareTo("free-hotspot.com") == 0) return WMapEntry.FLAG_IS_FREEHOTSPOT; if (result.SSID.toLowerCase(Locale.US).contains("the cloud")) return WMapEntry.FLAG_IS_THECLOUD; return WMapEntry.FLAG_IS_OPEN; } return 0; } private boolean isFreeHotspot(int flags) { return (((flags & WMapEntry.FLAG_IS_FREIFUNK) == WMapEntry.FLAG_IS_FREIFUNK) || ((flags & WMapEntry.FLAG_IS_FREEHOTSPOT) == WMapEntry.FLAG_IS_FREEHOTSPOT) || ((flags & WMapEntry.FLAG_IS_THECLOUD) == WMapEntry.FLAG_IS_THECLOUD)); } void storeConfig() { DataOutputStream out; try { out = new DataOutputStream(openFileOutput("wscnprefs", Context.MODE_PRIVATE)); out.writeByte(1); // version out.writeInt(ScanService.scanData.getFlags()); // operation flags; out.writeInt(ScanService.scanData.getStoredValues()); // number of currently stored values out.writeInt(ScanService.scanData.getUploadedCount()); out.writeInt(ScanService.scanData.getUploadedRank()); out.writeInt(0); // Open WLANs, no longer used out.writeInt(ScanService.scanData.getFreeHotspotWLANs()); out.writeFloat(ScanService.scanData.getTelemetryData().getCorrAccelX()); out.writeFloat(ScanService.scanData.getTelemetryData().getCorrAccelY()); out.writeFloat(ScanService.scanData.getTelemetryData().getCorrAccelZ()); out.writeFloat(ScanService.scanData.getTelemetryData().getCorrCoG()); out.writeFloat(ScanService.scanData.getTelemetryData().getCorrOrientY()); out.writeFloat(ScanService.scanData.getTelemetryData().getCorrOrientZ()); out.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } 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 } private class UploadPositionTask extends AsyncTask<Void, Void, Void> { protected Void doInBackground(Void... params) { String outString; HttpURLConnection c = null; DataOutputStream os = null; outString = scanData.getOwnBSSID(); outString = outString + "\nL\tX\t" + lastLat + "\t" + lastLon + "\n"; try { URL connectURL = new URL("http://www.openwlanmap.org/android/upload.php"); c = (HttpURLConnection) connectURL.openConnection(); if (c == null) { return null; } c.setDoOutput(true); // enable POST c.setRequestMethod("POST"); c.addRequestProperty("Content-Type", "application/x-www-form-urlencoded, *.*"); c.addRequestProperty("Content-Length", "" + outString.length()); os = new DataOutputStream(c.getOutputStream()); os.write(outString.getBytes()); os.flush(); c.getResponseCode(); os.close(); outString = null; os = null; } catch (IOException ioe) { } finally { try { if (os != null) os.close(); if (c != null) c.disconnect(); } catch (IOException ioe) { ioe.printStackTrace(); } } return null; } } }
public void run() { int x, y; Bitmap locTile; Canvas canvas; float useLon, useLat, useLonMax, useLatMax; System.gc(); if ((useOverlay.tileX == 0) && (useOverlay.tileY == 0)) return; mapThreadRunning = true; try { if (locMap == null) locMap = Bitmap.createBitmap(tileWidth * 256, tileHeight * 256, Bitmap.Config.ARGB_8888); } catch (OutOfMemoryError oome) { return; } locMap.eraseColor(Color.BLACK); canvas = new Canvas(locMap); useLon = (GeoUtils.tilex2long(useOverlay.tileX, useOverlay.m_zoom) + GeoUtils.tilex2long(useOverlay.tileX + 1, useOverlay.m_zoom)) / 2.0f; useLat = (GeoUtils.tiley2lat(useOverlay.tileY, useOverlay.m_zoom) + GeoUtils.tiley2lat(useOverlay.tileY + 1, useOverlay.m_zoom)) / 2.0f; while (mScaleFactor >= 2.0) { mScaleFactor /= 2.0f; useOverlay.m_zoom++; if (useOverlay.m_zoom > 17) { useOverlay.m_zoom = 17; imgOffsetX -= (scrWidth - (scrWidth * 2.0)) / 2.0; imgOffsetY -= (scrHeight - (scrHeight * 2.0)) / 2.0; } } while (mScaleFactor <= 0.5) { mScaleFactor *= 2.0f; useOverlay.m_zoom--; if (useOverlay.m_zoom < 3) { useOverlay.m_zoom = 3; imgOffsetX -= (scrWidth - (scrWidth * 2.0)) / 2.0; imgOffsetY -= (scrHeight - (scrHeight * 2.0)) / 2.0; } } mScaleFactor = 1.0f; /* if ((wasScaleOp) && (lonCenter!=0.0f) && (latCenter!=0.0f)) { tileX=GeoUtils.long2tilex(lonCenter,m_zoom); tileY=GeoUtils.lat2tiley(latCenter,m_zoom); tileX-=(scrWidth / 256); tileY-=(scrWidth / 256); } else*/ { useOverlay.tileX = GeoUtils.long2tilex(useLon, useOverlay.m_zoom); useOverlay.tileY = GeoUtils.lat2tiley(useLat, useOverlay.m_zoom); } useLon = GeoUtils.tilex2long(useOverlay.tileX - 1, useOverlay.m_zoom); useLat = GeoUtils.tiley2lat(useOverlay.tileY - 1, useOverlay.m_zoom); useLonMax = GeoUtils.tilex2long(useOverlay.tileX + tileWidth + 1, useOverlay.m_zoom); useLatMax = GeoUtils.tiley2lat(useOverlay.tileY + tileHeight + 1, useOverlay.m_zoom); /* if (imgOffsetX>scrWidth) { imgOffsetX=scrWidth/2; } if (imgOffsetX<=-scrWidth) { imgOffsetX=-scrWidth/2; } if (imgOffsetY>scrHeight) { imgOffsetY=scrHeight/2; } if (imgOffsetY<=-scrHeight) { imgOffsetY=-scrHeight/2; }*/ while (imgOffsetX > 0) { imgOffsetX -= 256.0f; useOverlay.tileX--; } while (imgOffsetX <= -256.0) { imgOffsetX += 256.0f; useOverlay.tileX++; } while (imgOffsetY > 0) { imgOffsetY -= 256.0f; useOverlay.tileY--; } while (imgOffsetY <= -256.0) { imgOffsetY += 256.0f; useOverlay.tileY++; } // calculate lat/lon of screen center point /* { int useTileX=tileX,useTileY=tileY; x=(int)((scrWidth/2.0f)+imgOffsetX); y=(int)((scrHeight/2.0f)+imgOffsetY); useTileX+=(x / 256); x=x % 256; useTileY+=(y / 256); y=y % 256; float tileLon1=GeoUtils.tilex2long(useTileX,m_zoom); float tileLat1=GeoUtils.tiley2lat(useTileY,m_zoom); float tileLon2=GeoUtils.tilex2long(useTileX+1,m_zoom); float tileLat2=GeoUtils.tiley2lat(useTileY+1,m_zoom); lonCenter=(((tileLon2-tileLon1)/256.0f)*x)+tileLon1; latCenter=(((tileLat2-tileLat1)/256.0f)*y)+tileLat1; }*/ matrix.setTranslate(imgOffsetX, imgOffsetY); breakMapThread = false; mapThreadRunning = false; for (x = 0; x < tileWidth; x++) for (y = 0; y < tileHeight; y++) { if (breakMapThread) return; locTile = geoUtils.loadMapTile( getContext(), useOverlay.tileX + x, useOverlay.tileY + y, useOverlay.m_zoom, allowNetAccess); if (locTile != null) canvas.drawBitmap(locTile, x * 256, y * 256, null); postInvalidate(); } useOverlay.doDraw(canvas, useLon, useLonMax, useLat, useLatMax, locMap); postInvalidate(); System.gc(); }
// Load the .so static { // Urho3D: everything resides in urho3d.so System.loadLibrary("Urho3D"); }
// ============================================================================== static { System.loadLibrary("juce_jni"); }
@Override public int onStartCommand(Intent intent, int flags, int startId) { // GET SETTINGS FROM SHARED PREFERENCES SharedPreferences settingsF = getSharedPreferences(FUZZY_STUFF, 0); int backgroundColorF = settingsF.getInt("BackgroundColorF", this.getResources().getColor(R.color.palesky)); int textColorF = settingsF.getInt("TextColorF", this.getResources().getColor(R.color.night)); String packageName = settingsF.getString("PackageName", "com.android.alarmclock"); String className = settingsF.getString("ClassName", "com.android.alarmclock.AlarmClock"); // CALCULATE ALL THE TIME DEPENDENT VARIABLES // reset the time dependent addition long alarmAddMillis = 0; // get time instance and values Calendar rightNow = Calendar.getInstance(); int thisMin = rightNow.get(Calendar.MINUTE); int thisHour = rightNow.get(Calendar.HOUR); // set correct hour values nextHour = thisHour + 1; if (thisHour == 0) { thisHour = 12; } if (nextHour == 13) { nextHour = 1; } // set text values based on minutes if (thisMin >= 0 && thisMin <= 7) { wordA = "its"; wordB = "about"; wordA_B = "its_about"; clockH = thisHour; nextAlarmMin = 8; alarmAddMillis = 0; } if (thisMin >= 8 && thisMin <= 22) { wordA = "quarter"; wordB = "past"; wordA_B = "quarter_past"; clockH = thisHour; nextAlarmMin = 23; alarmAddMillis = 0; } if (thisMin >= 23 && thisMin <= 37) { wordA = "half"; wordB = "past"; wordA_B = "half_past"; clockH = thisHour; nextAlarmMin = 38; alarmAddMillis = 0; } if (thisMin >= 38 && thisMin <= 52) { wordA = "quarter"; wordB = "to"; wordA_B = "quarter_to"; clockH = nextHour; nextAlarmMin = 53; alarmAddMillis = 0; } if (thisMin >= 53 && thisMin <= 59) { wordA = "its"; wordB = "about"; wordA_B = "its_about"; clockH = nextHour; nextAlarmMin = 8; alarmAddMillis = 3600000; } // CANCEL ANY UNSENT ALARM if (alarmManager != null) { alarmManager.cancel(pendingIntent); } // SET UP THE NEXT ALARM // set the time Calendar nextAlarm = Calendar.getInstance(); // add one hour of millis if its for the next hour nextAlarm.setTimeInMillis(System.currentTimeMillis() + alarmAddMillis); // set the correct minute nextAlarm.set(Calendar.MINUTE, nextAlarmMin); nextAlarm.set(Calendar.SECOND, 15); nextAlarm.set(Calendar.MILLISECOND, 0); // request the alarm alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); Intent usIntent = new Intent(this, AlarmReceiver.class); pendingIntent = PendingIntent.getBroadcast(this, 0, usIntent, 0); // use onExact for API19+ int currentApiVersion = android.os.Build.VERSION.SDK_INT; if (currentApiVersion <= 18) { alarmManager.set(AlarmManager.RTC, nextAlarm.getTimeInMillis(), pendingIntent); } else { alarmManager.setExact(AlarmManager.RTC, nextAlarm.getTimeInMillis(), pendingIntent); } // SET UP THE IMAGES // get the resource id ints for images to send by remoteviews int timePhraseA = this.getResources().getIdentifier("phr_" + wordA, "drawable", this.getPackageName()); int timePhraseB = this.getResources().getIdentifier("phr_" + wordB, "drawable", this.getPackageName()); int timePhraseA_B = this.getResources().getIdentifier("phr_" + wordA_B, "drawable", this.getPackageName()); int hourWordImageCrop = this.getResources().getIdentifier("num_" + clockH, "drawable", this.getPackageName()); int hourWordImageWide = this.getResources() .getIdentifier("num_" + clockH + "_w", "drawable", this.getPackageName()); // SET THE BITMAP COLOR AND OTHER VALUES fillPaintF = new Paint(Paint.FILTER_BITMAP_FLAG); fillPaintF.setColor(textColorF); fillPaintF.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP)); BitmapFactory.Options options = new BitmapFactory.Options(); options.inPurgeable = true; options.inPreferredConfig = Bitmap.Config.ARGB_8888; // ASSEMBLE THE PENDING INTENTS // create the open configuration pending intent Intent openAWC = new Intent(this, AppWidgetConfigure.class); openAWC.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent openAwcPi = PendingIntent.getActivity(this, 0, openAWC, PendingIntent.FLAG_UPDATE_CURRENT); // create the open alarms pending intent - done here because it couldnt be saved in prefs // set up open Alarms Intent PendingIntent alarmPI = null; PackageManager packageManager = this.getPackageManager(); Intent alarmClockIntent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER); // get the activity info and attach to the intent try { ComponentName cn = new ComponentName(packageName, className); packageManager.getActivityInfo(cn, PackageManager.GET_META_DATA); alarmClockIntent.setComponent(cn); } catch (PackageManager.NameNotFoundException e) { stopSelf(); } // finalize the pending intent alarmPI = PendingIntent.getActivity(this, 0, alarmClockIntent, 0); // create the refresh widget pending intent Intent startUpdateF = new Intent(this, UpdateService.class); startUpdateF.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); pendingStartUpdateF = PendingIntent.getService(this, 0, startUpdateF, PendingIntent.FLAG_UPDATE_CURRENT); // **** BACKGROUND IMAGE PREPARATION **** // draw an empty image bitmapBackgroundF = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888); // paint in the color Canvas canvasBackgroundF = new Canvas(bitmapBackgroundF); fillPaintBackgroundF = new Paint(); fillPaintBackgroundF.setColor(backgroundColorF); canvasBackgroundF.drawPaint(fillPaintBackgroundF); // SEND ALL THE STUFF TO THE PLACED WIDGETS // get appwidgetmanager instance for all widgets AppWidgetManager localAppWidgetManager = AppWidgetManager.getInstance(this); // update all 4x1 widget instances ComponentName thisWidget4x1 = new ComponentName(getBaseContext(), WidgetProvider4x1.class); int[] allWidgetIds4x1 = localAppWidgetManager.getAppWidgetIds(thisWidget4x1); if (allWidgetIds4x1 != null) { // join the images together into one strip Bitmap bitmap4x1partA = BitmapFactory.decodeResource(getResources(), timePhraseA, options); Bitmap bitmap4x1partB = BitmapFactory.decodeResource(getResources(), timePhraseB, options); Bitmap bitmap4x1partC = BitmapFactory.decodeResource(getResources(), hourWordImageCrop, options); Bitmap bitmap4x1strip = Bitmap.createBitmap( bitmap4x1partA.getWidth() + bitmap4x1partB.getWidth() + bitmap4x1partC.getWidth(), bitmap4x1partA.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas4x1strip = new Canvas(bitmap4x1strip); canvas4x1strip.drawBitmap(bitmap4x1partA, 0, 0, null); canvas4x1strip.drawBitmap(bitmap4x1partB, bitmap4x1partA.getWidth(), 0, null); canvas4x1strip.drawBitmap( bitmap4x1partC, bitmap4x1partA.getWidth() + bitmap4x1partB.getWidth(), 0, null); // generate adjusted images if color theme isnt default // strip Bitmap bitmap4x1strip2 = bitmap4x1strip.copy(Bitmap.Config.ARGB_8888, true); Canvas canvas4x1strip2 = new Canvas(bitmap4x1strip2); canvas4x1strip2.drawPaint(fillPaintF); for (int widgetId : allWidgetIds4x1) { RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.widget_layout_4x1); remoteViews.setImageViewBitmap(R.id.imageviewBG, bitmapBackgroundF); remoteViews.setImageViewBitmap(R.id.imageviewABC, bitmap4x1strip2); remoteViews.setOnClickPendingIntent(R.id.topclickLeft, alarmPI); remoteViews.setOnClickPendingIntent(R.id.topclickRight, openAwcPi); localAppWidgetManager.updateAppWidget(widgetId, remoteViews); } bitmap4x1strip2 = null; canvas4x1strip2 = null; bitmap4x1strip = null; canvas4x1strip = null; } // update all 3x2 widget instances ComponentName thisWidget3x2 = new ComponentName(getBaseContext(), WidgetProvider3x2.class); int[] allWidgetIds3x2 = localAppWidgetManager.getAppWidgetIds(thisWidget3x2); if (allWidgetIds3x2 != null) { // generate adjusted images if color theme isnt default // time phrase if (bitmapTimePhraseA_B == null) { bitmapTimePhraseA_B1 = BitmapFactory.decodeResource(getResources(), timePhraseA_B, options); bitmapTimePhraseA_B = bitmapTimePhraseA_B1.copy(Bitmap.Config.ARGB_8888, true); canvasPhrase = new Canvas(bitmapTimePhraseA_B); canvasPhrase.drawPaint(fillPaintF); } // hour word if (bitmapHourWordImage == null) { bitmapHourWordImage1 = BitmapFactory.decodeResource(getResources(), hourWordImageWide, options); bitmapHourWordImage = bitmapHourWordImage1.copy(Bitmap.Config.ARGB_8888, true); canvasHour = new Canvas(bitmapHourWordImage); canvasHour.drawPaint(fillPaintF); } for (int widgetId : allWidgetIds3x2) { RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.widget_layout_3x2); remoteViews.setImageViewBitmap(R.id.imageviewA_B, bitmapTimePhraseA_B); remoteViews.setImageViewBitmap(R.id.imageviewC, bitmapHourWordImage); remoteViews.setImageViewBitmap(R.id.imageviewBG, bitmapBackgroundF); remoteViews.setOnClickPendingIntent(R.id.topclickLeft, alarmPI); remoteViews.setOnClickPendingIntent(R.id.topclickRight, openAwcPi); localAppWidgetManager.updateAppWidget(widgetId, remoteViews); } } // CLEAR ALL THE BITMAPS bitmapTimePhraseA_B = null; bitmapTimePhraseA_B1 = null; bitmapHourWordImageCrop = null; bitmapHourWordImageCrop1 = null; bitmapHourWordImage = null; bitmapHourWordImage1 = null; canvasPhrase = null; canvasHour = null; bitmapBackgroundF = null; stopSelf(); return super.onStartCommand(intent, flags, startId); }