Exemple #1
0
  public static Bitmap getSmallAvatarWithRoundedCorner(String url, int reqWidth, int reqHeight) {

    if (!FileManager.isExternalStorageMounted()) {
      return null;
    }

    String absoluteFilePath = FileManager.getFilePathFromUrl(url, FileLocationMethod.avatar_small);
    absoluteFilePath = absoluteFilePath + ".jpg";

    Bitmap bitmap = BitmapFactory.decodeFile(absoluteFilePath);

    if (bitmap == null && !SettingUtility.isEnablePic()) {
      return null;
    }

    if (bitmap == null) {
      boolean result = getBitmapFromNetWork(url, absoluteFilePath, null);
      if (result) bitmap = BitmapFactory.decodeFile(absoluteFilePath);
    }

    if (bitmap != null) {
      if (bitmap.getHeight() < reqHeight || bitmap.getWidth() < reqWidth) {
        Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, reqWidth, reqHeight, true);
        Bitmap roundedBitmap = ImageEdit.getRoundedCornerBitmap(scaledBitmap);
        bitmap.recycle();
        scaledBitmap.recycle();
        return roundedBitmap;
      }
    }

    return null;
  }
  public MsgDetailReadWorker(WeiboDetailImageView view, MessageBean msg) {
    this.view = view;
    this.pb = this.view.getProgressBar();
    this.msg = msg;
    this.retry = view.getRetryButton();
    retry.setVisibility(View.INVISIBLE);

    oriPath =
        FileManager.getFilePathFromUrl(msg.getOriginal_pic(), FileLocationMethod.picture_large);

    if (ImageUtility.isThisBitmapCanRead(oriPath)
        && TaskCache.isThisUrlTaskFinished(msg.getOriginal_pic())) {

      onPostExecute(oriPath);
      cancel(true);
      return;
    }

    middlePath =
        FileManager.getFilePathFromUrl(msg.getBmiddle_pic(), FileLocationMethod.picture_bmiddle);

    if (ImageUtility.isThisBitmapCanRead(middlePath)
        && TaskCache.isThisUrlTaskFinished(msg.getBmiddle_pic())) {
      onPostExecute(middlePath);
      cancel(true);
      return;
    }

    pb.setVisibility(View.VISIBLE);
    pb.setIndeterminate(true);
  }
    @Override
    public Boolean call() throws Exception {
      synchronized (TimeLineBitmapDownloader.pauseDownloadWorkLock) {
        while (TimeLineBitmapDownloader.pauseDownloadWork
            && !Thread.currentThread().isInterrupted()) {
          try {
            TimeLineBitmapDownloader.pauseDownloadWorkLock.wait();
          } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
          }
        }
      }
      String filePath = FileManager.generateDownloadFileName(url);

      String actualDownloadUrl = url;

      switch (method) {
        case picture_thumbnail:
          actualDownloadUrl = url.replace("thumbnail", "webp180");
          break;
        case picture_bmiddle:
          actualDownloadUrl = url.replace("bmiddle", "webp720");
          break;
        case picture_large:
          actualDownloadUrl = url.replace("large", "woriginal");
          break;
      }

      boolean result =
          ImageUtility.getBitmapFromNetWork(
              actualDownloadUrl,
              filePath,
              new FileDownloaderHttpHelper.DownloadListener() {
                @Override
                public void pushProgress(int progress, int max) {
                  JobCallable.this.progress = progress;
                  JobCallable.this.max = max;
                  for (FileDownloaderHttpHelper.DownloadListener downloadListener :
                      downloadListenerList) {
                    if (downloadListener != null) {
                      downloadListener.pushProgress(progress, max);
                    }
                  }
                }
              });

      if (result) {
        DownloadPicturesDBTask.add(
            this.url, FileManager.generateDownloadFileName(this.url), this.method);
      }

      TaskCache.removeDownloadTask(url, futureTask);
      return result;
    }
Exemple #4
0
  public static Bitmap getMiddlePictureInBrowserMSGActivity(
      String url, FileDownloaderHttpHelper.DownloadListener downloadListener) {

    String absoluteFilePath =
        FileManager.getFilePathFromUrl(url, FileLocationMethod.picture_bmiddle);

    File file = new File(absoluteFilePath);

    if (!file.exists() && !SettingUtility.isEnablePic()) {
      return null;
    }

    if (!file.exists()) {
      getBitmapFromNetWork(url, absoluteFilePath, downloadListener);
    }
    file = new File(absoluteFilePath);
    if (file.exists()) {
      DisplayMetrics displayMetrics = GlobalContext.getInstance().getDisplayMetrics();

      Bitmap bitmap =
          decodeBitmapFromSDCard(
              absoluteFilePath, displayMetrics.widthPixels, displayMetrics.heightPixels);
      return bitmap;
    }
    return null;
  }
Exemple #5
0
  public static Bitmap getMiddlePictureInBrowserMSGActivity(
      String url, FileDownloaderHttpHelper.DownloadListener downloadListener) {

    try {

      String filePath = FileManager.getFilePathFromUrl(url, FileLocationMethod.picture_bmiddle);

      File file = new File(filePath);

      if (!file.exists() && !SettingUtility.isEnablePic()) {
        return null;
      }

      if (!file.exists()) {
        getBitmapFromNetWork(url, filePath, downloadListener);
      }
      file = new File(filePath);
      if (file.exists()) {
        DisplayMetrics displayMetrics = GlobalContext.getInstance().getDisplayMetrics();
        return decodeBitmapFromSDCard(filePath, displayMetrics.widthPixels, 900);
      }
      return null;
    } catch (OutOfMemoryError ignored) {
      return null;
    }
  }
Exemple #6
0
  public static Bitmap getTimeLineBigAvatarWithRoundedCorner(
      String url, int reqWidth, int reqHeight) {

    if (!FileManager.isExternalStorageMounted()) {
      return null;
    }

    String absoluteFilePath = FileManager.getFilePathFromUrl(url, FileLocationMethod.avatar_large);
    absoluteFilePath = absoluteFilePath + ".jpg";

    boolean fileExist = new File(absoluteFilePath).exists();

    if (!fileExist && !SettingUtility.isEnablePic()) {
      return null;
    }

    if (!fileExist) {
      boolean result = getBitmapFromNetWork(url, absoluteFilePath, null);
      if (!result) return null;
    }

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(absoluteFilePath, options);

    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
    options.inJustDecodeBounds = false;
    options.inPurgeable = true;
    options.inInputShareable = true;

    Bitmap bitmap = BitmapFactory.decodeFile(absoluteFilePath, options);

    if (bitmap != null) {
      Bitmap roundBitmap = ImageEdit.getRoundedCornerBitmap(bitmap);
      bitmap.recycle();
      return roundBitmap;
    }

    return bitmap;
  }
Exemple #7
0
  public static Bitmap getBigAvatarWithRoundedCorner(String url) {

    if (!FileManager.isExternalStorageMounted()) {
      return null;
    }

    String absoluteFilePath = FileManager.getFilePathFromUrl(url, FileLocationMethod.avatar_large);
    absoluteFilePath = absoluteFilePath + ".jpg";

    Bitmap bitmap = BitmapFactory.decodeFile(absoluteFilePath);

    if (bitmap == null && SettingUtility.isEnablePic()) {
      getBitmapFromNetWork(url, absoluteFilePath, null);
      bitmap = BitmapFactory.decodeFile(absoluteFilePath);
    }

    if (bitmap != null) {
      bitmap = ImageEdit.getRoundedCornerBitmap(bitmap);
    }

    return bitmap;
  }
Exemple #8
0
  public static Bitmap getThumbnailPictureWithRoundedCorner(String url) {

    String absoluteFilePath =
        FileManager.getFilePathFromUrl(url, FileLocationMethod.picture_thumbnail);

    Bitmap bitmap = BitmapFactory.decodeFile(absoluteFilePath);

    if (bitmap != null) {
      return ImageEdit.getRoundedCornerBitmap(bitmap);
    } else if (SettingUtility.isEnablePic()) {
      getBitmapFromNetWork(url, absoluteFilePath, null);
      bitmap = BitmapFactory.decodeFile(absoluteFilePath);
      if (bitmap != null) return ImageEdit.getRoundedCornerBitmap(bitmap);
    }
    return null;
  }
Exemple #9
0
  @Override
  public void run() {

    Thread.currentThread().setPriority(Thread.MIN_PRIORITY);

    AppLogger.d("clear cache task start");

    if (Utility.isWifi(GlobalContext.getInstance())) {

      List<String> pathList = FileManager.getCachePath();

      for (String path : pathList) {
        if (!TextUtils.isEmpty(path)) handleDir(new File(path));
      }

      AppLogger.d("clear cache task stop");
    } else {
      AppLogger.d("this device dont have wifi network, clear cache task stop");
    }
  }
Exemple #10
0
  public static String getMiddlePictureWithoutRoundedCorner(
      String url, FileDownloaderHttpHelper.DownloadListener downloadListener) {

    String absoluteFilePath =
        FileManager.getFilePathFromUrl(url, FileLocationMethod.picture_bmiddle);

    File file = new File(absoluteFilePath);

    if (file.exists()) {
      return absoluteFilePath;

    } else {
      getBitmapFromNetWork(url, absoluteFilePath, downloadListener);

      file = new File(absoluteFilePath);
      if (file.exists()) {
        return absoluteFilePath;
      } else {
        return "";
      }
    }
  }
Exemple #11
0
  public static Bitmap getNotificationAvatar(String url, int reqWidth, int reqHeight) {

    String absoluteFilePath = FileManager.getFilePathFromUrl(url, FileLocationMethod.avatar_large);
    absoluteFilePath = absoluteFilePath + ".jpg";

    Bitmap bitmap = BitmapFactory.decodeFile(absoluteFilePath);

    if (bitmap == null) {
      getBitmapFromNetWork(url, absoluteFilePath, null);
      bitmap = BitmapFactory.decodeFile(absoluteFilePath);
    }

    if (bitmap != null) {
      bitmap = Bitmap.createScaledBitmap(bitmap, reqWidth, reqHeight, true);
    }

    if (bitmap != null) {
      bitmap = ImageEdit.getRoundedCornerBitmap(bitmap);
    }

    return bitmap;
  }
    @Override
    protected Void doInBackground(Void... params) {
      Map<String, String> emotions = GlobalContext.getInstance().getEmotions();
      List<String> index = new ArrayList<String>();
      index.addAll(emotions.keySet());
      for (String str : index) {
        if (!isCancelled()) {
          String url = emotions.get(str);
          String path = FileManager.getFileAbsolutePathFromUrl(url, FileLocationMethod.emotion);
          String name = new File(path).getName();
          AssetManager assetManager = GlobalContext.getInstance().getAssets();
          InputStream inputStream;
          try {
            inputStream = assetManager.open(name);
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            emotionsPic.put(str, bitmap);
          } catch (IOException ignored) {

          }
        }
      }
      return null;
    }
Exemple #13
0
  public static Bitmap getMiddlePictureInTimeLine(
      String url,
      int reqWidth,
      int reqHeight,
      FileDownloaderHttpHelper.DownloadListener downloadListener) {

    //        int useWidth = 400;
    int useWidth = reqWidth;

    String absoluteFilePath =
        FileManager.getFilePathFromUrl(url, FileLocationMethod.picture_bmiddle);

    File file = new File(absoluteFilePath);

    if (!file.exists() && !SettingUtility.isEnablePic()) {
      return null;
    }

    if (!file.exists()) {
      getBitmapFromNetWork(url, absoluteFilePath, downloadListener);
    }

    if (absoluteFilePath.endsWith(".gif")) {
      return getMiddlePictureInTimeLineGif(absoluteFilePath, reqWidth, reqHeight);
    }

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(absoluteFilePath, options);

    int height = options.outHeight;
    int width = options.outWidth;

    int cutHeight = 0;
    int cutWidth = 0;

    if (height >= reqHeight && width >= useWidth) {
      cutHeight = reqHeight;
      cutWidth = useWidth;

    } else if (height < reqHeight && width >= useWidth) {

      cutHeight = height;
      cutWidth = (useWidth * cutHeight) / reqHeight;

    } else if (height >= reqHeight && width < useWidth) {

      cutWidth = width;
      cutHeight = (reqHeight * cutWidth) / useWidth;

    } else if (height < reqHeight && width < useWidth) {

      float betweenWidth = ((float) useWidth - (float) width) / (float) width;
      float betweenHeight = ((float) reqHeight - (float) height) / (float) height;

      if (betweenWidth > betweenHeight) {
        cutWidth = width;
        cutHeight = (reqHeight * cutWidth) / useWidth;

      } else {
        cutHeight = height;
        cutWidth = (useWidth * cutHeight) / reqHeight;
      }
    }

    if (cutWidth > 0 && cutHeight > 0) {

      int startX = 0;

      if (cutWidth < width) {
        startX = (width - cutWidth) / 2;
      }

      try {
        BitmapRegionDecoder decoder = BitmapRegionDecoder.newInstance(absoluteFilePath, false);
        if (decoder != null) {
          Bitmap region =
              decoder.decodeRegion(new Rect(startX, 0, startX + cutWidth, cutHeight), null);
          Bitmap scale = null;
          if (region.getHeight() < reqHeight && region.getWidth() < reqWidth) {
            scale = Bitmap.createScaledBitmap(region, reqWidth, reqHeight, true);
          }
          if (scale == null) {
            Bitmap anotherValue = ImageEdit.getRoundedCornerBitmap(region);
            region.recycle();

            return anotherValue;
            //                        return region;
          } else {
            Bitmap anotherValue = ImageEdit.getRoundedCornerBitmap(scale);
            region.recycle();
            scale.recycle();
            return anotherValue;
            //                        return scale;
          }
        }
      } catch (IOException ignored) {
        // do nothing
      }
    }

    return null;
  }
  private void buildNotification(String uid) {

    final ValueWrapper valueWrapper = valueBagHashMap.get(uid);

    if (valueWrapper == null) {
      return;
    }

    final AccountBean accountBean = valueWrapper.accountBean;

    final MessageListBean mentionsWeibo = valueWrapper.mentionsWeibo;

    final CommentListBean mentionsComment = valueWrapper.mentionsComment;

    final CommentListBean commentsToMe = valueWrapper.commentsToMe;

    final UnreadBean unreadBean = valueWrapper.unreadBean;

    int currentIndex = valueWrapper.currentIndex;

    Intent clickToOpenAppPendingIntentInner = valueWrapper.clickToOpenAppPendingIntentInner;

    String ticker = valueWrapper.ticker;

    ArrayList<Parcelable> notificationItems = valueWrapper.notificationItems;

    //        int count = Math.min(unreadBean.getMention_status(), data.getSize());

    int count = notificationItems.size();

    if (count == 0) {
      return;
    }

    Parcelable itemBean = notificationItems.get(currentIndex);

    Notification.Builder builder =
        new Notification.Builder(getBaseContext())
            .setTicker(ticker)
            .setContentText(ticker)
            .setSubText(accountBean.getUsernick())
            .setSmallIcon(R.drawable.ic_notification)
            .setAutoCancel(true)
            .setContentIntent(
                getPendingIntent(clickToOpenAppPendingIntentInner, itemBean, accountBean))
            .setOnlyAlertOnce(true);

    builder.setContentTitle(getString(R.string.app_name));

    if (count > 1) {
      builder.setNumber(count);
    }

    Utility.unregisterReceiverIgnoredReceiverNotRegisteredException(
        GlobalContext.getInstance(), valueWrapper.clearNotificationEventReceiver);

    valueWrapper.clearNotificationEventReceiver =
        new RecordOperationAppBroadcastReceiver() {

          // mark these messages as read, write to database
          @Override
          public void onReceive(Context context, Intent intent) {
            new Thread(
                    new Runnable() {
                      @Override
                      public void run() {
                        try {
                          ArrayList<String> ids = new ArrayList<String>();

                          if (mentionsWeibo != null) {
                            for (MessageBean msg : mentionsWeibo.getItemList()) {
                              ids.add(msg.getId());
                            }

                            NotificationDBTask.addUnreadNotification(
                                accountBean.getUid(),
                                ids,
                                NotificationDBTask.UnreadDBType.mentionsWeibo);
                          }

                          ids.clear();

                          if (commentsToMe != null) {

                            for (CommentBean msg : commentsToMe.getItemList()) {
                              ids.add(msg.getId());
                            }

                            NotificationDBTask.addUnreadNotification(
                                accountBean.getUid(),
                                ids,
                                NotificationDBTask.UnreadDBType.commentsToMe);
                          }
                          ids.clear();
                          if (mentionsComment != null) {
                            for (CommentBean msg : mentionsComment.getItemList()) {
                              ids.add(msg.getId());
                            }

                            NotificationDBTask.addUnreadNotification(
                                accountBean.getUid(),
                                ids,
                                NotificationDBTask.UnreadDBType.mentionsComment);
                          }
                        } finally {
                          Utility.unregisterReceiverIgnoredReceiverNotRegisteredException(
                              GlobalContext.getInstance(),
                              valueWrapper.clearNotificationEventReceiver);
                          if (Utility.isDebugMode()) {

                            new Handler(Looper.getMainLooper())
                                .post(
                                    new Runnable() {
                                      @Override
                                      public void run() {
                                        Toast.makeText(
                                                getApplicationContext(),
                                                "weiciyuan:remove notification items"
                                                    + System.currentTimeMillis(),
                                                Toast.LENGTH_SHORT)
                                            .show();
                                      }
                                    });
                          }
                        }
                      }
                    })
                .start();
          }
        };

    IntentFilter intentFilter = new IntentFilter(RESET_UNREAD_MENTIONS_WEIBO_ACTION);

    Utility.registerReceiverIgnoredReceiverHasRegisteredHereException(
        GlobalContext.getInstance(), valueWrapper.clearNotificationEventReceiver, intentFilter);

    Intent broadcastIntent = new Intent(RESET_UNREAD_MENTIONS_WEIBO_ACTION);

    PendingIntent deletedPendingIntent =
        PendingIntent.getBroadcast(
            GlobalContext.getInstance(),
            accountBean.getUid().hashCode(),
            broadcastIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setDeleteIntent(deletedPendingIntent);

    if (itemBean instanceof MessageBean) {
      MessageBean msg = (MessageBean) itemBean;
      Intent intent =
          WriteCommentActivity.newIntentFromNotification(getApplicationContext(), accountBean, msg);
      PendingIntent pendingIntent =
          PendingIntent.getActivity(
              getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
      builder.addAction(
          R.drawable.comment_light,
          getApplicationContext().getString(R.string.comments),
          pendingIntent);
    } else if (itemBean instanceof CommentBean) {
      CommentBean commentBean = (CommentBean) itemBean;
      Intent intent =
          WriteReplyToCommentActivity.newIntentFromNotification(
              getApplicationContext(), accountBean, commentBean);
      PendingIntent pendingIntent =
          PendingIntent.getActivity(
              getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
      builder.addAction(
          R.drawable.reply_to_comment_light,
          getApplicationContext().getString(R.string.reply_to_comment),
          pendingIntent);
    }

    String avatar = ((ItemBean) itemBean).getUser().getAvatar_large();
    String avatarPath = FileManager.getFilePathFromUrl(avatar, FileLocationMethod.avatar_large);
    if (ImageUtility.isThisBitmapCanRead(avatarPath) && TaskCache.isThisUrlTaskFinished(avatar)) {
      Bitmap bitmap = BitmapFactory.decodeFile(avatarPath, new BitmapFactory.Options());
      if (bitmap != null) {
        builder.setLargeIcon(bitmap);
      }
    }

    if (count > 1) {

      String actionName;
      int nextIndex;
      int actionDrawable;
      if (currentIndex < count - 1) {
        nextIndex = currentIndex + 1;
        actionName = getString(R.string.next_message);
        actionDrawable = R.drawable.notification_action_next;
      } else {
        nextIndex = 0;
        actionName = getString(R.string.first_message);
        actionDrawable = R.drawable.notification_action_previous;
      }
      Intent nextIntent =
          BigTextNotificationService.newIntent(
              accountBean,
              mentionsWeibo,
              commentsToMe,
              mentionsComment,
              unreadBean,
              clickToOpenAppPendingIntentInner,
              ticker,
              nextIndex);
      PendingIntent retrySendIntent =
          PendingIntent.getService(
              BigTextNotificationService.this,
              accountBean.getUid().hashCode(),
              nextIntent,
              PendingIntent.FLAG_UPDATE_CURRENT);
      builder.addAction(actionDrawable, actionName, retrySendIntent);
    }

    Notification.BigTextStyle bigTextStyle = new Notification.BigTextStyle(builder);
    bigTextStyle.setBigContentTitle(
        getItemBigContentTitle(accountBean, notificationItems, currentIndex));
    bigTextStyle.bigText(getItemBigText(notificationItems, currentIndex));
    String summaryText;
    if (count > 1) {
      summaryText = accountBean.getUsernick() + "(" + (currentIndex + 1) + "/" + count + ")";
    } else {
      summaryText = accountBean.getUsernick();
    }
    bigTextStyle.setSummaryText(summaryText);

    builder.setStyle(bigTextStyle);
    Utility.configVibrateLedRingTone(builder);

    NotificationManager notificationManager =
        (NotificationManager) getApplicationContext().getSystemService(NOTIFICATION_SERVICE);
    notificationManager.notify(getMentionsWeiboNotificationId(accountBean), builder.build());
  }
 @Override
 protected String doInBackground(Void... params) {
   return FileManager.getPictureCacheSize();
 }
 @Override
 protected Boolean doInBackground(Void... params) {
   return FileManager.deletePictureCache();
 }
Exemple #17
0
  public static Bitmap getMiddlePictureInTimeLine(
      String url,
      int reqWidth,
      int reqHeight,
      FileDownloaderHttpHelper.DownloadListener downloadListener) {
    try {

      String filePath = FileManager.getFilePathFromUrl(url, FileLocationMethod.picture_bmiddle);

      File file = new File(filePath);

      if (!file.exists() && !SettingUtility.isEnablePic()) {
        return null;
      }

      if (!file.exists()) {
        getBitmapFromNetWork(url, filePath, downloadListener);
      }

      if (isGif(filePath)) {
        return getMiddlePictureInTimeLineGif(filePath, reqWidth, reqHeight);
      }

      BitmapFactory.Options options = new BitmapFactory.Options();
      options.inJustDecodeBounds = true;
      BitmapFactory.decodeFile(filePath, options);

      int height = options.outHeight;
      int width = options.outWidth;

      int cutHeight = 0;
      int cutWidth = 0;

      if (height >= reqHeight && width >= reqWidth) {
        cutHeight = reqHeight;
        cutWidth = reqWidth;

      } else if (height < reqHeight && width >= reqWidth) {

        cutHeight = height;
        cutWidth = (reqWidth * cutHeight) / reqHeight;

      } else if (height >= reqHeight && width < reqWidth) {

        cutWidth = width;
        cutHeight = (reqHeight * cutWidth) / reqWidth;

      } else if (height < reqHeight && width < reqWidth) {

        float betweenWidth = ((float) reqWidth - (float) width) / (float) width;
        float betweenHeight = ((float) reqHeight - (float) height) / (float) height;

        if (betweenWidth > betweenHeight) {
          cutWidth = width;
          cutHeight = (reqHeight * cutWidth) / reqWidth;

        } else {
          cutHeight = height;
          cutWidth = (reqWidth * cutHeight) / reqHeight;
        }
      }

      if (cutWidth > 0 && cutHeight > 0) {

        int startX = 0;

        if (cutWidth < width) {
          startX = (width - cutWidth) / 2;
        }

        try {
          BitmapRegionDecoder decoder = BitmapRegionDecoder.newInstance(filePath, false);
          if (decoder != null) {
            Bitmap bitmap =
                decoder.decodeRegion(new Rect(startX, 0, startX + cutWidth, cutHeight), null);
            if (bitmap.getHeight() < reqHeight && bitmap.getWidth() < reqWidth) {
              Bitmap scale = Bitmap.createScaledBitmap(bitmap, reqWidth, reqHeight, true);
              if (scale != bitmap) {
                bitmap.recycle();
                bitmap = scale;
              }
            }
            if (bitmap != null) {
              Bitmap roundedCornerBitmap = ImageEdit.getRoundedCornerBitmap(bitmap);
              if (roundedCornerBitmap != bitmap) {
                bitmap.recycle();
                bitmap = roundedCornerBitmap;
              }

              return bitmap;
            }
          }
        } catch (IOException ignored) {

        }
      }

      return null;
    } catch (OutOfMemoryError ignored) {
      ignored.printStackTrace();
      return null;
    }
  }
Exemple #18
0
  public static Bitmap getRoundedCornerPic(
      String url, int reqWidth, int reqHeight, FileLocationMethod method) {
    try {

      if (!FileManager.isExternalStorageMounted()) {
        return null;
      }

      String filePath = FileManager.getFilePathFromUrl(url, method);
      if (!filePath.endsWith(".jpg") && !filePath.endsWith(".gif")) filePath = filePath + ".jpg";

      boolean fileExist = new File(filePath).exists();

      if (!fileExist && !SettingUtility.isEnablePic()) {
        return null;
      }

      if (!fileExist) {
        boolean result = getBitmapFromNetWork(url, filePath, null);
        if (!result) return null;
      }

      BitmapFactory.Options options = new BitmapFactory.Options();
      options.inJustDecodeBounds = true;
      BitmapFactory.decodeFile(filePath, options);

      options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
      options.inJustDecodeBounds = false;
      options.inPurgeable = true;
      options.inInputShareable = true;

      Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);

      if (bitmap == null) {
        // this picture is broken,so delete it
        new File(filePath).delete();
        return null;
      }

      if (bitmap.getHeight() < reqHeight || bitmap.getWidth() < reqWidth) {

        int[] size = calcResize(bitmap.getWidth(), bitmap.getHeight(), reqWidth, reqHeight);
        Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, size[0], size[1], true);

        if (scaledBitmap != bitmap) {
          bitmap.recycle();
          bitmap = scaledBitmap;
        }

        Bitmap roundedBitmap = ImageEdit.getRoundedCornerBitmap(bitmap);
        if (roundedBitmap != bitmap) {
          bitmap.recycle();
          bitmap = roundedBitmap;
        }
        return bitmap;
      }

      return bitmap;
    } catch (OutOfMemoryError ignored) {
      ignored.printStackTrace();
      return null;
    }
  }
  public boolean doGetSaveFile(
      String urlStr, String path, FileDownloaderHttpHelper.DownloadListener downloadListener) {

    File file = FileManager.createNewFileInSDCard(path);
    if (file == null) {
      return false;
    }

    FileOutputStream out = null;
    InputStream in = null;
    HttpURLConnection urlConnection = null;
    try {

      URL url = new URL(urlStr);
      AppLogger.d("download request=" + urlStr);
      Proxy proxy = getProxy();
      if (proxy != null) urlConnection = (HttpURLConnection) url.openConnection(proxy);
      else urlConnection = (HttpURLConnection) url.openConnection();

      urlConnection.setRequestMethod("GET");
      urlConnection.setDoOutput(false);
      urlConnection.setConnectTimeout(DOWNLOAD_CONNECT_TIMEOUT);
      urlConnection.setReadTimeout(DOWNLOAD_READ_TIMEOUT);
      urlConnection.setRequestProperty("Connection", "Keep-Alive");
      urlConnection.setRequestProperty("Charset", "UTF-8");
      urlConnection.setRequestProperty("Accept-Encoding", "gzip, deflate");

      urlConnection.connect();

      int status = urlConnection.getResponseCode();

      if (status != HttpURLConnection.HTTP_OK) {
        return false;
      }

      int bytetotal = (int) urlConnection.getContentLength();
      int bytesum = 0;
      int byteread = 0;
      out = new FileOutputStream(file);
      in = urlConnection.getInputStream();

      final Thread thread = Thread.currentThread();
      byte[] buffer = new byte[1444];
      while ((byteread = in.read(buffer)) != -1) {
        if (thread.isInterrupted()) {
          file.delete();
          throw new InterruptedIOException();
        }

        bytesum += byteread;
        out.write(buffer, 0, byteread);
        if (downloadListener != null && bytetotal > 0) {
          downloadListener.pushProgress(bytesum, bytetotal);
        }
      }
      return true;

    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      Utility.closeSilently(in);
      Utility.closeSilently(out);
      if (urlConnection != null) urlConnection.disconnect();
    }

    return false;
  }
Exemple #20
0
  @Override
  protected Bitmap doInBackground(String... url) {

    String path = FileManager.getFilePathFromUrl(data, method);

    int height = 0;
    int width = 0;

    switch (method) {
      case avatar_small:
      case avatar_large:
        width =
            GlobalContext.getInstance()
                    .getResources()
                    .getDimensionPixelSize(R.dimen.timeline_avatar_width)
                - Utility.dip2px(5) * 2;
        height =
            GlobalContext.getInstance()
                    .getResources()
                    .getDimensionPixelSize(R.dimen.timeline_avatar_height)
                - Utility.dip2px(5) * 2;
        break;

      case picture_thumbnail:
        width =
            GlobalContext.getInstance()
                .getResources()
                .getDimensionPixelSize(R.dimen.timeline_pic_thumbnail_width);
        height =
            GlobalContext.getInstance()
                .getResources()
                .getDimensionPixelSize(R.dimen.timeline_pic_thumbnail_height);
        break;

      case picture_large:
      case picture_bmiddle:
        if (!isMultiPictures) {
          DisplayMetrics metrics = GlobalContext.getInstance().getDisplayMetrics();

          float reSize = GlobalContext.getInstance().getResources().getDisplayMetrics().density;

          height =
              GlobalContext.getInstance()
                  .getResources()
                  .getDimensionPixelSize(R.dimen.timeline_pic_high_thumbnail_height);
          // 8 is  layout padding
          width = (int) (metrics.widthPixels - (8 + 8) * reSize);
        } else {
          height = width = Utility.dip2px(120);
        }
        break;
    }

    Bitmap bitmap;

    switch (method) {
      case avatar_small:
      case avatar_large:
        bitmap = ImageUtility.getRoundedCornerPic(path, width, height, Utility.dip2px(2));
        break;
      default:
        bitmap = ImageUtility.getRoundedCornerPic(path, width, height, 0);
        break;
    }

    return bitmap;
  }