Example #1
0
  private String readResult(HttpURLConnection urlConnection) throws WeiboException {
    InputStream is = null;
    BufferedReader buffer = null;
    GlobalContext globalContext = GlobalContext.getInstance();
    String errorStr = globalContext.getString(R.string.timeout);
    globalContext = null;
    try {
      is = urlConnection.getInputStream();

      String content_encode = urlConnection.getContentEncoding();

      if (null != content_encode && !"".equals(content_encode) && content_encode.equals("gzip")) {
        is = new GZIPInputStream(is);
      }

      buffer = new BufferedReader(new InputStreamReader(is));
      StringBuilder strBuilder = new StringBuilder();
      String line;
      while ((line = buffer.readLine()) != null) {
        strBuilder.append(line);
      }
      AppLogger.d("result=" + strBuilder.toString());
      return strBuilder.toString();
    } catch (IOException e) {
      e.printStackTrace();
      throw new WeiboException(errorStr, e);
    } finally {
      Utility.closeSilently(is);
      Utility.closeSilently(buffer);
      urlConnection.disconnect();
    }
  }
    @Override
    public void run() {
      if (!SettingUtility.getEnableAutoRefresh()) {
        return;
      }

      if (!Utility.isTaskStopped(dbTask)) {
        return;
      }

      if (!allowRefresh()) {
        return;
      }

      if (!Utility.isWifi(getActivity())) {
        return;
      }

      if (isListViewFling()
          || !isVisible()
          || ((MainTimeLineActivity) getActivity()).getSlidingMenu().isMenuShowing()) {
        return;
      }

      Bundle bundle = new Bundle();
      bundle.putBoolean(BundleArgsConstants.SCROLL_TO_TOP, false);
      bundle.putBoolean(BundleArgsConstants.AUTO_REFRESH, true);
      getLoaderManager().restartLoader(NEW_MSG_LOADER_ID, bundle, msgAsyncTaskLoaderCallback);
    }
  public void buildActionBarNav() {
    if ((((MainTimeLineActivity) getActivity()).getMenuFragment()).getCurrentIndex()
        != LeftMenuFragment.HOME_INDEX) {
      return;
    }
    ((MainTimeLineActivity) getActivity()).setCurrentFragment(this);

    getActivity().getActionBar().setDisplayShowTitleEnabled(false);
    getActivity().getActionBar().setDisplayHomeAsUpEnabled(Utility.isDevicePort());
    getActivity().getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
    List<GroupBean> list = new ArrayList<GroupBean>();
    if (GlobalContext.getInstance().getGroup() != null) {
      list = GlobalContext.getInstance().getGroup().getLists();
    } else {
      list = new ArrayList<GroupBean>();
    }

    navAdapter = new FriendsTimeLineListNavAdapter(getActivity(), buildListNavData(list));
    final List<GroupBean> finalList = list;
    getActivity()
        .getActionBar()
        .setListNavigationCallbacks(
            navAdapter,
            new ActionBar.OnNavigationListener() {
              @Override
              public boolean onNavigationItemSelected(int which, long itemId) {

                if (!Utility.isTaskStopped(dbTask)) {
                  return true;
                }

                String groupId = getGroupIdFromIndex(which, finalList);

                if (!groupId.equals(currentGroupId)) {

                  switchFriendsGroup(groupId);
                }
                return true;
              }
            });
    currentGroupId =
        FriendsTimeLineDBTask.getRecentGroupId(GlobalContext.getInstance().getCurrentAccountId());

    if (Utility.isDevicePort()) {
      ((MainTimeLineActivity) getActivity()).setTitle("");
      getActivity().getActionBar().setIcon(R.drawable.ic_menu_home);
    } else {
      ((MainTimeLineActivity) getActivity()).setTitle("");
      getActivity().getActionBar().setIcon(R.drawable.ic_launcher);
    }

    if (getActivity().getActionBar().getNavigationMode() == ActionBar.NAVIGATION_MODE_LIST
        && isVisible()) {
      getActivity().getActionBar().setSelectedNavigationItem(getRecentNavIndex());
    }
  }
Example #4
0
  @Override
  protected void onPause() {
    super.onPause();
    Utility.unregisterReceiverIgnoredReceiverNotRegisteredException(
        this, newMsgInterruptBroadcastReceiver);
    Utility.unregisterReceiverIgnoredReceiverNotRegisteredException(this, musicReceiver);

    if (isFinishing()) {
      saveNavigationPositionToDB();
    }
  }
  @Override
  protected void oldMsgLoaderSuccessCallback(MessageListBean oldValue) {
    if (Utility.isAllNotNull(getActivity(), oldValue) && oldValue.getSize() > 1) {
      getList().addOldData(oldValue);
      putToGroupDataMemoryCache(currentGroupId, getList());
      FriendsTimeLineDBTask.asyncReplace(getList(), accountBean.getUid(), currentGroupId);

    } else if (Utility.isAllNotNull(getActivity())) {
      Toast.makeText(getActivity(), getString(R.string.older_message_empty), Toast.LENGTH_SHORT)
          .show();
    }
  }
Example #6
0
 @Override
 protected void onResume() {
   super.onResume();
   IntentFilter filter = new IntentFilter(AppEventAction.NEW_MSG_PRIORITY_BROADCAST);
   filter.setPriority(1);
   newMsgInterruptBroadcastReceiver = new NewMsgInterruptBroadcastReceiver();
   Utility.registerReceiverIgnoredReceiverHasRegisteredHereException(
       this, newMsgInterruptBroadcastReceiver, filter);
   musicReceiver = new MusicReceiver();
   Utility.registerReceiverIgnoredReceiverHasRegisteredHereException(
       this, musicReceiver, AppEventAction.getSystemMusicBroadcastFilterAction());
   readClipboard();
   // ensure timeline picture type is correct
   ConnectionChangeReceiver.judgeNetworkStatus(this, false);
 }
  @Override
  protected boolean canSend() {

    boolean haveContent = !TextUtils.isEmpty(getEditTextView().getText().toString());
    boolean haveToken = !TextUtils.isEmpty(token);
    int sum = Utility.length(getEditTextView().getText().toString());
    int num = 140 - sum;

    boolean contentNumBelow140 = (num >= 0);

    if (haveContent && haveToken && contentNumBelow140) {
      return true;
    } else {
      if (!haveContent && !haveToken) {
        Toast.makeText(
                this,
                getString(R.string.content_cant_be_empty_and_dont_have_account),
                Toast.LENGTH_SHORT)
            .show();
      } else if (!haveContent) {
        getEditTextView().setError(getString(R.string.content_cant_be_empty));
      } else if (!haveToken) {
        Toast.makeText(this, getString(R.string.dont_have_account), Toast.LENGTH_SHORT).show();
      }

      if (!contentNumBelow140) {
        getEditTextView().setError(getString(R.string.content_words_number_too_many));
      }
    }

    return false;
  }
Example #8
0
  public String doGet(String urlStr, Map<String, String> param) throws WeiboException {
    GlobalContext globalContext = GlobalContext.getInstance();
    String errorStr = globalContext.getString(R.string.timeout);
    globalContext = null;
    InputStream is = null;
    try {

      StringBuilder urlBuilder = new StringBuilder(urlStr);
      urlBuilder.append("?").append(Utility.encodeUrl(param));
      URL url = new URL(urlBuilder.toString());
      AppLogger.d("get request" + url);
      Proxy proxy = getProxy();
      HttpURLConnection urlConnection;
      if (proxy != null) urlConnection = (HttpURLConnection) url.openConnection(proxy);
      else urlConnection = (HttpURLConnection) url.openConnection();

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

      urlConnection.connect();

      return handleResponse(urlConnection);
    } catch (IOException e) {
      e.printStackTrace();
      throw new WeiboException(errorStr, e);
    }
  }
  @Override
  public void onActivityCreated(Bundle savedInstanceState) {

    commander = ((AbstractAppActivity) getActivity()).getBitmapDownloader();

    switch (getCurrentState(savedInstanceState)) {
      case FIRST_TIME_START:
        if (Utility.isTaskStopped(dbTask)) {
          dbTask = new DBCacheTask();
          dbTask.executeOnExecutor(MyAsyncTask.THREAD_POOL_EXECUTOR);
        }
        break;
      case SCREEN_ROTATE:
        // nothing
        refreshLayout(getList());
        break;
      case ACTIVITY_DESTROY_AND_CREATE:
        getList().addNewData((MessageListBean) savedInstanceState.getSerializable("bean"));
        userBean = (UserBean) savedInstanceState.getSerializable("userBean");
        token = savedInstanceState.getString("token");
        getAdapter().notifyDataSetChanged();
        refreshLayout(bean);
        break;
    }

    super.onActivityCreated(savedInstanceState);
  }
Example #10
0
  public String doPost(String urlAddress, Map<String, String> param) throws WeiboException {
    GlobalContext globalContext = GlobalContext.getInstance();
    String errorStr = globalContext.getString(R.string.timeout);
    globalContext = null;
    try {
      URL url = new URL(urlAddress);
      Proxy proxy = getProxy();
      HttpURLConnection uRLConnection;
      if (proxy != null) uRLConnection = (HttpURLConnection) url.openConnection(proxy);
      else uRLConnection = (HttpURLConnection) url.openConnection();

      uRLConnection.setDoInput(true);
      uRLConnection.setDoOutput(true);
      uRLConnection.setRequestMethod("POST");
      uRLConnection.setUseCaches(false);
      uRLConnection.setConnectTimeout(CONNECT_TIMEOUT);
      uRLConnection.setReadTimeout(READ_TIMEOUT);
      uRLConnection.setInstanceFollowRedirects(false);
      uRLConnection.setRequestProperty("Connection", "Keep-Alive");
      uRLConnection.setRequestProperty("Charset", "UTF-8");
      uRLConnection.setRequestProperty("Accept-Encoding", "gzip, deflate");
      uRLConnection.connect();

      DataOutputStream out = new DataOutputStream(uRLConnection.getOutputStream());
      out.write(Utility.encodeUrl(param).getBytes());
      out.flush();
      out.close();
      return handleResponse(uRLConnection);
    } catch (IOException e) {
      e.printStackTrace();
      throw new WeiboException(errorStr, e);
    }
  }
  public void switchFriendsGroup(String groupId) {
    getLoaderManager().destroyLoader(NEW_MSG_LOADER_ID);
    getLoaderManager().destroyLoader(MIDDLE_MSG_LOADER_ID);
    getLoaderManager().destroyLoader(OLD_MSG_LOADER_ID);
    getPullToRefreshListView().onRefreshComplete();
    dismissFooterView();
    savedCurrentLoadingMsgViewPositon = -1;
    if (timeLineAdapter instanceof AbstractAppListAdapter) {
      ((AbstractAppListAdapter) timeLineAdapter)
          .setSavedMiddleLoadingViewPosition(savedCurrentLoadingMsgViewPositon);
    }

    positionCache.put(currentGroupId, Utility.getCurrentPositionFromListView(getListView()));
    saveNewMsgCountToPositionsCache();
    setSelected(groupId);
    newMsgTipBar.clearAndReset();
    if (groupDataCache.get(currentGroupId) == null
        || groupDataCache.get(currentGroupId).getSize() == 0) {
      getList().getItemList().clear();
      getAdapter().notifyDataSetChanged();
      getPullToRefreshListView().setRefreshing();
      loadNewMsg();

    } else {
      getList().replaceData(groupDataCache.get(currentGroupId));
      getAdapter().notifyDataSetChanged();
      setListViewPositionFromPositionsCache();
      saveGroupIdToDB();
      new RefreshReCmtCountTask(this, getList())
          .executeOnExecutor(MyAsyncTask.THREAD_POOL_EXECUTOR);
    }
  }
 public void clear() {
   ArrayList<String> deletedList = new ArrayList<String>();
   deletedList.addAll(list);
   list.clear();
   adapter.notifyDataSetChanged();
   if (Utility.isTaskStopped(removeTask)) {
     removeTask = new RemoveFilterDBTask(deletedList);
     removeTask.executeOnExecutor(MyAsyncTask.THREAD_POOL_EXECUTOR);
   }
 }
Example #13
0
 private void readClipboard() {
   ClipboardManager cm =
       (ClipboardManager) getApplicationContext().getSystemService(Context.CLIPBOARD_SERVICE);
   ClipData cmContent = cm.getPrimaryClip();
   if (cmContent == null) {
     return;
   }
   ClipData.Item item = cmContent.getItemAt(0);
   if (item != null) {
     String url = item.coerceToText(this).toString();
     boolean a =
         !TextUtils.isEmpty(url) && !url.equals(SettingUtility.getLastFoundWeiboAccountLink());
     boolean b = Utility.isWeiboAccountIdLink(url) || Utility.isWeiboAccountDomainLink(url);
     if (a && b) {
       OpenWeiboAccountLinkDialog dialog = new OpenWeiboAccountLinkDialog(url);
       dialog.show(getSupportFragmentManager(), "");
       SettingUtility.setLastFoundWeiboAccountLink(url);
     }
   }
 }
Example #14
0
  private String getWeiboOAuthUrl() {

    Map<String, String> parameters = new HashMap<String, String>();
    parameters.put("client_id", URLHelper.APP_KEY);
    parameters.put("response_type", "token");
    parameters.put("redirect_uri", URLHelper.DIRECT_URL);
    parameters.put("display", "mobile");
    return URLHelper.URL_OAUTH2_ACCESS_AUTHORIZE
        + "?"
        + Utility.encodeUrl(parameters)
        + "&scope=friendships_groups_read,friendships_groups_write";
  }
 private void startDownloadingOtherPicturesOnWifiNetworkEnvironment() {
   if (backgroundWifiDownloadPicThread == null
       && Utility.isWifi(getActivity())
       && SettingUtility.getEnableBigPic()
       && SettingUtility.isWifiAutoDownloadPic()) {
     final int position = getListView().getFirstVisiblePosition();
     int listVewOrientation = ((VelocityListView) getListView()).getTowardsOrientation();
     WifiAutoDownloadPictureRunnable runnable =
         new WifiAutoDownloadPictureRunnable(getList(), position, listVewOrientation);
     backgroundWifiDownloadPicThread = new Thread(runnable);
     backgroundWifiDownloadPicThread.start();
     AppLogger.i(
         "WifiAutoDownloadPictureRunnable startDownloadingOtherPicturesOnWifiNetworkEnvironment");
   }
 }
 @Override
 protected void newMsgLoaderSuccessCallback(MessageListBean newValue, Bundle loaderArgs) {
   if (Utility.isAllNotNull(getActivity(), newValue) && newValue.getSize() > 0) {
     if (loaderArgs != null && loaderArgs.getBoolean(BundleArgsConstants.AUTO_REFRESH, false)) {
       addNewDataAndRememberPositionAutoRefresh(newValue);
     } else {
       boolean scrollToTop = SettingUtility.isReadStyleEqualWeibo();
       if (scrollToTop) {
         addNewDataWithoutRememberPosition(newValue);
       } else {
         addNewDataAndRememberPosition(newValue);
       }
     }
     putToGroupDataMemoryCache(currentGroupId, getList());
     FriendsTimeLineDBTask.asyncReplace(getList(), accountBean.getUid(), currentGroupId);
   }
 }
 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
   switch (item.getItemId()) {
     case android.R.id.home:
       Intent intent = new Intent(this, AccountActivity.class);
       intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
       intent.putExtra("launcher", false);
       startActivity(intent);
       return true;
     case R.id.menu_login:
       if (Utility.isTaskStopped(loginTask)) {
         loginTask = new LoginTask();
         loginTask.executeOnExecutor(MyAsyncTask.THREAD_POOL_EXECUTOR);
       }
       return true;
     default:
       return super.onOptionsItemSelected(item);
   }
 }
Example #18
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");
    }
  }
Example #19
0
    @Override
    protected DBResult doInBackground(String... params) {

      String token = params[0];
      long expiresInSeconds = Long.valueOf(params[1]);

      try {
        UserBean user = new OAuthDao(token).getOAuthUserInfo();
        AccountBean account = new AccountBean();
        account.setAccess_token(token);
        account.setExpires_time(System.currentTimeMillis() + expiresInSeconds * 1000);
        account.setInfo(user);
        AppLogger.e("token expires in " + Utility.calcTokenExpiresInDays(account) + " days");
        return AccountDBTask.addOrUpdateAccount(account, false);
      } catch (WeiboException e) {
        AppLogger.e(e.getError());
        this.e = e;
        cancel(true);
        return null;
      }
    }
Example #20
0
  @Override
  protected String doInBackground(Void... arg) {
    if (isCancelled()) {
      return null;
    }

    if (Utility.isWifi(GlobalContext.getInstance())) {
      boolean result =
          TaskCache.waitForPictureDownload(
              msg.getOriginal_pic(), downloadListener, oriPath, FileLocationMethod.picture_large);
      return result ? oriPath : null;
    } else {
      boolean result =
          TaskCache.waitForPictureDownload(
              msg.getBmiddle_pic(),
              downloadListener,
              middlePath,
              FileLocationMethod.picture_bmiddle);
      return result ? middlePath : null;
    }
  }
Example #21
0
  private void handleRedirectUrl(WebView view, String url) {
    Bundle values = Utility.parseUrl(url);

    String error = values.getString("error");
    String error_code = values.getString("error_code");

    Intent intent = new Intent();
    intent.putExtras(values);

    if (error == null && error_code == null) {

      String access_token = values.getString("access_token");
      String expires_time = values.getString("expires_in");
      setResult(RESULT_OK, intent);
      new OAuthTask().execute(access_token, expires_time);
    } else {
      Toast.makeText(OAuthActivity.this, getString(R.string.you_cancel_login), Toast.LENGTH_SHORT)
          .show();
      finish();
    }
  }
Example #22
0
  private void configSlidingMenu(boolean phone) {
    SlidingMenu slidingMenu = getSlidingMenu();
    slidingMenu.setShadowWidthRes(R.dimen.shadow_width);
    slidingMenu.setShadowDrawable(R.drawable.shadow_slidingmenu);
    if (phone) {
      slidingMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
    } else {
      slidingMenu.setBehindOffset(Utility.getScreenWidth());
    }

    slidingMenu.setFadeDegree(0.35f);
    slidingMenu.setOnPageScrollListener(
        new SlidingMenu.OnPageScrollListener() {
          @Override
          public void onPageScroll() {
            LongClickableLinkMovementMethod.getInstance().setLongClickable(false);
            (getFriendsTimeLineFragment()).clearActionMode();
            (getFavFragment()).clearActionMode();
            (getCommentsTimeLineFragment()).clearActionMode();
            (getMentionsTimeLineFragment()).clearActionMode();
            (getMyProfileFragment()).clearActionMode();

            if (GlobalContext.getInstance().getAccountBean().isBlack_magic()) {
              (getSearchFragment()).clearActionMode();
              (getDMFragment()).clearActionMode();
            }
          }
        });

    slidingMenu.setOnClosedListener(
        new SlidingMenu.OnClosedListener() {
          @Override
          public void onClosed() {
            LongClickableLinkMovementMethod.getInstance().setLongClickable(true);
            LocalBroadcastManager.getInstance(MainTimeLineActivity.this)
                .sendBroadcast(new Intent(AppEventAction.SLIDING_MENU_CLOSED_BROADCAST));
          }
        });
  }
  protected void middleMsgLoaderSuccessCallback(
      int position, MessageListBean newValue, boolean towardsBottom) {

    if (newValue == null) {
      return;
    }

    int size = newValue.getSize();

    if (getActivity() != null && newValue.getSize() > 0) {
      getList().addMiddleData(position, newValue, towardsBottom);

      if (towardsBottom) {
        getAdapter().notifyDataSetChanged();
      } else {

        View v = Utility.getListViewItemViewFromPosition(getListView(), position + 1 + 1);
        int top = (v == null) ? 0 : v.getTop();
        getAdapter().notifyDataSetChanged();
        int ss = position + 1 + size - 1;
        getListView().setSelectionFromTop(ss, top);
      }
    }
  }
  private void animateClose(ObjectAnimator backgroundAnimator) {

    AnimationRect rect = getArguments().getParcelable("rect");

    if (rect == null) {
      photoView.animate().alpha(0);
      backgroundAnimator.start();
      return;
    }

    final Rect startBounds = rect.scaledBitmapRect;
    final Rect finalBounds = AnimationUtility.getBitmapRectFromImageView(photoView);

    if (finalBounds == null) {
      photoView.animate().alpha(0);
      backgroundAnimator.start();
      return;
    }

    if (Utility.isDevicePort() != rect.isScreenPortrait) {
      photoView.animate().alpha(0);
      backgroundAnimator.start();
      return;
    }

    float startScale;
    if ((float) finalBounds.width() / finalBounds.height()
        > (float) startBounds.width() / startBounds.height()) {
      startScale = (float) startBounds.height() / finalBounds.height();

    } else {
      startScale = (float) startBounds.width() / finalBounds.width();
    }

    final float startScaleFinal = startScale;

    int deltaTop = startBounds.top - finalBounds.top;
    int deltaLeft = startBounds.left - finalBounds.left;

    photoView.setPivotY((photoView.getHeight() - finalBounds.height()) / 2);
    photoView.setPivotX((photoView.getWidth() - finalBounds.width()) / 2);

    photoView
        .animate()
        .translationX(deltaLeft)
        .translationY(deltaTop)
        .scaleY(startScaleFinal)
        .scaleX(startScaleFinal)
        .setDuration(ANIMATION_DURATION)
        .setInterpolator(new AccelerateDecelerateInterpolator())
        .withEndAction(
            new Runnable() {
              @Override
              public void run() {

                photoView
                    .animate()
                    .alpha(0.0f)
                    .setDuration(200)
                    .withEndAction(
                        new Runnable() {
                          @Override
                          public void run() {}
                        });
              }
            });

    AnimatorSet animationSet = new AnimatorSet();
    animationSet.setDuration(ANIMATION_DURATION);
    animationSet.setInterpolator(new AccelerateDecelerateInterpolator());

    animationSet.playTogether(backgroundAnimator);

    animationSet.playTogether(
        ObjectAnimator.ofFloat(
            photoView, "clipBottom", 0, AnimationRect.getClipBottom(rect, finalBounds)));
    animationSet.playTogether(
        ObjectAnimator.ofFloat(
            photoView, "clipRight", 0, AnimationRect.getClipRight(rect, finalBounds)));
    animationSet.playTogether(
        ObjectAnimator.ofFloat(
            photoView, "clipTop", 0, AnimationRect.getClipTop(rect, finalBounds)));
    animationSet.playTogether(
        ObjectAnimator.ofFloat(
            photoView, "clipLeft", 0, AnimationRect.getClipLeft(rect, finalBounds)));

    animationSet.start();
  }
 @Override
 protected void onDestroy() {
   super.onDestroy();
   Utility.cancelTasks(loginTask);
 }
Example #26
0
  public boolean doUploadFile(
      String urlStr,
      Map<String, String> param,
      String path,
      final FileUploaderHttpHelper.ProgressListener listener)
      throws WeiboException {
    String BOUNDARYSTR = getBoundry();
    String BOUNDARY = "--" + BOUNDARYSTR + "\r\n";
    HttpURLConnection urlConnection = null;
    BufferedOutputStream out = null;
    FileInputStream fis = null;
    GlobalContext globalContext = GlobalContext.getInstance();
    String errorStr = globalContext.getString(R.string.timeout);
    globalContext = null;
    InputStream is = null;
    try {
      URL url = null;

      url = new URL(urlStr);

      Proxy proxy = getProxy();
      if (proxy != null) urlConnection = (HttpURLConnection) url.openConnection(proxy);
      else urlConnection = (HttpURLConnection) url.openConnection();

      urlConnection.setConnectTimeout(UPLOAD_CONNECT_TIMEOUT);
      urlConnection.setReadTimeout(UPLOAD_READ_TIMEOUT);
      urlConnection.setDoInput(true);
      urlConnection.setDoOutput(true);
      urlConnection.setRequestMethod("POST");
      urlConnection.setUseCaches(false);
      urlConnection.setRequestProperty("Connection", "Keep-Alive");
      urlConnection.setRequestProperty("Charset", "UTF-8");
      urlConnection.setRequestProperty(
          "Content-type", "multipart/form-data;boundary=" + BOUNDARYSTR);
      urlConnection.connect();

      out = new BufferedOutputStream(urlConnection.getOutputStream());

      StringBuilder sb = new StringBuilder();

      Map<String, String> paramMap = new HashMap<String, String>();

      for (String key : param.keySet()) {
        if (param.get(key) != null) {
          paramMap.put(key, param.get(key));
        }
      }

      for (String str : paramMap.keySet()) {
        sb.append(BOUNDARY);
        sb.append("Content-Disposition:form-data;name=\"");
        sb.append(str);
        sb.append("\"\r\n\r\n");
        sb.append(param.get(str));
        sb.append("\r\n");
      }

      out.write(sb.toString().getBytes());

      File file = new File(path);
      out.write(BOUNDARY.getBytes());
      StringBuilder filenamesb = new StringBuilder();
      filenamesb.append(
          "Content-Disposition:form-data;Content-Type:application/octet-stream;name=\"pic");
      filenamesb.append("\";filename=\"");
      filenamesb.append(file.getName() + "\"\r\n\r\n");
      out.write(filenamesb.toString().getBytes());

      fis = new FileInputStream(file);

      int bytesRead;
      int bytesAvailable;
      int bufferSize;
      byte[] buffer;
      int maxBufferSize = 1 * 1024;

      bytesAvailable = fis.available();
      bufferSize = Math.min(bytesAvailable, maxBufferSize);
      buffer = new byte[bufferSize];
      bytesRead = fis.read(buffer, 0, bufferSize);
      long transferred = 0;
      final Thread thread = Thread.currentThread();
      while (bytesRead > 0) {

        if (thread.isInterrupted()) {
          file.delete();
          throw new InterruptedIOException();
        }
        out.write(buffer, 0, bufferSize);
        bytesAvailable = fis.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = fis.read(buffer, 0, bufferSize);
        transferred += bytesRead;
        if (transferred % 50 == 0) out.flush();
        if (listener != null) listener.transferred(transferred);
      }

      out.write("\r\n\r\n".getBytes());
      fis.close();

      out.write(("--" + BOUNDARYSTR + "--\r\n").getBytes());
      out.flush();
      out.close();
      int status = urlConnection.getResponseCode();
      if (listener != null) {
        listener.completed();
      }
      if (status != HttpURLConnection.HTTP_OK) {
        String error = handleError(urlConnection);
        throw new WeiboException(error);
      }

    } catch (IOException e) {
      e.printStackTrace();
      throw new WeiboException(errorStr, e);
    } finally {
      Utility.closeSilently(fis);
      Utility.closeSilently(out);
      if (urlConnection != null) urlConnection.disconnect();
    }

    return true;
  }
Example #27
0
  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;
  }
 @Override
 public void onDestroy() {
   super.onDestroy();
   Utility.cancelTasks(dbTask);
   GlobalContext.getInstance().unRegisterForAccountChangeListener(this);
 }
  @Override
  public void onActivityCreated(Bundle savedInstanceState) {

    switch (getCurrentState(savedInstanceState)) {
      case FIRST_TIME_START:
        if (Utility.isTaskStopped(dbTask) && getList().getSize() == 0) {
          dbTask = new DBCacheTask(this, accountBean.getUid());
          dbTask.executeOnExecutor(MyAsyncTask.THREAD_POOL_EXECUTOR);
          GroupInfoTask groupInfoTask =
              new GroupInfoTask(
                  GlobalContext.getInstance().getSpecialToken(),
                  GlobalContext.getInstance().getCurrentAccountId());
          groupInfoTask.executeOnExecutor(MyAsyncTask.THREAD_POOL_EXECUTOR);
        } else {
          getAdapter().notifyDataSetChanged();
          refreshLayout(getList());
        }

        groupDataCache.put(ALL_GROUP_ID, new MessageListBean());
        groupDataCache.put(BILATERAL_GROUP_ID, new MessageListBean());

        if (getList().getSize() > 0) {
          groupDataCache.put(ALL_GROUP_ID, getList().copy());
        }
        buildActionBarNav();

        break;
      case SCREEN_ROTATE:
        // nothing
        refreshLayout(getList());
        buildActionBarNav();
        setListViewPositionFromPositionsCache();
        break;
      case ACTIVITY_DESTROY_AND_CREATE:
        userBean = savedInstanceState.getParcelable("userBean");
        accountBean = savedInstanceState.getParcelable("account");
        token = savedInstanceState.getString("token");

        if (Utility.isTaskStopped(dbTask) && getList().getSize() == 0) {
          dbTask = new DBCacheTask(this, accountBean.getUid());
          dbTask.executeOnExecutor(MyAsyncTask.THREAD_POOL_EXECUTOR);
          GroupInfoTask groupInfoTask =
              new GroupInfoTask(
                  GlobalContext.getInstance().getSpecialToken(),
                  GlobalContext.getInstance().getCurrentAccountId());
          groupInfoTask.executeOnExecutor(MyAsyncTask.THREAD_POOL_EXECUTOR);
        } else {
          getAdapter().notifyDataSetChanged();
          refreshLayout(getList());
        }

        groupDataCache.put(ALL_GROUP_ID, new MessageListBean());
        groupDataCache.put(BILATERAL_GROUP_ID, new MessageListBean());

        if (getList().getSize() > 0) {
          groupDataCache.put(ALL_GROUP_ID, getList().copy());
        }
        buildActionBarNav();

        break;
    }

    super.onActivityCreated(savedInstanceState);
  }
 @Override
 public void scrollToTop() {
   Utility.stopListViewScrollingAndScrollToTop(getListView());
 }