Ejemplo n.º 1
1
 public void onRadioButtonClicked(View v) {
   if (v.getId() == R.id.group_closed_radio) {
     groupLogo.setImageResource(R.drawable.group_closed);
     groupLogo.setBackgroundColor(R.color.color_primary);
     groupTypeDescr.setText(R.string.group_closed_description);
     Log.e(
         TAG,
         "Cliccato: "
             + v.getId()
             + "! Setto: "
             + R.drawable.group_closed
             + ", "
             + R.color.color_primary
             + ", "
             + R.string.group_closed_description);
   } else if (v.getId() == R.id.group_open_radio) {
     groupLogo.setImageResource(R.drawable.group_open);
     groupLogo.setBackgroundColor(R.color.color_primary);
     groupTypeDescr.setText(R.string.group_open_description);
     Log.e(
         TAG,
         "Cliccato: "
             + v.getId()
             + "! Setto: "
             + R.drawable.group_open
             + ", "
             + R.color.color_primary
             + ", "
             + R.string.group_open_description);
   }
 }
Ejemplo n.º 2
1
        @Override
        public void onReceive(Context context, Intent intent) {
          if (intent.getAction().equals(ACTION_CANCEL_DOWNLOAD)) {
            String url = intent.getStringExtra(EXTRA_DOWNLOAD_URL);
            if (url == null) {
              throw new IllegalArgumentException(
                  "ACTION_CANCEL_DOWNLOAD intent needs download url extra");
            }
            if (AppConfig.DEBUG) Log.d(TAG, "Cancelling download with url " + url);
            Downloader d = getDownloader(url);
            if (d != null) {
              d.cancel();
            } else {
              Log.e(TAG, "Could not cancel download with url " + url);
            }

          } else if (intent.getAction().equals(ACTION_CANCEL_ALL_DOWNLOADS)) {
            for (Downloader d : downloads) {
              d.cancel();
              if (AppConfig.DEBUG) Log.d(TAG, "Cancelled all downloads");
            }
            sendBroadcast(new Intent(ACTION_DOWNLOADS_CONTENT_CHANGED));
          }
          queryDownloads();
        }
Ejemplo n.º 3
1
  public static String submitPostData(String pos, String data) throws IOException {
    Log.v("req", data);

    URL url = new URL(urlPre + pos);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    configConnection(connection);
    if (sCookie != null && sCookie.length() > 0) {
      connection.setRequestProperty("Cookie", sCookie);
    }
    connection.connect();

    // Send data
    DataOutputStream output = new DataOutputStream(connection.getOutputStream());
    output.write(data.getBytes());
    output.flush();
    output.close();

    // check Cookie
    String cookie = connection.getHeaderField("set-cookie");
    if (cookie != null && !cookie.equals(sCookie)) {
      sCookie = cookie;
    }

    // Respond
    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
      sb.append(line + "\n");
    }
    connection.disconnect();
    String res = sb.toString();
    Log.v("res", res);
    return res;
  }
Ejemplo n.º 4
1
 private static void drawToast(View v, Rect vRect) {
   // TODO Auto-generated method stub
   if (mToast != null) {
     View tv = mToast.getView();
     if (tv.getWidth() > 0 && tv.isShown()) {
       if (LOGD_ENABLED) Log.i(LOG_TAG, "==== " + tv.getWidth() + " " + tv.getHeight());
       Bitmap second = Utils.createPngScreenshot(tv, tv.getWidth(), tv.getHeight(), 0);
       if (LOGD_ENABLED)
         Log.d(
             LOG_TAG,
             "====== gravity "
                 + mToast.getGravity()
                 + " x y "
                 + mToast.getXOffset()
                 + " "
                 + mToast.getYOffset()
                 + " "
                 + mToast.getHorizontalMargin()
                 + " "
                 + mToast.getVerticalMargin());
       PointF fromPoint =
           new PointF(
               (v.getWidth() - tv.getWidth()) / 2,
               v.getHeight() - vRect.top - mToast.getYOffset() - tv.getHeight());
       if (LOGD_ENABLED)
         Log.i(LOG_TAG, "======= prepare menu view2  ========" + fromPoint.x + " " + fromPoint.y);
       mCapture = Utils.mixtureBitmap2(mCapture, second, fromPoint, 0, (float) 1.0);
     }
   }
 }
Ejemplo n.º 5
0
  private void openVideo() {
    if (mUri == null || mSurfaceHolder == null) {
      // not ready for playback just yet, will try again later
      return;
    }

    if (mMediaPlayer != null) {
      mMediaPlayer.reset();
      mMediaPlayer.release();
      mMediaPlayer = null;
    }
    try {
      mMediaPlayer = new MediaPlayer();
      mMediaPlayer.setOnPreparedListener(mPreparedListener);
      mIsPrepared = false;
      mMediaPlayer.setOnCompletionListener(mCompletionListener);
      mMediaPlayer.setOnErrorListener(mErrorListener);
      mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener);
      mCurrentBufferPercentage = 0;
      mMediaPlayer.setDataSource(mContext, mUri);
      mMediaPlayer.setDisplay(mSurfaceHolder);
      mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
      mMediaPlayer.setScreenOnWhilePlaying(true);
      mMediaPlayer.prepareAsync();
      attachMediaController();
    } catch (IOException ex) {
      Log.w("VideoView", "Unable to open content: " + mUri, ex);
      return;
    } catch (IllegalArgumentException ex) {
      Log.w("VideoView", "Unable to open content: " + mUri, ex);
      return;
    }
  }
Ejemplo n.º 6
0
 public void stop() {
   Log.d("MandelbrotView", "stoping...");
   if (fractalRequest != null) {
     fractalRequest.cancel();
   }
   Log.d("MandelbrotView", "stoped...");
 }
Ejemplo n.º 7
0
  @Override
  protected void onResume() {

    Log.d("", "resume activity tab");
    if (AppMain.isphone) {
      if (AppMain.isGotoshelf) {
        Log.d("", "Go to shelf");
        if (AppMain.isphone) {
          mTabHost.setCurrentTabByTag("Tab5");
          AppMain.isGotoshelf = false;
        } else {
          mTabHost.setCurrentTabByTag("Tab5");
          AppMain.isGotoshelf = false;
        }
      }
    } else {

      if (AppMain.isGotoshelf) {
        Log.d("", "Go to shelf");
        if (AppMain.isphone) {
          mTabHost.setCurrentTabByTag("Tab4");
          AppMain.isGotoshelf = false;
        } else {
          mTabHost.setCurrentTabByTag("Tab4");
          AppMain.isGotoshelf = false;
        }
      }
    }

    super.onResume();
  }
  /** Called each time a new audio device has been added or removed. */
  private void onAudioManagerChangedState() {
    Log.d(
        TAG,
        "onAudioManagerChangedState: devices="
            + audioDevices
            + ", selected="
            + selectedAudioDevice);

    // Enable the proximity sensor if there are two available audio devices
    // in the list. Given the current implementation, we know that the choice
    // will then be between EARPIECE and SPEAKER_PHONE.
    if (audioDevices.size() == 2) {
      AppRTCUtils.assertIsTrue(
          audioDevices.contains(AudioDevice.EARPIECE)
              && audioDevices.contains(AudioDevice.SPEAKER_PHONE));
      // Start the proximity sensor.
      proximitySensor.start();
    } else if (audioDevices.size() == 1) {
      // Stop the proximity sensor since it is no longer needed.
      proximitySensor.stop();
    } else {
      Log.e(TAG, "Invalid device list");
    }

    if (onStateChangeListener != null) {
      // Run callback to notify a listening client. The client can then
      // use public getters to query the new state.
      onStateChangeListener.run();
    }
  }
Ejemplo n.º 9
0
  @Override
  public void onReceive(Context context, Intent intent) {
    Log.d(this.getClass().toString(), "alarm received");
    NotificationManager notificationManager =
        (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    Intent notificationIntent = new Intent(context, HourlyreminderActivity.class);
    PendingIntent pendingIntent =
        PendingIntent.getActivity(
            context, REQUESTCODE, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    Notification.Builder builder = new Notification.Builder(context);
    builder
        .setContentIntent(pendingIntent)
        .setSmallIcon(R.drawable.alarm_icon)
        .setTicker(context.getString(R.string.notification_status_bar_text))
        .setWhen(System.currentTimeMillis())
        .setAutoCancel(true)
        .setDefaults(Notification.DEFAULT_ALL)
        .setContentTitle(context.getString(R.string.notification_title))
        .setContentText(context.getString(R.string.notification_message));
    Notification notification = builder.getNotification();
    // TODO: text updaten bij meerdere

    notificationManager.notify(1, notification);
    Log.d(this.getClass().toString(), "notification send");
  }
 public static void setBestExposure(Camera.Parameters parameters, boolean lightOn) {
   int minExposure = parameters.getMinExposureCompensation();
   int maxExposure = parameters.getMaxExposureCompensation();
   float step = parameters.getExposureCompensationStep();
   if ((minExposure != 0 || maxExposure != 0) && step > 0.0f) {
     // Set low when light is on
     float targetCompensation = lightOn ? MIN_EXPOSURE_COMPENSATION : MAX_EXPOSURE_COMPENSATION;
     int compensationSteps = Math.round(targetCompensation / step);
     float actualCompensation = step * compensationSteps;
     // Clamp value:
     compensationSteps = Math.max(Math.min(compensationSteps, maxExposure), minExposure);
     if (parameters.getExposureCompensation() == compensationSteps) {
       Log.i(
           TAG,
           "Exposure compensation already set to "
               + compensationSteps
               + " / "
               + actualCompensation);
     } else {
       Log.i(
           TAG,
           "Setting exposure compensation to " + compensationSteps + " / " + actualCompensation);
       parameters.setExposureCompensation(compensationSteps);
     }
   } else {
     Log.i(TAG, "Camera does not support exposure compensation");
   }
 }
Ejemplo n.º 11
0
  private void copyWaveFile(String inFilename, String outFilename) {
    FileInputStream in = null;
    FileOutputStream out = null;
    long totalAudioLen = 0;
    long totalDataLen = totalAudioLen + 36;
    long longSampleRate = RECORDER_SAMPLERATE;
    int channels = 2;
    long byteRate = RECORDER_BPP * RECORDER_SAMPLERATE * channels / 8;

    byte[] data = new byte[bufferSize];

    try {
      in = new FileInputStream(inFilename);
      out = new FileOutputStream(outFilename);
      totalAudioLen = in.getChannel().size();
      totalDataLen = totalAudioLen + 36;

      // AppLog.logString("File size: " + totalDataLen);

      WriteWaveFileHeader(out, totalAudioLen, totalDataLen, longSampleRate, channels, byteRate);

      while (in.read(data) != -1) {
        out.write(data);
      }

      in.close();
      out.close();
    } catch (FileNotFoundException e) {
      Log.d("SAN", e.getMessage());
    } catch (IOException e) {
      Log.d("SAN", e.getMessage());
    }
  }
  public boolean openOrCreateDatabase(Context context, File dbFile) {

    try {

      if (dbFile.exists()) {
        Log.i("SQLiteHelper", "Opening database at " + dbFile);
        mDb =
            SQLiteDatabase.openDatabase(
                dbFile.getAbsolutePath(), null, SQLiteDatabase.OPEN_READWRITE);
        return true;

        // Test if DB works properly
        // get(MapTile.TABLE_TILE_NAME, "tilekey");
        // ---

        // if (DATABASE_VERSION > db.getVersion())
        // upgrade();
      } else {
        Log.i("SQLiteHelper", "Creating database at " + dbFile);
        mDb = SQLiteDatabase.openOrCreateDatabase(dbFile, null);
        Log.i("SQLiteHelper", "Opened database at " + dbFile);
        upgradeFromFile(mDb, R.raw.sql_osm_maptile);
        return true;
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    return false;
  }
Ejemplo n.º 13
0
 @Override
 public void onCreate() {
   Log.v("MyAlarmServiceログ", "Create");
   Thread thr = new Thread(null, mTask, "MyAlarmServiceThread");
   thr.start();
   Log.v("MyAlarmServiceログ", "スレッド開始");
 }
Ejemplo n.º 14
0
    @Override
    protected String doInBackground(String... urls) {
      Log.d("DEBUG", "Inside dwp");
      String response = "";
      for (String url : urls) {
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
          HttpResponse execute = client.execute(httpGet);
          InputStream content = execute.getEntity().getContent();

          BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
          String s = "";
          while ((s = buffer.readLine()) != null) {
            response += s;
            Log.d("DEBUG", s);
          }

        } catch (Exception e) {
          e.printStackTrace();
          Log.d("DEBUG", "Exception");
        }
      }
      Log.d("DEBUG", "Done dwp");
      return response;
    }
Ejemplo n.º 15
0
 public synchronized int fetchStatusUpdates() {
   Log.d(TAG, "Fetching status updates");
   Twitter twitter = this.getTwitter();
   if (twitter == null) {
     Log.d(TAG, "Twitter connection info not initialized");
     return 0;
   }
   try {
     List<Status> statusUpdates = twitter.getFriendsTimeline();
     long latestStatusCreatedAtTime = this.getStatusData().getLatestStatusCreatedAtTime();
     int count = 0;
     ContentValues contentValues = new ContentValues();
     for (Status status : statusUpdates) {
       contentValues.put(StatusData.C_ID, status.getId());
       long createdAt = status.getCreatedAt().getTime();
       contentValues.put(StatusData.C_CREATED_AT, createdAt);
       contentValues.put(StatusData.C_TEXT, status.getText());
       contentValues.put(StatusData.C_USER, status.getUser().getName());
       Log.d(TAG, "Got update with id " + status.getId() + ". Saving");
       this.getStatusData().insertOrIgnore(contentValues);
       if (latestStatusCreatedAtTime < createdAt) {
         count++;
       }
     }
     Log.d(TAG, count > 0 ? "Got" + count + " status updates" : "No new staus updates");
     return count;
   } catch (RuntimeException e) {
     Log.e(TAG, "Failed to fetch status updates", e);
     return 0;
   }
 }
Ejemplo n.º 16
0
    @Override
    public Void doInBackground(String... params) {
      HttpsURLConnection connection = null;

      try {
        URL url = new URL(SEARCH_URL + params[0]);
        Log.d("****URL:", url.toString());
        connection = (HttpsURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Host", "api.twitter.com");
        connection.setRequestProperty("User-Agent", "JustDoIt");
        connection.setRequestProperty("Authorization", "Bearer " + BEARER_TOKEN);
        connection.setUseCaches(false);

        JSONObject obj = new JSONObject(ReadResponse.readResponse(connection));

        buildTweets(obj);

        Log.d("***GetTweets:", obj.toString());

      } catch (MalformedURLException e) {
        Log.e("***GetTweets", "Invalid endpoint URL specified.", e);

      } catch (IOException e) {
        Log.e("***GetTweets", "IOException: ", e);
      } catch (JSONException e) {
        e.printStackTrace();
      } finally {
        if (connection != null) {
          connection.disconnect();
        }
        lock.release();
      }
      return null;
    }
Ejemplo n.º 17
0
 @Override
 public Fragment getItem(int position) {
   switch (position) {
     case 0:
       if (getSource() == SOURCE_YELP) {
         Log.d("InvitePagerAdapter", "Source is YELP");
         return currentPlace == null
             ? new PickYelpPlaceInviteFragment()
             : PickYelpPlaceInviteFragment.newInstance(currentPlace);
       } else if (getSource() == SOURCE_GOOGLE) {
         Log.d("InvitePagerAdapter", "Source is GOOGLE");
         return currentPlace == null
             ? new PickGooglePlaceInviteFragment()
             : PickGooglePlaceInviteFragment.newInstance(currentPlace);
       }
     case 1:
       return new FriendsInviteFragment();
     case 2:
       return new DetailsInviteFragment();
     case 3:
       return isUpdateMode ? new UpdateInviteFragment() : new SendInviteFragment();
     default:
       return null;
   }
 }
    private void decodeAudioSample() {
      int output = mAudioCodec.dequeueOutputBuffer(mAudioInfo, mTimeOutUs);
      if (output >= 0) {
        // http://bigflake.com/mediacodec/#q11
        ByteBuffer outputData = mAudioCodecOutputBuffers[output];
        if (mAudioInfo.size != 0) {
          outputData.position(mAudioInfo.offset);
          outputData.limit(mAudioInfo.offset + mAudioInfo.size);
          // Log.d(TAG, "raw audio data bytes: " + mVideoInfo.size);
        }
        mAudioPlayback.write(outputData, mAudioInfo.presentationTimeUs);
        mAudioCodec.releaseOutputBuffer(output, false);

        if ((mAudioInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
          mAudioOutputEos = true;
          Log.d(TAG, "EOS audio output");
        }
      } else if (output == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
        Log.d(TAG, "audio output buffers have changed.");
        mAudioCodecOutputBuffers = mAudioCodec.getOutputBuffers();
      } else if (output == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
        MediaFormat format = mAudioCodec.getOutputFormat();
        Log.d(TAG, "audio output format has changed to " + format);
        mAudioPlayback.init(format);
      }
    }
 public static void setBestPreviewFPS(Camera.Parameters parameters, int minFPS, int maxFPS) {
   List<int[]> supportedPreviewFpsRanges = parameters.getSupportedPreviewFpsRange();
   Log.i(TAG, "Supported FPS ranges: " + toString(supportedPreviewFpsRanges));
   if (supportedPreviewFpsRanges != null && !supportedPreviewFpsRanges.isEmpty()) {
     int[] suitableFPSRange = null;
     for (int[] fpsRange : supportedPreviewFpsRanges) {
       int thisMin = fpsRange[Camera.Parameters.PREVIEW_FPS_MIN_INDEX];
       int thisMax = fpsRange[Camera.Parameters.PREVIEW_FPS_MAX_INDEX];
       if (thisMin >= minFPS * 1000 && thisMax <= maxFPS * 1000) {
         suitableFPSRange = fpsRange;
         break;
       }
     }
     if (suitableFPSRange == null) {
       Log.i(TAG, "No suitable FPS range?");
     } else {
       int[] currentFpsRange = new int[2];
       parameters.getPreviewFpsRange(currentFpsRange);
       if (Arrays.equals(currentFpsRange, suitableFPSRange)) {
         Log.i(TAG, "FPS range already set to " + Arrays.toString(suitableFPSRange));
       } else {
         Log.i(TAG, "Setting FPS range to " + Arrays.toString(suitableFPSRange));
         parameters.setPreviewFpsRange(
             suitableFPSRange[Camera.Parameters.PREVIEW_FPS_MIN_INDEX],
             suitableFPSRange[Camera.Parameters.PREVIEW_FPS_MAX_INDEX]);
       }
     }
   }
 }
Ejemplo n.º 20
0
  private void writeAudioDataToFile() {
    byte data[] = new byte[bufferSize];
    String filename = getTempFilename();
    FileOutputStream os = null;

    try {
      os = new FileOutputStream(filename);
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      Log.d("SAN", e.getMessage());
    }

    int read = 0;

    if (null != os) {
      while (isRecording) {
        read = recorder.read(data, 0, bufferSize);

        if (AudioRecord.ERROR_INVALID_OPERATION != read) {
          try {
            os.write(data);
          } catch (IOException e) {
            Log.d("SAN", e.getMessage());
          }
        }
      }

      try {
        os.close();
      } catch (IOException e) {
        Log.d("SAN", e.getMessage());
      }
    }
  }
Ejemplo n.º 21
0
 private List<Article> loadNewsFromFile(Context context) {
   startedLoadingNews = true;
   List<Article> articles = new ArrayList<>();
   if (newsFile == null) newsFile = new File(context.getFilesDir(), NEWS_FILE_NAME);
   if (newsFile.exists()) {
     try {
       BufferedReader reader = new BufferedReader(new FileReader(newsFile));
       String currentLine = reader.readLine();
       if (currentLine != null) {
         String[] split = currentLine.split("-");
         if (split.length > 1) {
           for (int i = 0;
               i < Integer.parseInt(split[1]);
               i++) { // TODO figure out why all lines, after i = 18, are null.
             currentLine = reader.readLine();
             Article a = readArticle(reader);
             articles.add(a);
             Log.d("q32", "" + i + "line: " + currentLine);
           }
         } else {
           updateNews(context);
         } // if we didn't find the number of articles, the file must be corrupt. Update the file.
       } else updateNews(context);
     } catch (IOException e) {
       Log.d("Unit5Calendar", e.getMessage(), e);
     }
     Collections.sort(newsArticles, Utils.articlePubDateSorter);
     newsReady = true;
   }
   return articles;
 }
  @Override
  public void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
      case FILE_SELECT_CODE:
        if (resultCode == Activity.RESULT_OK) {
          // Get the Uri of the selected file
          Uri uri = data.getData();

          Log.d(LOG_TAG, "File Uri: " + uri.toString());
          try {
            filePath = FileUtils.getPath(getActivity(), uri);
            fileChoosen = new File(filePath);

            if (fileChoosen != null) {
              tv_choose_file.setText(fileChoosen.getName());
            } else {
              break;
            }
            bt_upload.setEnabled(true);

          } catch (URISyntaxException e) {
            Log.d(LOG_TAG, e.getLocalizedMessage());
          }
        }
        break;
    }
    super.onActivityResult(requestCode, resultCode, data);
  }
Ejemplo n.º 23
0
  @Override
  public void setBinaryData(Object answer) {
    // you are replacing an answer. delete the previous image using the
    // content provider.
    if (mBinaryName != null) {
      deleteMedia();
    }

    File newImage = (File) answer;
    if (newImage.exists()) {
      // Add the new image to the Media content provider so that the
      // viewing is fast in Android 2.0+
      ContentValues values = new ContentValues(6);
      values.put(Images.Media.TITLE, newImage.getName());
      values.put(Images.Media.DISPLAY_NAME, newImage.getName());
      values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
      values.put(Images.Media.MIME_TYPE, "image/jpeg");
      values.put(Images.Media.DATA, newImage.getAbsolutePath());

      Uri imageURI =
          getContext().getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);
      Log.i(t, "Inserting image returned uri = " + imageURI.toString());

      mBinaryName = newImage.getName();
      Log.i(t, "Setting current answer to " + newImage.getName());
    } else {
      Log.e(t, "NO IMAGE EXISTS at: " + newImage.getAbsolutePath());
    }

    Collect.getInstance().getFormController().setIndexWaitingForData(null);
  }
  /**
   * fills the list with stops from the local database
   *
   * @param db the database adapter to use
   */
  private void fillList(BusDbAdapter db) {
    Cursor c;
    if (listType == FAVORITES) {
      c = db.getFavoriteDest(NUM_ENTRIES_TO_FETCH);
    } else { // listType == MAJOR
      c = db.getMajorDest(NUM_ENTRIES_TO_FETCH);
    }
    int stopIDIndex = c.getColumnIndex("stop_id");
    int stopDescIndex = c.getColumnIndex("stop_desc");
    int routeIDIndex = c.getColumnIndex("route_id");
    int routeDescIndex = c.getColumnIndex("route_desc");
    if (c != null) {
      for (int i = 0; i < c.getCount(); i++) {
        HashMap<String, String> item = new HashMap<String, String>();

        String stopID = c.getString(stopIDIndex);
        String stopName = c.getString(stopDescIndex);
        String route = c.getString(routeIDIndex);
        String routeDesc = c.getString(routeDescIndex);
        Log.v(TAG, "PUT");
        Log.v(TAG, "stopID " + stopID + " stopName " + stopName);
        Log.v(TAG, "routeID " + route + " routeDesc" + routeDesc);
        item.put("stopID", stopID);
        item.put("stopName", stopName);
        item.put("routeID", route);
        item.put("routeDesc", routeDesc);
        c.moveToNext();
        locationList.add(item);
      }
      listAdapter.notifyDataSetChanged();
    }
  }
  /** {@inheritDoc} */
  @Override
  public void execute()
      throws InsufficientPermissionsException, NoSuchFileOrDirectory, ExecutionException {
    if (isTrace()) {
      Log.v(TAG, String.format("Creating from %s to %s", this.mSrc, this.mDst)); // $NON-NLS-1$
    }

    File s = new File(this.mSrc);
    File d = new File(this.mDst);
    if (!s.exists()) {
      if (isTrace()) {
        Log.v(TAG, "Result: FAIL. NoSuchFileOrDirectory"); // $NON-NLS-1$
      }
      throw new NoSuchFileOrDirectory(this.mSrc);
    }

    // Copy recursively
    if (!s.renameTo(d)) {
      if (isTrace()) {
        Log.v(TAG, "Result: FAIL. InsufficientPermissionsException"); // $NON-NLS-1$
      }
      throw new InsufficientPermissionsException();
    }

    if (isTrace()) {
      Log.v(TAG, "Result: OK"); // $NON-NLS-1$
    }
  }
Ejemplo n.º 26
0
  /**
   * Searching places
   *
   * @param latitude - latitude of place
   * @params longitude - longitude of place
   * @param radius - radius of searchable area
   * @param types - type of place to search
   * @return list of places
   */
  public PlacesList search(double latitude, double longitude, double radius, String types)
      throws Exception {

    this._latitude = latitude;
    this._longitude = longitude;
    this._radius = radius;

    try {

      HttpRequestFactory httpRequestFactory = createRequestFactory(HTTP_TRANSPORT);
      HttpRequest request = httpRequestFactory.buildGetRequest(new GenericUrl(PLACES_SEARCH_URL));
      request.getUrl().put("key", API_KEY);
      request.getUrl().put("location", _latitude + "," + _longitude);
      request.getUrl().put("radius", _radius); // in meters
      request.getUrl().put("sensor", "false");
      if (types != null) request.getUrl().put("types", types);

      PlacesList list = request.execute().parseAs(PlacesList.class);
      // Check log cat for places response status
      Log.d("Places Status", "" + list.status);
      return list;

    } catch (HttpResponseException e) {
      Log.e("Error:", e.getMessage());
      return null;
    }
  }
  private void saveBmpToSd(Bitmap bm, String url) {
    if (bm == null) {
      Log.w(TAG, " trying to savenull bitmap");
      return;
    }
    // 判断sdcard上的空间
    //        if (FREE_SD_SPACE_NEEDED_TO_CACHE >freeSpaceOnSd()) {
    //            Log.w(TAG, "Low free space onsd, do not cache");
    //            return;
    //        }

    File file = new File(Environment.getExternalStorageDirectory() + "/cache/" + MD5(url) + ".jpg");
    try {
      file.createNewFile();
      OutputStream outStream = new FileOutputStream(file);
      bm.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
      outStream.flush();
      outStream.close();
      Log.i(TAG, "Image saved tosd");
    } catch (FileNotFoundException e) {
      Log.w(TAG, "FileNotFoundException");
    } catch (IOException e) {
      Log.w(TAG, "IOException");
    }
  }
  /** Opens a rear-facing camera with {@link Camera#open(int)}, if one exists, or opens camera 0. */
  public static Camera open() {

    int numCameras = Camera.getNumberOfCameras();
    if (numCameras == 0) {
      Log.w(TAG, "No cameras!");
      return null;
    }

    int index = 0;
    while (index < numCameras) {
      Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
      Camera.getCameraInfo(index, cameraInfo);
      // CAMERA_FACING_BACK:手机背面的摄像头
      if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
        break;
      }
      index++;
    }

    Camera camera;
    if (index < numCameras) {
      Log.i(TAG, "Opening camera #" + index);
      camera = Camera.open(index);
    } else {
      Log.i(TAG, "No camera facing back; returning camera #0");
      camera = Camera.open(0);
    }

    return camera;
  }
Ejemplo n.º 29
0
  public static InputConnection getInputConnection() {
    InputService service = InputService.getInputService();
    if (service != null) {
      InputConnection connection = service.getCurrentInputConnection();

      if (connection != null) {
        return connection;
      } else {
        Log.w(LOG_TAG, "input service not connected");
      }
    } else if (!isInputServiceEnabled()) {
      Log.w(LOG_TAG, "input service not enabled");
    } else if (!isInputServiceSelected()) {
      Log.w(LOG_TAG, "input service not selected");
    } else {
      Log.w(LOG_TAG, "input service not started");
    }

    if (!isInputServiceSelected()) {
      Log.w(LOG_TAG, "showing input method picker");
      ApplicationUtilities.getInputMethodManager().showInputMethodPicker();
    }

    return null;
  }
  @Override
  public View onCreateView(
      LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_stories_view, container, false);
    getActivity().setTitle(getResources().getString(R.string.title_activity_news_home_screen));

    swipeLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_refresh_layout);
    swipeLayout.setOnRefreshListener(this);

    TextView noTopicsText = (TextView) rootView.findViewById(R.id.no_topics_textview);
    user = ValuesAndUtil.getInstance().loadUserData(getActivity().getApplicationContext());

    boolean hasTopics = false;
    try {
      hasTopics = user.has("topics") && user.getJSONArray("topics").length() > 0;
    } catch (JSONException e) {
      e.printStackTrace();
    }
    Log.d("SVF", "Has topics = " + hasTopics);
    if (!hasTopics) {
      noTopicsText.setText(getString(R.string.no_topics_available));
      swipeLayout.setVisibility(View.INVISIBLE);
    } else {
      Log.d("SVF", "Topics were not null");
      swipeLayout.setVisibility(View.VISIBLE);
      try {
        topics = user.getJSONArray("topics");
        setUpList(rootView, topics);
      } catch (JSONException e) {
        e.printStackTrace();
      }
    }

    return rootView;
  }