// code which handles the action for each menu item public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.settings: { Intent preferences_intent = new Intent(); preferences_intent.setComponent( new ComponentName(download_photos.this, preferences.class)); preferences_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); getApplicationContext().startActivity(preferences_intent); return true; } case R.id.logout: { try { download_photos.this.facebook.logout(getApplicationContext()); } catch (IOException e) { e.printStackTrace(); } mPrefs = getSharedPreferences("COMMON", MODE_PRIVATE); SharedPreferences.Editor editor = mPrefs.edit(); editor.putString("access_token", null); editor.putLong("access_expires", 0); editor.putBoolean("logout", true); editor.commit(); finish(); return true; } case R.id.about: { // shows our customized about dialog AboutDialog about = new AboutDialog(this); about.show(); return true; } // lets deal with default case default: return super.onOptionsItemSelected(item); } }
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 }
@Override public void onCreate(Bundle savedInstanceState) { // locks the screen in portrait mode setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); super.onCreate(savedInstanceState); setContentView(R.layout.downloader); mtext = (TextView) findViewById(R.id.mtext); progress_text = (TextView) findViewById(R.id.progress_text); progress_download = (ProgressBar) findViewById(R.id.progress_download); // resume capability paused = false; resume_pause = (Button) findViewById(R.id.resume); // Create and launch the download thread downloadThread = new DownloadThread(this); downloadThread.start(); // Create the Handler. It will implicitly bind to the Looper // that is internally created for this thread (since it is the UI thread) handler = new Handler(); resume_pause.setOnClickListener( new View.OnClickListener() { public void onClick(View v) { if (!paused) { paused = true; resume_pause.setText("Resume"); // writeProgress(completed_downloads,total_files_to_download); downloadThread.requestStop(); downloadThread = null; } else { resume_pause.setText("Pause"); paused = false; initial_value = readProgress()[0]; final_value = links.size(); for (int i = initial_value; i < links.size(); i++) { downloadThread = new DownloadThread(download_photos.this); downloadThread.start(); downloadThread.enqueueDownload( new DownloadTask( links.get(i), path, i + 1, links.size(), download_photos.this)); } } } }); // load preferences for this activity mPrefs = getSharedPreferences("COMMON", MODE_PRIVATE); // This declaration is solely meant for reading the checkbox preference for downloading high res // pics. SharedPreferences dl_prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); // The global variable is set after reading the checkbox preference. dl_high_res_pics = dl_prefs.getBoolean("download_high_res", false); // load fb access token and its expiry values String access_token = mPrefs.getString("access_token", null); long expires = mPrefs.getLong("access_expires", 0); if (access_token != null) { facebook.setAccessToken(access_token); } if (expires != 0) { facebook.setAccessExpires(expires); } // get friend_name and album_name from the intent which started this activity Intent starting_intent = getIntent(); album_id = starting_intent.getStringExtra("id"); album_name = starting_intent.getStringExtra("name"); friend_name = starting_intent.getStringExtra("friend_name"); // real album and friend name may contain characters not suitable for file names. // regex pattern includes most of the invalid characters in file names legal_album_name = album_name.replaceAll("[.\\\\/:*?\"<>|]?[\\\\/:*?\"<>|]*", ""); legal_friend_name = friend_name.replaceAll("[.\\\\/:*?\"<>|]?[\\\\/:*?\"<>|]*", ""); // initialise the directory structure for download path = new File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/" + getText(R.string.app_name) + "/" + legal_friend_name + "/" + legal_album_name); if (dl_high_res_pics) path = new File(path.toString() + "/" + getText(R.string.folder_name_high_res)); resume_file = new File(path, "resume.txt"); // implements actions to done after receiving json object class meRequestListener extends BaseRequestListener { @Override public void onComplete(String response, Object state) { try { Log.i(TAG, response); json = Util.parseJson(response); // photos are in the form of a json array child = json.getJSONArray("data"); int total = child.length(); // contains links to photos links = new ArrayList<String>(total); // adds link to each photo to our list after replacing the "https" from url // DownloadManager does not support https in gingerbread for (int i = 0; i < total; i++) { photo_json = child.getJSONObject(i); if (dl_high_res_pics) { JSONArray image_set = photo_json.getJSONArray("images"); // highest resolution picture has the index zero in the images jsonarray JSONObject highest_res_pic = image_set.getJSONObject(0); String http_replaced = highest_res_pic.getString("source").replaceFirst("https", "http"); links.add(i, http_replaced); } else { // source property of the json object points to the photo's link String http_replaced = photo_json.getString("source").replaceFirst("https", "http"); links.add(i, http_replaced); } } download_photos.this.runOnUiThread( new Runnable() { public void run() { // mytask = new DownloadImageTask(); // mytask.execute(links); // start downloading using asynctask // new DownloadImageTask().execute(links); // downloadThread.setPath(path); // downloadThread.setWholeTasks(links.size()); if (resume_file.exists()) { initial_value = readProgress()[0]; final_value = links.size(); // case if the task is already completed if (initial_value == final_value) { completed = true; resume_pause.setVisibility(View.GONE); progress_download.setMax(final_value); progress_download.setProgress(0); // bug in progress bar progress_download.setProgress(initial_value); progress_text.setText("Completed."); mtext.setText( getText(R.string.download_textview_message_1) + " " + path.toString() + ". "); } // case if some of the photos are already downloaded else { progress_download.setMax(links.size()); // progress_download.setProgress(0); //bug in progress bar progress_download.setProgress(initial_value); // N.B if i= initial_value -1, then one image will be downloaded again. so to // save cost we start with i = initial_value for (int i = initial_value; i < links.size(); i++) { mtext.setText( getText(R.string.download_textview_message_1) + " " + path.toString() + ". "); // downloadThread.setRunningTask(i + 1); downloadThread.enqueueDownload( new DownloadTask( links.get(i), path, i + 1, final_value, download_photos.this)); } } } // case if the task is entirely new task else { for (int i = 0; i < links.size(); i++) { mtext.setText( getText(R.string.download_textview_message_1) + " " + path.toString() + ". "); // downloadThread.setRunningTask(i + 1); downloadThread.enqueueDownload( new DownloadTask( links.get(i), path, i + 1, links.size(), download_photos.this)); } } } }); } catch (JSONException ex) { Log.e(TAG, "JSONEXception : " + ex.getMessage()); } } } // makes asynchronous request to facebook graph api // the actions to be performed after receiving json response is implemented above Bundle parameters = new Bundle(); // facebook returns only 25 photos when limit is not specified. parameters.putString("limit", max_photos_in_album); if (!completed) mAsyncRunner.request(album_id + "/photos", parameters, new meRequestListener()); if (!facebook.isSessionValid()) { facebook.authorize( this, permissions, new DialogListener() { // save fb access token and its expiry values to prefernces of this activity @Override public void onComplete(Bundle values) { SharedPreferences.Editor editor = mPrefs.edit(); editor.putString("access_token", facebook.getAccessToken()); editor.putLong("access_expires", facebook.getAccessExpires()); editor.commit(); } @Override public void onFacebookError(FacebookError error) { Log.e(TAG, "Facebook Error : " + error.getMessage()); } @Override public void onError(DialogError e) { Log.e(TAG, e.getMessage()); } @Override public void onCancel() { // do nothing LOL :-) } }); } }