@Override
  protected void onStart() {
    final GameBoard boardView = (GameBoard) this.findViewById(R.id.gameBoard);
    SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);

    this.level = prefs.getInt("level", 0);
    String mapJson = prefs.getString("map", null);

    if (mapJson == null) {
      waitForNext = true;
    } else {
      this.game.initGame(mapJson);
      String howdyPosition = prefs.getString("howdy", null);

      if (howdyPosition != null) {
        this.game.setHowdyPosition(howdyPosition);
      }

      Toast.makeText(this, this.level + "", Toast.LENGTH_SHORT).show();
    }

    String allDoneLevelsString = prefs.getString("doneLevels", null);

    if (allDoneLevelsString != null) {
      allDoneLevels = new ArrayList<String>(Arrays.asList(allDoneLevelsString.split(",")));
    }

    super.onStart();
  }
Beispiel #2
0
  /** Event raised when the form is created for the first time */
  @Override
  public void onCreate(Bundle savedInstanceState) {

    Utilities.LogDebug("GpsMainActivity.onCreate");

    SharedPreferences prefs =
        PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    String lang = prefs.getString("locale_override", "");

    if (!lang.equalsIgnoreCase("")) {
      Locale locale = new Locale(lang);
      Locale.setDefault(locale);
      Configuration config = new Configuration();
      config.locale = locale;
      getApplicationContext()
          .getResources()
          .updateConfiguration(config, getApplicationContext().getResources().getDisplayMetrics());
    }

    super.onCreate(savedInstanceState);

    Utilities.LogInfo("GPSLogger started");

    setContentView(R.layout.main);

    GetPreferences();

    StartAndBindService();
  }
 @Override
 public void onResume() {
   super.onResume();
   rootdir = Environment.getExternalStorageDirectory().getAbsolutePath();
   directoryView = (TextView) findViewById(R.id.directory);
   SharedPreferences settings = getPreferences(0);
   String lastBrowsedDirectory = settings.getString("lastBrowsedDirectory", null);
   if (lastBrowsedDirectory == null) {
     lastBrowsedDirectory = rootdir;
   }
   loadDirectory(lastBrowsedDirectory);
 }
  private void finishWithPath(String path) {
    if (pathSettingKey != null && !pathSettingKey.isEmpty()) {
      SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
      SharedPreferences.Editor editor = settings.edit();
      editor.putString(pathSettingKey, path);
      editor.commit();
    }

    Intent intent = new Intent();
    intent.putExtra("PATH", path);
    setResult(RESULT_OK, intent);
    finish();
  }
 private void getAccountInfo() {
   SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
   String id = sharedPref.getString("id", "");
   if (!TextUtils.isEmpty(id)) {
     accountBean = DatabaseManager.getInstance().getAccount(id);
     if (accountBean != null) {
       token = accountBean.getAccess_token();
       getActionBar().setSubtitle(accountBean.getUsernick());
     } else {
       List<AccountBean> accountList = DatabaseManager.getInstance().getAccountList();
       if (accountList != null && accountList.size() > 0) {
         AccountBean account = accountList.get(0);
         accountBean = account;
         token = account.getAccess_token();
         getActionBar().setSubtitle(account.getUsernick());
       }
     }
   }
 }
  @Override
  protected void onStop() {
    SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();

    editor.putInt("level", this.level);
    editor.putString("map", game.getLabyrinth().getJsonMap());
    editor.putString("howdy", game.getJsonHowdy());

    String allDoneLevelsString = "";

    for (String s : allDoneLevels) {
      allDoneLevelsString += s + ",";
    }

    if (allDoneLevelsString.length() > 0) {
      editor.putString(
          "doneLevels", allDoneLevelsString.substring(0, allDoneLevelsString.length() - 1));
    }

    editor.commit();

    super.onStop();
  }
  // 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);
    }
  }
Beispiel #8
0
  Runner(final Group group, String router, String routerPrefix, final MainActivity mainActivity) {
    super(group, router, routerPrefix);
    // group, model, colors, audio observer are all set up now.
    this.mainActivity = mainActivity;
    gui = new Gui(mainActivity, group, model);
    String key = "com.tayek.tablet.sharedPreferencesKey";
    sharedPreferences = mainActivity.getSharedPreferences(key, Context.MODE_PRIVATE);
    // sharedPreferences.edit().clear().commit(); // only if we have to
    pl("router: " + router + ", prefix: " + routerPrefix);
    pl("preferences: " + sharedPreferences.getAll());
    ((AndroidPrefs) prefs)
        .setDelegate(
            new AndroidPrefs() {
              @Override
              public String get(String key) {
                return sharedPreferences.getString(key, "");
              }

              @Override
              public void put(String key, String value) {
                sharedPreferences.edit().putString(key, value).commit();
              }

              @Override
              public Map<String, ?> map() {
                return sharedPreferences.getAll();
              }

              @Override
              public String toString() {
                return sharedPreferences.getAll().toString();
              }
            });
    pl("prefs: " + prefs);
    // Exec.exec("settings put global captive_portal_detection_enabled 0 ");
    // loopSleep=10_000;
    // prefs.clear();
    // try clearing the prefs to see if it fixed the problem
    // that conrad found on sunday.
  }
Beispiel #9
0
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    mAppContext = this;
    mMainHandler = new Handler();

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

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

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

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

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

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

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

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

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

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

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

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

    GeckoNetworkManager.getInstance().init();

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

    checkAndLaunchUpdate();
    mLibLoadThread =
        new Thread(
            new Runnable() {
              public void run() {
                // At some point while loading the gecko libs our default locale gets set
                // so just save it to locale here and reset it as default after the join
                Locale locale = Locale.getDefault();
                GeckoAppShell.loadGeckoLibs(getApplication().getPackageResourcePath());
                Locale.setDefault(locale);
                Resources res = getBaseContext().getResources();
                Configuration config = res.getConfiguration();
                config.locale = locale;
                res.updateConfiguration(config, res.getDisplayMetrics());
              }
            });
    mLibLoadThread.start();
  }
  public void run() {
    int i,
        j,
        storedValues,
        sleepTime = 3000,
        timeoutCtr = 0,
        lastFlags = -1,
        trackCnt = 0,
        lastLocMethod = -5;
    String bssid;
    WMapEntry currEntry;
    DataOutputStream out;
    FileInputStream in;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);

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

    connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
  }
Beispiel #12
0
  public static void ConfigureLogbackDirectly(Context context) {
    try {
      // reset the default context (which may already have been initialized)
      // since we want to reconfigure it
      LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
      lc.reset();

      // final String LOG_DIR = "/sdcard/GPSLogger";
      SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
      final String LOG_DIR =
          prefs.getString(
              "gpslogger_folder", Utilities.GetDefaultStorageFolder(context).getAbsolutePath());

      GpsRollingFileAppender<ILoggingEvent> rollingFileAppender =
          new GpsRollingFileAppender<ILoggingEvent>();
      rollingFileAppender.setAppend(true);
      rollingFileAppender.setContext(lc);

      // OPTIONAL: Set an active log file (separate from the rollover files).
      // If rollingPolicy.fileNamePattern already set, you don't need this.
      rollingFileAppender.setFile(LOG_DIR + "/debuglog.txt");
      rollingFileAppender.setLazy(true);

      TimeBasedRollingPolicy<ILoggingEvent> rollingPolicy =
          new TimeBasedRollingPolicy<ILoggingEvent>();
      rollingPolicy.setFileNamePattern(LOG_DIR + "/debuglog.%d.txt");
      rollingPolicy.setMaxHistory(3);
      rollingPolicy.setParent(rollingFileAppender); // parent and context required!
      rollingPolicy.setContext(lc);
      rollingPolicy.start();

      rollingFileAppender.setRollingPolicy(rollingPolicy);

      PatternLayoutEncoder encoder = new PatternLayoutEncoder();
      encoder.setPattern("%d{HH:mm:ss} %-5p %class{0}.%method:%L - %m%n");
      encoder.setContext(lc);
      encoder.start();

      rollingFileAppender.setEncoder(encoder);
      rollingFileAppender.start();

      // setup LogcatAppender
      PatternLayoutEncoder encoder2 = new PatternLayoutEncoder();
      encoder2.setContext(lc);
      encoder2.setPattern("%method:%L - %m%n");
      encoder2.start();

      LogcatAppender logcatAppender = new LogcatAppender();
      logcatAppender.setContext(lc);
      logcatAppender.setEncoder(encoder2);
      logcatAppender.start();

      SessionLogcatAppender sessionAppender = new SessionLogcatAppender();
      sessionAppender.setContext(lc);
      sessionAppender.start();

      // add the newly created appenders to the root logger;
      // qualify Logger to disambiguate from org.slf4j.Logger
      ch.qos.logback.classic.Logger root =
          (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
      root.addAppender(rollingFileAppender);
      root.addAppender(logcatAppender);
      root.addAppender(sessionAppender);

    } catch (Exception ex) {
      System.out.println("Could not configure logging!");
    }
  }
Beispiel #13
0
 public static boolean IsDropBoxSetup(Context context) {
   SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
   return prefs.contains(DropBoxHelper.ACCESS_KEY_NAME)
       && prefs.contains(DropBoxHelper.ACCESS_SECRET_NAME);
 }
Beispiel #14
0
  /** Gets user preferences, populates the AppSettings class. */
  public static void PopulateAppSettings(Context context) {

    tracer.debug("Getting preferences");
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);

    AppSettings.setHideNotificationButtons(prefs.getBoolean("hide_notification_buttons", false));

    AppSettings.setUseImperial(prefs.getBoolean("useImperial", false));

    AppSettings.setLogToKml(prefs.getBoolean("log_kml", false));

    AppSettings.setLogToGpx(prefs.getBoolean("log_gpx", true));

    AppSettings.setLogToPlainText(prefs.getBoolean("log_plain_text", false));

    AppSettings.setLogToNmea(prefs.getBoolean("log_nmea", false));

    AppSettings.setLogToCustomUrl(prefs.getBoolean("log_customurl_enabled", false));
    AppSettings.setCustomLoggingUrl(prefs.getString("log_customurl_url", ""));

    AppSettings.setLogToOpenGts(prefs.getBoolean("log_opengts", false));

    Set<String> listeners = new HashSet<String>(GetListeners());
    AppSettings.setChosenListeners(prefs.getStringSet("listeners", listeners));

    String minimumDistanceString = prefs.getString("distance_before_logging", "0");

    if (minimumDistanceString != null && minimumDistanceString.length() > 0) {
      AppSettings.setMinimumDistanceInMeters(Integer.valueOf(minimumDistanceString));
    } else {
      AppSettings.setMinimumDistanceInMeters(0);
    }

    String minimumAccuracyString = prefs.getString("accuracy_before_logging", "0");

    if (minimumAccuracyString != null && minimumAccuracyString.length() > 0) {
      AppSettings.setMinimumAccuracyInMeters(Integer.valueOf(minimumAccuracyString));
    } else {
      AppSettings.setMinimumAccuracyInMeters(0);
    }

    String minimumSecondsString = prefs.getString("time_before_logging", "60");

    if (minimumSecondsString != null && minimumSecondsString.length() > 0) {
      AppSettings.setMinimumSeconds(Integer.valueOf(minimumSecondsString));
    } else {
      AppSettings.setMinimumSeconds(60);
    }

    AppSettings.setKeepFix(prefs.getBoolean("keep_fix", false));

    String retryIntervalString = prefs.getString("retry_time", "60");

    if (retryIntervalString != null && retryIntervalString.length() > 0) {
      AppSettings.setRetryInterval(Integer.valueOf(retryIntervalString));
    } else {
      AppSettings.setRetryInterval(60);
    }

    /**
     * New file creation preference: onceaday, custom file (static), every time the service starts
     */
    AppSettings.setNewFileCreation(prefs.getString("new_file_creation", "onceaday"));

    if (AppSettings.getNewFileCreation().equals("onceaday")) {
      AppSettings.setNewFileOnceADay(true);
      AppSettings.setCustomFile(false);
    } else if (AppSettings.getNewFileCreation().equals("custom")
        || AppSettings.getNewFileCreation().equals("static")) {
      AppSettings.setCustomFile(true);
      AppSettings.setCustomFileName(prefs.getString("new_file_custom_name", "gpslogger"));
      AppSettings.setAskCustomFileNameEachTime(prefs.getBoolean("new_file_custom_each_time", true));
    } else /* new log with each start */ {
      AppSettings.setNewFileOnceADay(false);
      AppSettings.setCustomFile(false);
    }

    AppSettings.setAutoSendEnabled(prefs.getBoolean("autosend_enabled", false));

    AppSettings.setEmailAutoSendEnabled(prefs.getBoolean("autoemail_enabled", false));

    try {
      AppSettings.setAutoSendDelay(
          Float.valueOf(prefs.getString("autosend_frequency_minutes", "60")));
    } catch (Exception e) {
      AppSettings.setAutoSendDelay(60f);
    }

    AppSettings.setAutoSendWhenIPressStop(
        prefs.getBoolean("autosend_frequency_whenstoppressed", false));

    AppSettings.setSmtpServer(prefs.getString("smtp_server", ""));
    AppSettings.setSmtpPort(prefs.getString("smtp_port", "25"));
    AppSettings.setSmtpSsl(prefs.getBoolean("smtp_ssl", true));
    AppSettings.setSmtpUsername(prefs.getString("smtp_username", ""));
    AppSettings.setSmtpPassword(prefs.getString("smtp_password", ""));
    AppSettings.setAutoEmailTargets(prefs.getString("autoemail_target", ""));
    AppSettings.setDebugToFile(prefs.getBoolean("debugtofile", false));
    AppSettings.setShouldSendZipFile(prefs.getBoolean("autosend_sendzip", true));
    AppSettings.setSmtpFrom(prefs.getString("smtp_from", ""));
    AppSettings.setOpenGtsAutoSendEnabled(prefs.getBoolean("autoopengts_enabled", false));
    AppSettings.setOpenGTSServer(prefs.getString("opengts_server", ""));
    AppSettings.setOpenGTSServerPort(prefs.getString("opengts_server_port", ""));
    AppSettings.setOpenGTSServerCommunicationMethod(
        prefs.getString("opengts_server_communication_method", ""));
    AppSettings.setOpenGTSServerPath(prefs.getString("autoopengts_server_path", ""));
    AppSettings.setOpenGTSDeviceId(prefs.getString("opengts_device_id", ""));
    AppSettings.setOpenGTSAccountName(prefs.getString("opengts_accountname", ""));

    AppSettings.setGDocsAutoSendEnabled(prefs.getBoolean("gdocs_enabled", false));
    AppSettings.setDropboxAutoSendEnabled(prefs.getBoolean("dropbox_enabled", false));
    AppSettings.setOsmAutoSendEnabled(prefs.getBoolean("osm_enabled", false));

    AppSettings.setFtpAutoSendEnabled(prefs.getBoolean("autoftp_enabled", false));
    AppSettings.setFtpServerName(prefs.getString("autoftp_server", ""));
    AppSettings.setFtpUsername(prefs.getString("autoftp_username", ""));
    AppSettings.setFtpPassword(prefs.getString("autoftp_password", ""));
    AppSettings.setFtpDirectory(prefs.getString("autoftp_directory", "GPSLogger"));
    AppSettings.setFtpPort(Integer.valueOf(prefs.getString("autoftp_port", "21")));
    AppSettings.setFtpUseFtps(prefs.getBoolean("autoftp_useftps", false));
    AppSettings.setFtpProtocol(prefs.getString("autoftp_ssltls", ""));
    AppSettings.setFtpImplicit(prefs.getBoolean("autoftp_implicit", false));

    AppSettings.setOwnCloudAutoSendEnabled(prefs.getBoolean("owncloud_enabled", false));
    AppSettings.setOwnCloudServerName(prefs.getString("owncloud_server", ""));
    AppSettings.setOwnCloudUsername(prefs.getString("owncloud_username", ""));
    AppSettings.setOwnCloudPassword(prefs.getString("owncloud_password", ""));
    AppSettings.setOwnCloudDirectory(prefs.getString("owncloud_directory", "/gpslogger"));

    AppSettings.setGpsLoggerFolder(
        prefs.getString(
            "gpslogger_folder", Utilities.GetDefaultStorageFolder(context).getAbsolutePath()));
    AppSettings.setFileNamePrefixSerial(prefs.getBoolean("new_file_prefix_serial", false));

    String absoluteTimeoutString = prefs.getString("absolute_timeout", "120");

    if (absoluteTimeoutString != null && absoluteTimeoutString.length() > 0) {
      AppSettings.setAbsoluteTimeout(Integer.valueOf(absoluteTimeoutString));
    } else {
      AppSettings.setAbsoluteTimeout(120);
    }

    AppSettings.setGoogleDriveFolderName(
        prefs.getString("gdocs_foldername", "GPSLogger for Android"));

    AppSettings.setShouldNotLogIfUserIsStill(
        prefs.getBoolean("activityrecognition_dontlogifstill", false));

    AppSettings.setAdjustAltitudeFromGeoIdHeight(
        prefs.getBoolean("altitude_subtractgeoidheight", false));
    AppSettings.setSubtractAltitudeOffset(
        Integer.valueOf(prefs.getString("altitude_subtractoffset", "0")));
  }
 private void savaDraft() {
   if (!TextUtils.isEmpty(content.getText().toString())) {
     SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
     sharedPref.edit().putString(TYPE_DRAFT, content.getText().toString()).commit();
   }
 }
  @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 :-)
            }
          });
    }
  }
 private String getLastContent() {
   SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
   String draft = sharedPref.getString(TYPE_DRAFT, "");
   return draft;
 }