protected Loader<AsyncTaskLoaderResult<MessageListBean>> onCreateOldMsgLoader(
     int id, Bundle args) {
   String accountId = accountBean.getUid();
   String token = accountBean.getAccess_token();
   String maxId = null;
   if (getList().getItemList().size() > 0) {
     maxId = getList().getItemList().get(getList().getItemList().size() - 1).getId();
   }
   return new FriendsMsgLoader(getActivity(), accountId, token, currentGroupId, null, maxId);
 }
  @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();
    }
  }
 protected Loader<AsyncTaskLoaderResult<MessageListBean>> onCreateMiddleMsgLoader(
     int id,
     Bundle args,
     String middleBeginId,
     String middleEndId,
     String middleEndTag,
     int middlePosition) {
   String accountId = accountBean.getUid();
   String token = accountBean.getAccess_token();
   return new FriendsMsgLoader(
       getActivity(), accountId, token, currentGroupId, middleBeginId, middleEndId);
 }
  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {

    AccountBean accountBean = intent.getParcelableExtra(NotificationServiceHelper.ACCOUNT_ARG);

    if (accountBean == null) {
      throw new IllegalArgumentException(
          "you must use BigTextNotificationService newIntent method");
    }

    ValueWrapper valueWrapper = valueBagHashMap.get(accountBean.getUid());

    if (valueWrapper == null) {
      valueWrapper = new ValueWrapper();
    }

    valueWrapper.accountBean = intent.getParcelableExtra(NotificationServiceHelper.ACCOUNT_ARG);
    valueWrapper.mentionsWeibo =
        intent.getParcelableExtra(NotificationServiceHelper.MENTIONS_WEIBO_ARG);
    valueWrapper.commentsToMe =
        intent.getParcelableExtra(NotificationServiceHelper.COMMENTS_TO_ME_ARG);
    valueWrapper.mentionsComment =
        intent.getParcelableExtra(NotificationServiceHelper.MENTIONS_COMMENT_ARG);
    valueWrapper.unreadBean = intent.getParcelableExtra(NotificationServiceHelper.UNREAD_ARG);
    valueWrapper.currentIndex = intent.getIntExtra(NotificationServiceHelper.CURRENT_INDEX_ARG, 0);
    valueWrapper.clickToOpenAppPendingIntentInner =
        intent.getParcelableExtra(NotificationServiceHelper.PENDING_INTENT_INNER_ARG);
    valueWrapper.ticker = intent.getStringExtra(NotificationServiceHelper.TICKER);

    ArrayList<Parcelable> notificationItems = new ArrayList<Parcelable>();
    if (valueWrapper.commentsToMe != null) {
      notificationItems.addAll(valueWrapper.commentsToMe.getItemList());
    }
    if (valueWrapper.mentionsComment != null) {
      notificationItems.addAll(valueWrapper.mentionsComment.getItemList());
    }
    if (valueWrapper.mentionsWeibo != null) {
      notificationItems.addAll(valueWrapper.mentionsWeibo.getItemList());
    }
    valueWrapper.notificationItems = notificationItems;
    valueBagHashMap.put(valueWrapper.accountBean.getUid(), valueWrapper);

    AppLogger.i("service account name=" + valueWrapper.accountBean.getUsernick());

    buildNotification(valueWrapper.accountBean.getUid());

    stopSelf();

    return super.onStartCommand(intent, flags, startId);
  }
  private void updateTimeLineMessageCommentAndRepostData(List<MessageReCmtCountBean> value) {

    if (getList().getSize() <= value.size()) {
      return;
    }

    for (int i = 0; i < value.size(); i++) {
      MessageBean msg = getList().getItem(i);
      MessageReCmtCountBean count = value.get(i);
      if (msg != null && msg.getId().equals(count.getId())) {
        msg.setReposts_count(count.getReposts());
        msg.setComments_count(count.getComments());
      }
    }
    getAdapter().notifyDataSetChanged();
    FriendsTimeLineDBTask.asyncReplace(getList(), accountBean.getUid(), currentGroupId);
  }
 @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
 protected MessageListBean getDoInBackgroundNewData() throws WeiboException {
   MainFriendsTimeLineDao dao;
   if (selectedId.equals("1")) {
     dao = new BilateralTimeLineDao(token);
   } else if (selectedId.equals("0")) {
     dao = new MainFriendsTimeLineDao(token);
   } else {
     dao = new FriendGroupTimeLineDao(token, selectedId);
   }
   if (getList().getItemList().size() > 0) {
     dao.setSince_id(getList().getItemList().get(0).getId());
   }
   MessageListBean result = dao.getGSONMsgList();
   if (result != null && selectedId.equals("0")) {
     DatabaseManager.getInstance().addHomeLineMsg(result, accountBean.getUid());
   }
   return result;
 }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (savedInstanceState != null) {
      accountBean = savedInstanceState.getParcelable("account");
    } else {
      Intent intent = getIntent();
      accountBean = intent.getParcelableExtra(BundleArgsConstants.ACCOUNT_EXTRA);
    }

    if (accountBean == null) {
      accountBean = GlobalContext.getInstance().getAccountBean();
    }

    GlobalContext.getInstance().setGroup(null);
    GlobalContext.getInstance().setAccountBean(accountBean);
    SettingUtility.setDefaultAccountId(accountBean.getUid());

    buildInterface(savedInstanceState);
  }
  @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);
  }
  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());
  }
  private void buildNotification(String uid) {

    ValueWrapper valueWrapper = valueBagHashMap.get(uid);

    if (valueWrapper == null) {
      return;
    }

    final AccountBean accountBean = valueWrapper.accountBean;
    final UnreadBean unreadBean = valueWrapper.unreadBean;

    Intent clickToOpenAppPendingIntentInner = valueWrapper.clickToOpenAppPendingIntentInner;

    String ticker = valueWrapper.ticker;

    final RecordOperationAppBroadcastReceiver clearNotificationEventReceiver =
        valueWrapper.clearNotificationEventReceiver;

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

    builder.setContentTitle(ticker);

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

    valueWrapper.clearNotificationEventReceiver =
        new RecordOperationAppBroadcastReceiver() {
          @Override
          public void onReceive(Context context, Intent intent) {
            new Thread(
                    new Runnable() {
                      @Override
                      public void run() {
                        try {
                          new ClearUnreadDao(accountBean.getAccess_token())
                              .clearMentionStatusUnread(unreadBean, accountBean.getUid());
                          new ClearUnreadDao(accountBean.getAccess_token())
                              .clearMentionCommentUnread(unreadBean, accountBean.getUid());
                          new ClearUnreadDao(accountBean.getAccess_token())
                              .clearCommentUnread(unreadBean, accountBean.getUid());
                        } catch (WeiboException ignored) {

                        } finally {
                          Utility.unregisterReceiverIgnoredReceiverNotRegisteredException(
                              GlobalContext.getInstance(), clearNotificationEventReceiver);
                          if (Utility.isDebugMode()) {
                            new Handler(Looper.getMainLooper())
                                .post(
                                    new Runnable() {
                                      @Override
                                      public void run() {
                                        Toast.makeText(
                                                getApplicationContext(),
                                                "weiciyuan:remove notification items",
                                                Toast.LENGTH_SHORT)
                                            .show();
                                      }
                                    });
                          }
                        }
                      }
                    })
                .start();
          }
        };

    IntentFilter intentFilter = new IntentFilter(RESET_UNREAD_MENTIONS_WEIBO_ACTION);

    GlobalContext.getInstance()
        .registerReceiver(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);

    Utility.configVibrateLedRingTone(builder);

    NotificationManager notificationManager =
        (NotificationManager) getApplicationContext().getSystemService(NOTIFICATION_SERVICE);
    notificationManager.notify(getMentionsWeiboNotificationId(accountBean), builder.build());
  }