@Override
  protected void onHandleIntent(Intent intent) {

    String[] downloadUrls = intent.getStringArrayExtra(URLS_KEY);
    int[] chapterIds = intent.getIntArrayExtra(CHAPTER_IDS_KEYS);
    ResultReceiver receiver = (ResultReceiver) intent.getParcelableExtra(RECEIVER_KEY);
    final String fileDownloadDirString = intent.getStringExtra(DOWNLOAD_DIR_KEY);
    final int bookId = intent.getIntExtra(BOOK_ID_KEY, -1);
    for (int ii = 0; ii < downloadUrls.length; ++ii) {
      final String urlToDownload = downloadUrls[ii];
      try {
        URL url = new URL(AudioUtils.makePlayableUrl(urlToDownload));
        URLConnection connection = url.openConnection();
        connection.connect();
        // this will be useful so that you can show a typical 0-100% progress bar
        int fileLength = connection.getContentLength();
        // download the file
        InputStream input = new BufferedInputStream(url.openStream());
        final int chapterId = chapterIds[ii];
        // File Format = /<BookId>_<Chapter_Id>.mp3
        // Log.d("QUTING", "original input = " + urlToDownload + ", url to download = " +
        // url.toString() + ", local path = " + String.format("%s/%d_%d.mp3", fileDownloadDirString,
        // bookId, chapterId));
        OutputStream output =
            new FileOutputStream(
                String.format("%s/%d_%d.mp3", fileDownloadDirString, bookId, chapterId));

        byte data[] = new byte[1024];
        long total = 0;
        int count;
        while ((count = input.read(data)) != -1) {
          total += count;
          // If there is only one chapter publish progress on a file size basis
          if (downloadUrls.length == 1) {
            Bundle resultData = new Bundle();
            resultData.putInt(PROGRESS_KEY, (int) (total * 100 / fileLength));
            resultData.putInt(MAX_KEY, 100);
            resultData.putInt(BOOK_ID_KEY, bookId);
            receiver.send(UPDATE_PROGRESS, resultData);
          }
          output.write(data, 0, count);
        }
        output.flush();
        output.close();
        input.close();
      } catch (IOException e) {
        Log.w("QUTING", "Exception in Download Service " + e);
      }
      // If there is more than one chapter publish progress on a chapter by chapter basis
      if (downloadUrls.length > 1) {
        Bundle resultData = new Bundle();
        resultData.putInt(PROGRESS_KEY, ii + 1);
        resultData.putInt(MAX_KEY, downloadUrls.length);
        resultData.putInt(BOOK_ID_KEY, bookId);
        receiver.send(UPDATE_PROGRESS, resultData);
      }
      break;
    }
  }
示例#2
1
  /**
   * Method used to send back the result to the {@link RequestManager}
   *
   * @param intent The value passed to {@link onHandleIntent(Intent)}. It must contain the {@link
   *     ResultReceiver} and the requestId
   * @param data A {@link Bundle} the data to send back
   * @param code The success/error code to send back
   */
  protected void sendResult(final Intent intent, Bundle data, final int code) {

    if (LogConfig.DP_DEBUG_LOGS_ENABLED) {
      Log.d(LOG_TAG, "sendResult : " + ((code == SUCCESS_CODE) ? "Success" : "Failure"));
    }

    ResultReceiver receiver = (ResultReceiver) intent.getParcelableExtra(INTENT_EXTRA_RECEIVER);

    if (receiver != null) {
      Bundle result = null;
      // Also adding the request parameters (can be useful when receiving the result)
      if (intent != null && intent.getExtras() != null) {
        result = intent.getExtras();
        result.putAll(data);
      }

      if (result == null) {
        result = new Bundle();
      }

      result.putInt(
          RequestManager.RECEIVER_EXTRA_REQUEST_ID,
          intent.getIntExtra(INTENT_EXTRA_REQUEST_ID, -1));

      result.putBoolean(
          RequestManager.RECEIVER_EXTRA_REQUEST_SAVE_IN_MEMORY,
          intent.getBooleanExtra(INTENT_EXTRA_IS_POST_REQUEST, false)
              || intent.getBooleanExtra(INTENT_EXTRA_SAVE_IN_MEMORY, false));

      result.putInt(RequestManager.RECEIVER_EXTRA_RESULT_CODE, code);

      receiver.send(code, result);
    }
  }
  /*
   * Evento que se ejecuta cuando se invocó el servicio por medio de un
   * Intent.
   */
  @Override
  protected void onHandleIntent(final Intent intent) {
    final ResultReceiver receiver = intent.getParcelableExtra("receiver");
    final String command = intent.getStringExtra("command");
    final String query = intent.getStringExtra("query");

    final Bundle b = new Bundle();
    try {
      if (command.equals(GET_PRODUCTS_CMD)) {
        getProducts(receiver, b, query);
      }
    } catch (SocketTimeoutException e) {
      Log.e(TAG, e.getMessage());
      receiver.send(STATUS_CONNECTION_ERROR, b);
    } catch (JSONException e) {
      Log.e(TAG, e.getMessage());
      receiver.send(STATUS_ERROR, b);
    } catch (ClientProtocolException e) {
      Log.e(TAG, e.getMessage());
      receiver.send(STATUS_ERROR, b);
    } catch (IllegalArgumentException e) {
      Log.e(TAG, e.getMessage());
      receiver.send(STATUS_ILLEGAL_ARGUMENT, b);
    } catch (IOException e) {
      Log.e(TAG, e.getMessage());
      receiver.send(STATUS_ERROR, b);
    } catch (Exception e) {
      Log.e(TAG, e.getMessage());
    }

    // Es importante terminar el servicio lo antes posible.
    this.stopSelf();
  }
  @Override
  protected void onHandleIntent(Intent intent) {

    Log.d(TAG, "Service Started!");

    final ResultReceiver receiver = intent.getParcelableExtra("receiver");
    String url = intent.getStringExtra("url");

    Bundle bundle = new Bundle();

    if (!TextUtils.isEmpty(url)) {
      /* Update UI: Download Service is Running */
      receiver.send(STATUS_RUNNING, Bundle.EMPTY);

      try {
        // String results = downloadData(url);
        String results = "hiiiiiiiii";

        /* Sending result back to activity */
        if (null != results && results.length() > 0) {
          bundle.putString("result", results);

          receiver.send(STATUS_FINISHED, bundle);
        }
      } catch (Exception e) {

        /* Sending error message back to activity */
        bundle.putString(Intent.EXTRA_TEXT, e.toString());
        receiver.send(STATUS_ERROR, bundle);
      }
    }
    Log.d(TAG, "Service Stopping!");
    this.stopSelf();
  }
 private ArrayList<RecipeGeneral> getSyncRecipes() {
   ArrayList<RecipeGeneral> resultList = null;
   try {
     Log.d(TAG, "AsyncLogin 1");
     ArrayList<RecipeGeneral> knownRecipes = db.getRecipes();
     int[] ids = new int[knownRecipes.size()];
     for (int i = 0; i < knownRecipes.size(); i++) {
       ids[i] = knownRecipes.get(i).getId();
     }
     String holefavorites = login(ids);
     resultList = getRecipesFromJSONString(holefavorites);
     Log.d(TAG, "AsyncLogin 2");
     if (resultList != null && !resultList.isEmpty()) {
       Log.d(TAG, "AsyncLogin 3");
       for (RecipeGeneral recipe : resultList) {
         Log.d(TAG, "AsyncLogin 4");
         InputStream in = new java.net.URL(Constants.URL + recipe.getImg_url()).openStream();
         Log.d(TAG, Constants.URL + recipe.getImg_url());
         Bitmap bitmap = BitmapFactory.decodeStream(new SanInputStream(in));
         Log.d(TAG, "Bitmap: " + bitmap);
         db.addRecipeToFavorites((Recipe) recipe, bitmap);
       }
     } else {
       Log.d(TAG, "ResultList is empty");
     }
   } catch (MalformedURLException e) {
     e.printStackTrace();
     receiver.send(Constants.AUTHORIZATION_NOT_PASSED, null);
   } catch (IOException e) {
     receiver.send(Constants.AUTHORIZATION_NOT_PASSED, null);
     e.printStackTrace();
   }
   return resultList;
 }
示例#6
0
 /**
  * Register a resultReceiver with this server, that will get notification when a change happens
  * with the connection to the core Like when the connection is lost.
  *
  * @param resultReceiver - Receiver that will get the status updates
  */
 public void registerStatusReceiver(ResultReceiver resultReceiver) {
   statusReceivers.add(resultReceiver);
   if (coreConn != null && coreConn.isConnected()) {
     resultReceiver.send(CoreConnService.CONNECTION_CONNECTED, null);
   } else {
     resultReceiver.send(CoreConnService.CONNECTION_DISCONNECTED, null);
   }
 }
  /**
   * Finishes the activity with negative result ( {@link Activity#RESULT_CANCELED}, {@link
   * #RESULT_FAILED} or {@link #RESULT_FORGOT_PATTERN}).
   */
  private void finishWithNegativeResult(int resultCode) {
    if (ACTION_COMPARE_PATTERN.equals(getIntent().getAction()))
      mIntentResult.putExtra(EXTRA_RETRY_COUNT, mRetryCount);

    setResult(resultCode, mIntentResult);

    /*
     * ResultReceiver
     */
    ResultReceiver receiver = getIntent().getParcelableExtra(EXTRA_RESULT_RECEIVER);
    if (receiver != null) {
      Bundle resultBundle = null;
      if (ACTION_COMPARE_PATTERN.equals(getIntent().getAction())) {
        resultBundle = new Bundle();
        resultBundle.putInt(EXTRA_RETRY_COUNT, mRetryCount);
      }
      receiver.send(resultCode, resultBundle);
    }

    /*
     * PendingIntent
     */
    PendingIntent pi = getIntent().getParcelableExtra(EXTRA_PENDING_INTENT_CANCELLED);
    if (pi != null) {
      try {
        pi.send(this, resultCode, mIntentResult);
      } catch (Throwable t) {
        Log.e(CLASSNAME, "Error sending PendingIntent: " + pi, t);
      }
    }

    finish();
  } // finishWithNegativeResult()
  private void deliverResultToReceiver(int resultCode, String message) {
    // Log.i(TAG, "ADDRESS TO DELIVER: " + message);
    Bundle bundle = new Bundle();
    bundle.putString(Constants.RESULT_DATA_KEY, message);

    mReceiver.send(resultCode, bundle);
  }
  public ArrayList<RecipeGeneral> getRecipesFromJSONString(String result2) {
    ArrayList<RecipeGeneral> recipes = new ArrayList<RecipeGeneral>();
    try {
      JSONArray jsonElements = new JSONArray(result2);
      Log.d(TAG, "In MainListActivity getRecipes(): " + jsonElements);
      Log.d(TAG, "jsonElements.length(): " + jsonElements.length());
      for (int i = 0; i < jsonElements.length(); i++) {
        Recipe favRecipe = (ModelUtil.getRecipeFromJSON(jsonElements.getJSONObject(i)));
        Log.d(TAG, "Recipe: " + jsonElements.getJSONObject(i));
        JSONArray stepsArray = jsonElements.getJSONObject(i).getJSONArray("steps");
        Log.d(TAG, "Steps: " + jsonElements.getJSONObject(i).getJSONArray("steps"));
        ArrayList<Step> favSteps = new ArrayList<Step>();

        for (int j = 0; j < stepsArray.length(); j++) {
          Step step = ModelUtil.getStepFromJSON(stepsArray.getJSONObject(j));
          Log.d(TAG, "Step: " + step);
          favSteps.add(step);
        }
        Log.d(TAG, "Steps ArrayList: " + favSteps);
        favRecipe.setSteps(favSteps);
        recipes.add((RecipeGeneral) favRecipe);
        Log.d(TAG, "In MainListActivity getRecipes() Adding every recipe");
      }
    } catch (Exception e) {
      e.printStackTrace();
      receiver.send(Constants.AUTHORIZATION_NOT_PASSED, null);
    }
    return recipes;
  }
示例#10
0
  protected final void finishWithForgotPatternResult(int resultCode) {
    if (LockPatternType.CREATE_PATTERN != lockPatternType) {
      intentResult.putExtra(EXTRA_RETRY_COUNT, retryCount);
    }

    setResult(resultCode, intentResult);

    /** ResultReceiver */
    ResultReceiver receiver = getIntent().getParcelableExtra(EXTRA_RESULT_RECEIVER);
    if (receiver != null) {
      Bundle resultBundle = new Bundle();
      if (LockPatternType.COMPARE_PATTERN == lockPatternType) {
        resultBundle.putInt(EXTRA_RETRY_COUNT, retryCount);
      }
      resultBundle.putSerializable(EXTRA_LOCK_PATTERN_TYPE, lockPatternType);
      resultBundle.putBoolean(EXTRA_IS_MODIFY, isModify());
      receiver.send(resultCode, resultBundle);
    }

    /** PendingIntent */
    PendingIntent pi = getIntent().getParcelableExtra(EXTRA_PENDING_INTENT_FORGOT_PATTERN);
    if (pi != null) {
      try {
        pi.send();
      } catch (Throwable t) {
        Log.e(CLASSNAME, "Error sending PendingIntent: " + pi, t);
      }
    }

    finish();
  }
 public void finishAndNotify() {
   if (started) {
     Log.i(Constants.TAG, "Send a message to ScannerService that broadcast is over");
     resultReceiver.send(1, new Bundle());
     finish();
   } else {
     Log.w(Constants.TAG, "Discovery already finished. Maybe the discovery finish is late?");
   }
 }
示例#12
0
 @Override
 protected final void onHandleIntent(Intent intent) {
   String action = intent.getAction();
   Bundle data = intent.getExtras();
   if (data == null) {
     data = new Bundle();
   }
   ResultReceiver resultReceiver = data.getParcelable(EXTRA_RESULT_RECEIVER);
   data.putString(EXTRA_ACTION, action);
   try {
     data = onExecute(action, data);
     if (resultReceiver != null) {
       resultReceiver.send(RESULT_OK, data);
     }
   } catch (Exception e) {
     L.w(e);
     if (resultReceiver != null) {
       data.putSerializable(EXTRA_EXCEPTION, e);
       resultReceiver.send(RESULT_CANCELED, data);
     }
   }
 }
  public boolean addReceiver(ResultReceiver receiver, boolean resentLast) {
    boolean isAdded = false;

    if (receiver == null) return false;
    if (!mReceivers.contains(receiver)) {
      mReceivers.add(receiver);
      isAdded = true;
    }

    if (resentLast) receiver.send(mResultCode, mResultData);

    return isAdded;
  }
  @Override
  public void onSensorChanged(SensorEvent event) {
    Sensor mySensor = event.sensor;

    if (mySensor.getType() == Sensor.TYPE_ACCELEROMETER) {
      float x = event.values[0];
      float y = event.values[1];
      float z = event.values[2];

      long curTime = System.currentTimeMillis();

      if ((curTime - lastUpdate) > SAMPLE_WINDOW_SIZE) {
        long diffTime = (curTime - lastUpdate);
        lastUpdate = curTime;

        float speed = Math.abs(x + y + z - last_x - last_y - last_z) / diffTime * 10000;

        if (speed > SHAKE_THRESHOLD) {
          Log.w(onSensorChangedTag, "THRESHOLD HIT. ACCEL FAILED.");
          senSensorManager.unregisterListener(this, senAccelerometer);
          Bundle bundle = new Bundle();
          bundle.putString(IntentConfig.RESULT_KEY, IntentConfig.RESULT_FAILED);
          mResultReceiver.send(IntentConfig.ACCELEROMETER, bundle);
        }
        last_x = x;
        last_y = y;
        last_z = z;
      }

      if ((curTime - firstTime) > TIME_THRES) {
        Log.d(onSensorChangedTag, "ACCEL PASSED");
        senSensorManager.unregisterListener(this, senAccelerometer);
        Bundle bundle = new Bundle();
        bundle.putString(IntentConfig.RESULT_KEY, IntentConfig.RESULT_PASSED);
        mResultReceiver.send(IntentConfig.ACCELEROMETER, bundle);
      }
    }
  }
示例#15
0
  @Override
  protected void onHandleIntent(Intent intent) {
    BaseCommand command = intent.getExtras().getParcelable(ARG_COMMAND_CLASS);
    ResultReceiver result = intent.getExtras().getParcelable(ARG_RESULT_RECEIVER);

    try {
      EventCallback event = command.execute(this);
      Bundle bundle = new Bundle();
      bundle.putParcelable(ARG_RESULT_BASE_EVENT, event);
      result.send(Activity.RESULT_OK, bundle);
    } catch (Exception e) {
      logError(intent, result, e);
    }
  }
  @Override
  protected void onReceiveResult(int resultCode, Bundle resultData) {
    boolean sentOnce = false;

    mResultCode = resultCode;
    mResultData = resultData;

    for (ResultReceiver receiver : mReceivers) {
      receiver.send(resultCode, resultData);
      sentOnce = true;
    }

    if (!sentOnce)
      Log.w(TAG, "Dropping result on floor for code " + resultCode + ": " + resultData.toString());
  }
  /**
   * Finishes activity with {@link Activity#RESULT_OK}.
   *
   * @param pattern the pattern, if this is in mode creating pattern. In any cases, it can be set to
   *     {@code null}.
   */
  private void finishWithResultOk(char[] pattern) {
    if (ACTION_CREATE_PATTERN.equals(getIntent().getAction()))
      mIntentResult.putExtra(EXTRA_PATTERN, pattern);
    else {
      /*
       * If the user was "logging in", minimum try count can not be zero.
       */
      mIntentResult.putExtra(EXTRA_RETRY_COUNT, mRetryCount + 1);
    }

    setResult(RESULT_OK, mIntentResult);

    /*
     * ResultReceiver
     */
    ResultReceiver receiver = getIntent().getParcelableExtra(EXTRA_RESULT_RECEIVER);
    if (receiver != null) {
      Bundle bundle = new Bundle();
      if (ACTION_CREATE_PATTERN.equals(getIntent().getAction()))
        bundle.putCharArray(EXTRA_PATTERN, pattern);
      else {
        /*
         * If the user was "logging in", minimum try count can not be
         * zero.
         */
        bundle.putInt(EXTRA_RETRY_COUNT, mRetryCount + 1);
      }
      receiver.send(RESULT_OK, bundle);
    }

    /*
     * PendingIntent
     */
    PendingIntent pi = getIntent().getParcelableExtra(EXTRA_PENDING_INTENT_OK);
    if (pi != null) {
      try {
        pi.send(this, RESULT_OK, mIntentResult);
      } catch (Throwable t) {
        Log.e(CLASSNAME, "Error sending PendingIntent: " + pi, t);
      }
    }

    finish();
  } // finishWithResultOk()
  private void getProducts(ResultReceiver receiver, Bundle b, String query)
      throws ClientProtocolException, IOException, Exception {
    Log.d(TAG, "OK in getCategories ");
    final DefaultHttpClient client = new DefaultHttpClient();
    final HttpResponse response =
        client.execute(
            new HttpGet(
                "http://eiffel.itba.edu.ar/hci/service/Catalog.groovy"
                    + "?method=GetProductListByName&criteria="
                    + query));
    if (response.getStatusLine().getStatusCode() != 200) {
      throw new IllegalArgumentException(response.getStatusLine().toString());
    }

    final String xmlToParse = EntityUtils.toString(response.getEntity());

    b.putSerializable("return", (Serializable) fromXMLtoProduct(xmlToParse));
    receiver.send(STATUS_OK, b);
  }
示例#19
0
  protected final void finishWithResultOk(char[] pattern) {
    if (LockPatternType.CREATE_PATTERN == lockPatternType) {
      if (autoSave) {
        AlpSettings.Security.setPattern(this, pattern);
      }
      intentResult.putExtra(EXTRA_PATTERN, pattern);
    } else {
      intentResult.putExtra(EXTRA_RETRY_COUNT, retryCount);
    }

    setResult(Activity.RESULT_OK, intentResult);

    /** ResultReceiver */
    ResultReceiver receiver = getIntent().getParcelableExtra(EXTRA_RESULT_RECEIVER);
    if (receiver != null) {
      Bundle bundle = new Bundle();
      if (LockPatternType.CREATE_PATTERN == lockPatternType)
        bundle.putCharArray(EXTRA_PATTERN, pattern);
      else {
        /** If the user was "logging in", minimum try count can not be zero. */
        bundle.putInt(EXTRA_RETRY_COUNT, retryCount);
      }
      bundle.putSerializable(EXTRA_LOCK_PATTERN_TYPE, lockPatternType);
      bundle.putBoolean(EXTRA_IS_MODIFY, isModify());
      receiver.send(Activity.RESULT_OK, bundle);
    }

    /** PendingIntent */
    PendingIntent pi = getIntent().getParcelableExtra(EXTRA_PENDING_INTENT_OK);
    if (pi != null) {
      try {
        pi.send(this, Activity.RESULT_OK, intentResult);
      } catch (Throwable t) {
        Log.e(CLASSNAME, "Error sending PendingIntent: " + pi, t);
      }
    }

    finish();
  }
  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // this method is invoked with an CANCELED result code if the activity is a "singleInstance"
    // (launchMode)
    // that is the reason that we removed that launch mode for the AndroidManifest (see SVN logs)
    LOG.LogDebug(
        Module.GUI,
        "******** onActivityResult # requestCode " + requestCode + ", resultCode: " + resultCode);

    AndroidActivityManager aam =
        (AndroidActivityManager)
            AndroidServiceLocator.GetInstance()
                .GetService(AndroidServiceLocator.SERVICE_ANDROID_ACTIVITY_MANAGER);
    boolean handleResult = false;
    if (aam != null) {
      handleResult = aam.publishActivityResult(requestCode, resultCode, data);
    }

    if (!handleResult) {

      ResultReceiver resultReceiver =
          ((AndroidServiceLocator) AndroidServiceLocator.GetInstance())
              .getResultReceiver(requestCode);

      if (resultReceiver != null) {
        LOG.LogDebug(
            Module.GUI, "******** Calling ResultReceiver send  (probably from a module)...");
        Bundle bundle = (data == null ? new Bundle() : data.getExtras());
        bundle.putInt(IAppDelegate.ACTIVITY_RESULT_CODE_BUNDLE_KEY, resultCode);
        resultReceiver.send(requestCode, bundle);

      } else {

        LOG.LogDebug(Module.GUI, "******** Calling super.onActivityResult()");
        super.onActivityResult(requestCode, resultCode, data);
      }
    }
  }
示例#21
0
  /**
   * Gets the teams provided by the service and persist them.
   *
   * @param receiver Receiver object which is used to send data about download progress of teams.
   */
  private void getAllTeamsAndPersistThem(ResultReceiver receiver) {
    Log.d(LOG_TAG, "Reached getAllTeamsAndPersistThem");
    DaoHelper daoHelper = new DaoHelper(this);

    if (daoHelper.getTeamCount() == 226) {
      activeSpinner(SPINNER_NOT_ACTIVE);
      return;
    }

    final ArrayList<String> leagues = new ArrayList<>();
    leagues.add("394");
    leagues.add("395");
    leagues.add("396");
    leagues.add("397");
    leagues.add("398");
    leagues.add("399");
    leagues.add("400");
    leagues.add("401");
    leagues.add("402");
    leagues.add("403");
    leagues.add("404");
    leagues.add("405");

    ArrayList<Team> teams = new ArrayList<>();

    for (String league : leagues) {
      try {
        URL url = createSeasonTeamUrl(league);
        String result = RestClient.getData(url.toString(), getString(R.string.api_key));

        ArrayList<Team> teamsTemp = Parser.parseTeams(result);
        teams.addAll(teamsTemp);

      } catch (MalformedURLException urlEx) {
        Log.e(LOG_TAG, "Error ", urlEx);
      } catch (IOException e) {
        Log.e(LOG_TAG, "Error ", e);
      }
    }

    // workaround - change http header per https
    changeHeaderForRequestHttps(teams);

    Vector<ContentValues> values = new Vector<>(leagues.size());
    int load = 0;
    for (Team team : teams) {

      if (null != team) {
        ContentValues teamValues = new ContentValues();
        teamValues.put(DatabaseContract.TeamEntry._ID, team.getId());
        teamValues.put(DatabaseContract.TeamEntry.NAME, team.getName());
        teamValues.put(DatabaseContract.TeamEntry.SHORT_NAME, team.getShortName());
        teamValues.put(DatabaseContract.TeamEntry.THUMBNAIL, team.getThumbnail());
        values.add(teamValues);
        Log.d("item downloaded", String.valueOf(team.getId()));
      }

      // data that will be send into ResultReceiver
      Bundle data = new Bundle();
      data.putInt(PROGRESS, ++load);

      // sends progress into ResultReceiver located in your Activity
      receiver.send(NEW_PROGRESS, data);
    }

    // activeSpinner(SPINNER_ACTIVE);
    insertData(values);
    activeSpinner(SPINNER_NOT_ACTIVE);
  }
  @Override
  protected void onHandleIntent(Intent intent) {

    // Get the extras from the intent
    mode = intent.getStringExtra("archive");
    final ResultReceiver mReceiver = intent.getParcelableExtra("receiver");
    String url = intent.getStringExtra("url");
    intentMode = intent.getStringExtra("mode");

    // Retrieve the latest timestamp from the prefs for fetching latest data
    prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    mPreviousPing = prefs.getString("latestPing", "0");
    Log.d(TAG, mPreviousPing);
    jsonParser = new JSONParser();
    Log.d(TAG, "Service Started");

    if (!TextUtils.isEmpty(url)) {

      mReceiver.send(STATUS_RUNNING, Bundle.EMPTY);
      try {
        // Fetch the data from the server in Json Format
        // and send it to the calling fragment
        // Also send the latest timestamp so that we can get the updates
        // from that particular time and not the whole data as such.
        JSONObject json = jsonParser.makeHttpGetRequest(url, "GET", mPreviousPing);

        // Parse the json data send it to the feed fragment which implements
        // the ResultReceiver. We also send the status of the service along with it.
        if (json.getInt("count") > 0) {
          Log.d(TAG, json.toString());
          Bundle results = parseJsonFeed(json);
          if (results != null && !(results.isEmpty())) {
            latestData = results;
            mReceiver.send(STATUS_FINISHED, results);
            Log.d(TAG, "Checking mode: " + mode);

            // If the service started from the BroadcastReceiver fetches some data,
            // We would want to notify the user.
            if (intentMode.equals("receiver")) {
              Intent emptyIntent = new Intent(this, Welcome.class);
              PendingIntent pendingIntent =
                  PendingIntent.getActivity(
                      this, 0, emptyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
              NotificationCompat.Builder mBuilder =
                  new NotificationCompat.Builder(this)
                      .setSmallIcon(R.drawable.gc_launcher)
                      .setContentTitle("Feed Updates Available")
                      .setContentText("Please check your feed for updates!")
                      .setContentIntent(pendingIntent);
              NotificationManager notificationManager =
                  (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
              notificationManager.notify(1, mBuilder.build());
            }
          } else {
            Bundle error = new Bundle();
            error.putString("error", "Something's Wrong. Please try again later.");
            mReceiver.send(STATUS_ERROR, error);
          }
        } else {
          // The fetched data is null.
          // Send the status to the feedFragment specifying null data
          Log.d(TAG, "Null object");
          Bundle nullBundle = new Bundle();
          nullBundle.putString("nullJSON", "Could not fetch data from server.Please try again");
          mReceiver.send(STATUS_ERROR, nullBundle);
        }
      } catch (Exception js) {
        js.printStackTrace();
      }
    }
  }
 public void signalActivity(String message) {
   Bundle b = new Bundle();
   b.putString("message", message);
   serverResult.send(port, b);
 }
  private String login(int... ids) {
    Log.d(TAG, "login(ids... method start");
    String result = "";
    String result2 = "";
    ArrayList<RecipeGeneral> recipes = null;
    try {
      DefaultHttpClient httpclient = new DefaultHttpClient();
      HttpGet httpget = new HttpGet(Constants.URL_LOGIN);
      httpget.setHeader("Accept", "application/json");

      HttpResponse response = httpclient.execute(httpget);
      HttpEntity entity = response.getEntity();
      Log.d(TAG, "Login form get: " + response.getStatusLine());
      Log.d(TAG, "Entity: " + entity.toString());
      if (entity != null) {
        result = HttpFactory.convertStreamToString(entity.getContent());
        Log.d(TAG, "Result: " + result);
      }

      List<Cookie> cookies = httpclient.getCookieStore().getCookies();
      if (cookies.isEmpty()) {
        Log.d(TAG, "No cookies");
      } else {
        for (int i = 0; i < cookies.size(); i++) {
          Log.d(TAG, "Cookies: " + cookies.get(i).toString());
        }
      }

      JSONObject jsonResponse = new JSONObject(result.trim());
      Log.d(TAG, "jsonResponce: " + jsonResponse.toString());
      String token_value = jsonResponse.getString("token_value");
      String token_name = jsonResponse.getString("token_name");
      Log.d(TAG, "token_value: " + token_value);
      Log.d(TAG, "token_name: " + token_name);

      HttpPost httpost = new HttpPost(Constants.URL_LOGIN);
      httpost.setHeader("Accept", "application/json");

      List<NameValuePair> nvps = new ArrayList<NameValuePair>();
      nvps.add(new BasicNameValuePair("user[email]", login));
      nvps.add(new BasicNameValuePair("user[password]", password));
      nvps.add(new BasicNameValuePair(token_name, token_value));

      httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

      HttpResponse response1 = httpclient.execute(httpost);
      HttpEntity entity1 = response1.getEntity();

      Log.d(TAG, "Login form post: " + response1.getStatusLine());
      if (entity1 != null) {
        result = HttpFactory.convertStreamToString(entity1.getContent());
        Log.d(TAG, "Entity: " + result);
      }

      StringBuilder idsParams = new StringBuilder();
      for (int id : ids) {
        idsParams.append("&ids[]=" + id);
      }
      HttpGet httpget2 = new HttpGet(Constants.URL_SYNC + "?ids[]=0" + idsParams);
      httpget2.setHeader("Accept", "application/json");
      Log.d(TAG, "Request line: " + httpget2.getRequestLine());
      Log.d(TAG, "Request params: " + httpget2.getParams());
      Log.d(TAG, "Request uri: " + httpget2.getURI());

      HttpResponse response2 = httpclient.execute(httpget2);
      HttpEntity entity2 = response2.getEntity();

      Log.d(TAG, "Login form get2: " + response2.getStatusLine());
      Log.d(TAG, "Entity2: " + entity2.toString());

      if (entity2 != null) {
        result2 = HttpFactory.convertStreamToString(entity2.getContent());
        Log.d(TAG, "Result2: " + result2);
      }

      List<Cookie> cookies2 = httpclient.getCookieStore().getCookies();
      if (cookies2.isEmpty()) {
        Log.d(TAG, "No cookies2 ");
      } else {
        for (int i = 0; i < cookies2.size(); i++) {
          Log.d(TAG, "Cookies2 : " + cookies2.get(i).toString());
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
      receiver.send(Constants.AUTHORIZATION_NOT_PASSED, null);
    }
    return result2;
  }
  @Override
  protected void onHandleIntent(Intent intent) {

    port = ((Integer) intent.getExtras().get("port")).intValue();
    saveLocation = (File) intent.getExtras().get("saveLocation");
    serverResult = (ResultReceiver) intent.getExtras().get("serverResult");

    // signalActivity("Starting to download");

    String fileName = "";

    ServerSocket welcomeSocket = null;
    Socket socket = null;

    try {

      welcomeSocket = new ServerSocket(port);

      while (true && serviceEnabled) {

        // Listen for incoming connections on specified port
        // Block thread until someone connects
        socket = welcomeSocket.accept();

        // signalActivity("TCP Connection Established: " + socket.toString() + " Starting file
        // transfer");

        InputStream is = socket.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);

        OutputStream os = socket.getOutputStream();
        PrintWriter pw = new PrintWriter(os);

        String inputData = "";

        signalActivity("About to start handshake");
        // Client-Server handshake

        /*
        String test = "Y";
        test = test + br.readLine() + test;


        signalActivity(test);
         */

        /*
        inputData = br.readLine();

        if(!inputData.equals("wdft_client_hello"))
        {
        	throw new IOException("Invalid WDFT protocol message");

        }

        pw.println("wdft_server_hello");


        inputData = br.readLine();


        if(inputData == null)
        {
        	throw new IOException("File name was null");

        }


        fileName = inputData;

        pw.println("wdft_server_ready");

        */

        // signalActivity("Handshake complete, getting file: " + fileName);

        String savedAs = "WDFL_File_" + System.currentTimeMillis();
        File file = new File(saveLocation, savedAs);

        byte[] buffer = new byte[4096];
        int bytesRead;

        FileOutputStream fos = new FileOutputStream(file);
        BufferedOutputStream bos = new BufferedOutputStream(fos);

        while (true) {
          bytesRead = is.read(buffer, 0, buffer.length);
          if (bytesRead == -1) {
            break;
          }
          bos.write(buffer, 0, bytesRead);
          bos.flush();
        }

        /*
        fos.close();
        bos.close();

        br.close();
        isr.close();
        is.close();

        pw.close();
        os.close();

        socket.close();
        */

        bos.close();
        socket.close();

        signalActivity("File Transfer Complete, saved as: " + savedAs);
        // Start writing to file

      }

    } catch (IOException e) {
      signalActivity(e.getMessage());

    } catch (Exception e) {
      signalActivity(e.getMessage());
    }

    // Signal that operation is complete
    serverResult.send(port, null);
  }
示例#26
0
 private void logError(Intent intent, ResultReceiver result, Exception e) {
   Timber.e(Log.getStackTraceString(e));
   result.send(Activity.RESULT_CANCELED, intent.getExtras());
 }
示例#27
0
  @Override
  protected void onHandleIntent(Intent intent) {
    try {
      rec = intent.getParcelableExtra("receiverTag");
      String user = intent.getStringExtra("username");
      String pass = intent.getStringExtra("password");
      String login = "******";
      URL urlForLogin = new URL(login);
      conn = (HttpsURLConnection) urlForLogin.openConnection();
      conn.setRequestMethod("GET");
      conn.setRequestProperty("Cookie", "utmccn=(referral)");
      conn.setRequestProperty("Accept", "text/html, application/xhtml+xml, */*");
      conn.setRequestProperty("Accept-Language", "en-US");
      conn.setRequestProperty(
          "User-Agent", "Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D)");
      conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
      conn.setRequestProperty("Host", "login.gatech.edu");
      conn.setRequestProperty("DNT", "1");
      conn.setRequestProperty("Connection", "Keep-Alive");
      String cookie = conn.getHeaderField("Set-Cookie"); // Real usage
      String js = parseJsession(cookie); // URL usage
      cookie = (cookie.split(";", 2)[0]);
      BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      String LT = "                        <input type=\"hidden\" name=\"lt\" value=\"";
      String input;
      // LT parameter algorithm
      while ((input = in.readLine()) != null) {
        if (input.startsWith("                        <input type=\"hidden\" name=\"lt\" value="))
          LT = input.substring(LT.length(), input.length() - 4);
      }

      strForHtml = login + js;
      Log.d("StrForHTML:", strForHtml);
      Log.d("LT:", LT);
      URL urlForHtml = new URL(strForHtml);
      conn = (HttpsURLConnection) urlForHtml.openConnection();
      conn.setRequestMethod("POST");
      conn.setRequestProperty("Cookie", cookie + ";utmccn=(referral)");
      conn.setRequestProperty("Accept", "text/html, application/xhtml+xml, */*");
      conn.setRequestProperty("Accept-Language", "en-US");
      conn.setRequestProperty(
          "User-Agent", "Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D)");
      conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
      conn.setRequestProperty("Host", "login.gatech.edu");
      conn.setRequestProperty("DNT", "1");
      conn.setRequestProperty("Connection", "Keep-Alive");
      conn.setRequestProperty("Referer", "https://login.gatech.edu/cas/login");
      conn.setRequestProperty("Cache-Control", "no-cache");
      conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
      String urlParameters =
          "username="******"&password="******"&lt="
              + LT
              + "&execution=e1s1"
              + "&_eventId=submit&submit=LOGIN";
      conn.setDoOutput(true);
      DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
      wr.writeBytes(urlParameters);
      wr.flush();
      wr.close();

      in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      String inputLine;
      StringBuffer html = new StringBuffer();

      while ((inputLine = in.readLine()) != null) {
        if (inputLine.contains("class=\"errors\"")) {
          html.append(inputLine);
        }
      }
      in.close();

      if (!html.toString().contains("class=\"errors\"")) {
        Log.e("check", "Loged in successfully");
        Bundle b = new Bundle();
        b.putBoolean("ServiceTag", true);
        rec.send(0, b);
      } else {
        Log.e("check", "Wrong username or password!");
        Bundle b = new Bundle();
        b.putBoolean("ServiceTag", false);
        rec.send(0, b);
      }
    } catch (Throwable e) {
      Log.e("check", "ERROR");
    }
  }
示例#28
0
    @Override
    public void handleMessage(Message msg) {
      if (msg == null) {
        Log.e(TAG, "Msg was null?");
        return;
      }

      Buffer buffer;
      IrcMessage message;
      switch (msg.what) {
        case R.id.CORECONNECTION_NEW_BACKLOGITEM_TO_SERVICE:
          /** New message on one buffer so update that buffer with the new message */
          message = (IrcMessage) msg.obj;
          buffer = bufferCollection.getBuffer(message.bufferInfo.id);
          if (buffer == null) {
            Log.e(TAG, "A messages buffer is null:" + message);
            return;
          }

          if (!buffer.hasMessage(message)) {
            /**
             * Check if we are highlighted in the message, TODO: Add support for custom highlight
             * masks
             */
            checkMessageForHighlight(buffer, message);
            checkForURL(message);
            parseColorCodes(message);
            parseStyleCodes(message);
            buffer.addBacklogMessage(message);
          } else {
            Log.e(TAG, "Getting message buffer already have " + buffer.getInfo().name);
          }
          break;
        case R.id.CORECONNECTION_NEW_MESSAGE_TO_SERVICE:
          /** New message on one buffer so update that buffer with the new message */
          message = (IrcMessage) msg.obj;
          buffer = bufferCollection.getBuffer(message.bufferInfo.id);
          if (buffer == null) {
            Log.e(TAG, "A messages buffer is null: " + message);
            return;
          }

          if (!buffer.hasMessage(message)) {
            /**
             * Check if we are highlighted in the message, TODO: Add support for custom highlight
             * masks
             */
            checkMessageForHighlight(buffer, message);
            parseColorCodes(message);
            parseStyleCodes(message);
            if (message.isHighlighted()) {
              // Create a notification about the highlight
              String text =
                  buffer.getInfo().name + ": <" + message.getNick() + "> " + message.content;
              Notification notification =
                  new Notification(R.drawable.highlight, text, System.currentTimeMillis());
              Intent launch = new Intent(CoreConnService.this, BufferActivity.class);
              launch.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
              PendingIntent contentIntent =
                  PendingIntent.getActivity(CoreConnService.this, 0, launch, 0);
              // Set the info for the views that show in the
              // notification panel.
              notification.setLatestEventInfo(
                  CoreConnService.this, getText(R.string.app_name), text, contentIntent);
              // Send the notification.
              notifyManager.notify(R.id.NOTIFICATION_HIGHLIGHT, notification);
            }

            checkForURL(message);
            buffer.addMessage(message);
          } else {
            Log.e(TAG, "Getting message buffer already have " + buffer.toString());
          }
          break;

        case R.id.CORECONNECTION_NEW_BUFFER_TO_SERVICE:
          /** New buffer received, so update out channel holder with the new buffer */
          buffer = (Buffer) msg.obj;
          bufferCollection.addBuffer(buffer);

          break;
        case R.id.CORECONNECTION_ADD_MULTIPLE_BUFFERS:
          /** Complete list of buffers received */
          bufferCollection.addBuffers((Collection<Buffer>) msg.obj);
          break;

        case R.id.CORECONNECTION_SET_LAST_SEEN_TO_SERVICE:
          /** Setting last seen message id in a buffer */
          if (bufferCollection.hasBuffer(msg.arg1)) {
            bufferCollection.getBuffer(msg.arg1).setLastSeenMessage(msg.arg2);
          } else {
            Log.e(TAG, "Getting set last seen message on unknown buffer: " + msg.arg1);
          }
          break;
        case R.id.CORECONNECTION_SET_MARKERLINE_TO_SERVICE:
          /** Setting marker line message id in a buffer */
          if (bufferCollection.hasBuffer(msg.arg1)) {
            bufferCollection.getBuffer(msg.arg1).setMarkerLineMessage(msg.arg2);
          } else {
            Log.e(TAG, "Getting set marker line message on unknown buffer: " + msg.arg1);
          }
          break;

        case R.id.CORECONNECTION_CONNECTED:
          /** CoreConn has connected to a core */
          showNotification(true);
          for (ResultReceiver statusReceiver : statusReceivers) {
            statusReceiver.send(CoreConnService.CONNECTION_CONNECTED, null);
          }
          break;

        case R.id.CORECONNECTION_LOST_CONNECTION:
          /** Lost connection with core, update notification */
          for (ResultReceiver statusReceiver : statusReceivers) {
            if (msg.obj != null) { // Have description of what is wrong,
              // used only for login atm
              Bundle bundle = new Bundle();
              bundle.putString(CoreConnService.STATUS_KEY, (String) msg.obj);
              statusReceiver.send(CoreConnService.CONNECTION_DISCONNECTED, bundle);
            } else {
              statusReceiver.send(CoreConnService.CONNECTION_DISCONNECTED, null);
            }
          }
          showNotification(false);
          break;

        case R.id.CORECONNECTION_NEW_USERLIST_ADDED:
          /** Initial list of users */
          ArrayList<IrcUser> users = (ArrayList<IrcUser>) msg.obj;
          for (IrcUser user : users) {
            newUser(user);
          }
          break;

        case R.id.CORECONNECTION_NEW_USER_ADDED:
          /** New IrcUser added */
          IrcUser user = (IrcUser) msg.obj;
          newUser(user);
          break;

        case R.id.CORECONNECTION_SET_BUFFER_ORDER:
          /** Buffer order changed so set the new one */
          bufferCollection.getBuffer(msg.arg1).setOrder(msg.arg2);
          break;

        case R.id.CORECONNECTION_SET_BUFFER_TEMP_HIDDEN:
          /** Buffer has been marked as temporary hidden, update buffer */
          bufferCollection.getBuffer(msg.arg1).setTemporarilyHidden((Boolean) msg.obj);
          break;

        case R.id.CORECONNECTION_SET_BUFFER_PERM_HIDDEN:
          /** Buffer has been marked as permanently hidden, update buffer */
          bufferCollection.getBuffer(msg.arg1).setPermanentlyHidden((Boolean) msg.obj);
          break;

        case R.id.CORECONNECTION_INVALID_CERTIFICATE:
          /** Received a mismatching certificate */
        case R.id.CORECONNECTION_NEW_CERTIFICATE:
          /** Received a new, unseen certificate */
          Bundle bundle = new Bundle();
          bundle.putString(CERT_KEY, (String) msg.obj);
          for (ResultReceiver statusReceiver : statusReceivers) {
            statusReceiver.send(CoreConnService.NEW_CERTIFICATE, bundle);
          }
          break;
        case R.id.CORECONNECTION_SET_BUFFER_ACTIVE:
          /** Set buffer as active or parted */
          bufferCollection.getBuffer(msg.arg1).setActive((Boolean) msg.obj);
          break;
        case R.id.CORECONNECTION_UNSUPPORTED_PROTOCOL:
          /** The protocol version of the core is not supported so tell user it is to old */
          for (ResultReceiver statusReceiver : statusReceivers) {
            statusReceiver.send(CoreConnService.UNSUPPORTED_PROTOCOL, null);
          }
      }
    }