Example usage for android.text.format DateUtils SECOND_IN_MILLIS

List of usage examples for android.text.format DateUtils SECOND_IN_MILLIS

Introduction

In this page you can find the example usage for android.text.format DateUtils SECOND_IN_MILLIS.

Prototype

long SECOND_IN_MILLIS

To view the source code for android.text.format DateUtils SECOND_IN_MILLIS.

Click Source Link

Usage

From source file:com.namelessdev.mpdroid.NotificationService.java

@Override
public void stateChanged(final MPDStatus mpdStatus, final String oldState) {
    if (mpdStatus == null) {
        Log.w(TAG, "Null mpdStatus received in stateChanged");
    } else {/* w  ww  .  j  ava2 s.co  m*/
        lastStatusRefresh = new Date().getTime();
        // MPDs elapsed time is in seconds, convert to milliseconds
        lastKnownElapsed = mpdStatus.getElapsedTime() * DateUtils.SECOND_IN_MILLIS;
        switch (mpdStatus.getState()) {
        case MPDStatus.MPD_STATE_PLAYING:
            stopServiceHandler();
            tryToGetAudioFocus();
            updatePlayingInfo(mpdStatus);
            break;
        case MPDStatus.MPD_STATE_STOPPED:
            if (app.getApplicationState().persistentNotification) {
                windDownResources(); /** Hide immediately, requires user intervention */
            } else {
                stopSelf();
            }
            break;
        case MPDStatus.MPD_STATE_PAUSED:
            if (!serviceHandlerActive) {
                setupServiceHandler();
                updatePlayingInfo(mpdStatus);
            }
            break;
        default:
            break;
        }
    }
}

From source file:com.audiokernel.euphonyrmt.fragments.NowPlayingFragment.java

private void startPosTimer(final long start, final long total) {
    stopPosTimer();//w w  w .  j  a va2s .c  om
    mPosTimer = new Timer();
    final TimerTask posTimerTask = new PosTimerTask(start, total);
    mPosTimer.scheduleAtFixedRate(posTimerTask, 0L, DateUtils.SECOND_IN_MILLIS);
}

From source file:com.android.deskclock.timer.TimerFullScreenFragment.java

@Override
public void onFabClick(View view) {
    if (mLastVisibleView != mTimersListPage) {
        // New timer create if timer length is not zero
        // Create a new timer object to track the timer and
        // switch to the timers view.
        int timerLength = mTimerSetup.getTime();
        if (timerLength == 0) {
            return;
        }/*from w  w  w.  j  a  va  2 s .  c  o  m*/
        TimerObj t = new TimerObj(timerLength * DateUtils.SECOND_IN_MILLIS, getActivity());
        t.setState(TimerObj.STATE_RUNNING);
        mAdapter.addTimer(t);
        updateTimersState(t, Timers.START_TIMER);
        Events.sendTimerEvent(R.string.action_start, R.string.label_deskclock);
        gotoTimersView();
        mTimerSetup.reset(); // Make sure the setup is cleared for next time

        mTimersList.setFirstPositionAndOffsets(mAdapter.findTimerPositionById(t.mTimerId), 0);
    } else {
        mTimerSetup.reset();
        gotoSetupView();
    }
}

From source file:com.android.exchange.EasAccountService.java

private void runPingLoop()
        throws IOException, StaleFolderListException, IllegalHeartbeatException, CommandStatusException {
    int pingHeartbeat = mPingHeartbeat;
    userLog("runPingLoop");
    // Do push for all sync services here
    long endTime = System.currentTimeMillis() + (30 * DateUtils.MINUTE_IN_MILLIS);
    HashMap<String, Integer> pingErrorMap = new HashMap<String, Integer>();
    ArrayList<String> readyMailboxes = new ArrayList<String>();
    ArrayList<String> notReadyMailboxes = new ArrayList<String>();
    int pingWaitCount = 0;
    long inboxId = -1;
    android.accounts.Account amAccount = new android.accounts.Account(mAccount.mEmailAddress,
            Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE);
    while ((System.currentTimeMillis() < endTime) && !isStopped()) {
        // Count of pushable mailboxes
        int pushCount = 0;
        // Count of mailboxes that can be pushed right now
        int canPushCount = 0;
        // Count of uninitialized boxes
        int uninitCount = 0;

        Serializer s = new Serializer();
        Cursor c = mContentResolver.query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION,
                MailboxColumns.ACCOUNT_KEY + '=' + mAccount.mId
                        + AND_FREQUENCY_PING_PUSH_AND_NOT_ACCOUNT_MAILBOX,
                null, null);/*  w w  w . j a v a2 s  . co m*/
        if (c == null)
            throw new ProviderUnavailableException();
        notReadyMailboxes.clear();
        readyMailboxes.clear();
        // Look for an inbox, and remember its id
        if (inboxId == -1) {
            inboxId = Mailbox.findMailboxOfType(mContext, mAccount.mId, Mailbox.TYPE_INBOX);
        }
        try {
            // Loop through our pushed boxes seeing what is available to push
            while (c.moveToNext()) {
                pushCount++;
                // Two requirements for push:
                // 1) ExchangeService tells us the mailbox is syncable (not running/not stopped)
                // 2) The syncKey isn't "0" (i.e. it's synced at least once)
                long mailboxId = c.getLong(Mailbox.CONTENT_ID_COLUMN);
                String mailboxName = c.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN);

                // See what type of box we've got and get authority
                int mailboxType = c.getInt(Mailbox.CONTENT_TYPE_COLUMN);
                String authority = EmailContent.AUTHORITY;
                switch (mailboxType) {
                case Mailbox.TYPE_CALENDAR:
                    authority = CalendarContract.AUTHORITY;
                    break;
                case Mailbox.TYPE_CONTACTS:
                    authority = ContactsContract.AUTHORITY;
                    break;
                }

                // See whether we can ping for this mailbox
                int pingStatus;
                if (!ContentResolver.getSyncAutomatically(amAccount, authority)) {
                    pingStatus = ExchangeService.PING_STATUS_DISABLED;
                } else {
                    pingStatus = ExchangeService.pingStatus(mailboxId);

                }

                if (pingStatus == ExchangeService.PING_STATUS_OK) {
                    String syncKey = c.getString(Mailbox.CONTENT_SYNC_KEY_COLUMN);
                    if ((syncKey == null) || syncKey.equals("0")) {
                        // We can't push until the initial sync is done
                        pushCount--;
                        uninitCount++;
                        continue;
                    }

                    if (canPushCount++ == 0) {
                        // Initialize the Ping command
                        s.start(Tags.PING_PING)
                                .data(Tags.PING_HEARTBEAT_INTERVAL, Integer.toString(pingHeartbeat))
                                .start(Tags.PING_FOLDERS);
                    }

                    String folderClass = getTargetCollectionClassFromCursor(c);
                    s.start(Tags.PING_FOLDER).data(Tags.PING_ID, c.getString(Mailbox.CONTENT_SERVER_ID_COLUMN))
                            .data(Tags.PING_CLASS, folderClass).end();
                    readyMailboxes.add(mailboxName);
                } else if ((pingStatus == ExchangeService.PING_STATUS_RUNNING)
                        || (pingStatus == ExchangeService.PING_STATUS_WAITING)) {
                    notReadyMailboxes.add(mailboxName);
                } else if (pingStatus == ExchangeService.PING_STATUS_UNABLE) {
                    pushCount--;
                    userLog(mailboxName, " in error state; ignore");
                    continue;
                } else if (pingStatus == ExchangeService.PING_STATUS_DISABLED) {
                    pushCount--;
                    userLog(mailboxName, " disabled by user; ignore");
                    continue;
                }
            }
        } finally {
            c.close();
        }

        if (Eas.USER_LOG) {
            if (!notReadyMailboxes.isEmpty()) {
                userLog("Ping not ready for: " + notReadyMailboxes);
            }
            if (!readyMailboxes.isEmpty()) {
                userLog("Ping ready for: " + readyMailboxes);
            }
        }

        // If we've waited 10 seconds or more, just ping with whatever boxes are ready
        // But use a shorter than normal heartbeat
        boolean forcePing = !notReadyMailboxes.isEmpty() && (pingWaitCount > 5);

        if ((canPushCount > 0) && ((canPushCount == pushCount) || forcePing)) {
            // If all pingable boxes are ready for push, send Ping to the server
            s.end().end().done();
            pingWaitCount = 0;
            mPostAborted = false;
            mPostReset = false;

            // If we've been stopped, this is a good time to return
            if (isStopped())
                return;

            long pingTime = SystemClock.elapsedRealtime();
            try {
                // Send the ping, wrapped by appropriate timeout/alarm
                if (forcePing) {
                    userLog("Forcing ping after waiting for all boxes to be ready");
                }
                EasResponse resp = sendPing(s.toByteArray(), forcePing ? mPingForceHeartbeat : pingHeartbeat);

                try {
                    int code = resp.getStatus();
                    userLog("Ping response: ", code);

                    // If we're not allowed to sync (e.g. roaming policy), terminate gracefully
                    // now; otherwise we might start a sync based on the response
                    if (!ExchangeService.canAutoSync(mAccount)) {
                        stop();
                    }

                    // Return immediately if we've been asked to stop during the ping
                    if (isStopped()) {
                        userLog("Stopping pingLoop");
                        return;
                    }

                    if (code == HttpStatus.SC_OK) {
                        if (!resp.isEmpty()) {
                            InputStream is = resp.getInputStream();
                            int pingResult = parsePingResult(is, mContentResolver, pingErrorMap);
                            // If our ping completed (status = 1), and wasn't forced and we're
                            // not at the maximum, try increasing timeout by two minutes
                            if (pingResult == PROTOCOL_PING_STATUS_COMPLETED && !forcePing) {
                                if (pingHeartbeat > mPingHighWaterMark) {
                                    mPingHighWaterMark = pingHeartbeat;
                                    userLog("Setting high water mark at: ", mPingHighWaterMark);
                                }
                                if ((pingHeartbeat < mPingMaxHeartbeat) && !mPingHeartbeatDropped) {
                                    pingHeartbeat += PING_HEARTBEAT_INCREMENT;
                                    if (pingHeartbeat > mPingMaxHeartbeat) {
                                        pingHeartbeat = mPingMaxHeartbeat;
                                    }
                                    userLog("Increase ping heartbeat to ", pingHeartbeat, "s");
                                }
                            } else if (pingResult == PROTOCOL_PING_STATUS_BAD_PARAMETERS
                                    || pingResult == PROTOCOL_PING_STATUS_RETRY) {
                                // These errors appear to be server-related (I've seen a bad
                                // parameters result with known good parameters...)
                                userLog("Server error during Ping: " + pingResult);
                                // Act as if we have an IOException (backoff, etc.)
                                throw new IOException();
                            }
                            // Make sure to clear out any pending sync errors
                            ExchangeService.removeFromSyncErrorMap(mMailboxId);
                        } else {
                            userLog("Ping returned empty result; throwing IOException");
                            // Act as if we have an IOException (backoff, etc.)
                            throw new IOException();
                        }
                    } else if (resp.isAuthError()) {
                        mExitStatus = EasSyncService.EXIT_LOGIN_FAILURE;
                        userLog("Authorization error during Ping: ", code);
                        throw new IOException();
                    }
                } finally {
                    resp.close();
                }
            } catch (IOException e) {
                String message = e.getMessage();
                // If we get the exception that is indicative of a NAT timeout and if we
                // haven't yet "fixed" the timeout, back off by two minutes and "fix" it
                boolean hasMessage = message != null;
                userLog("IOException runPingLoop: " + (hasMessage ? message : "[no message]"));
                if (mPostReset) {
                    // Nothing to do in this case; this is ExchangeService telling us to try
                    // another ping.
                } else if (mPostAborted || isLikelyNatFailure(message)) {
                    long pingLength = SystemClock.elapsedRealtime() - pingTime;
                    if ((pingHeartbeat > mPingMinHeartbeat) && (pingHeartbeat > mPingHighWaterMark)) {
                        pingHeartbeat -= PING_HEARTBEAT_INCREMENT;
                        mPingHeartbeatDropped = true;
                        if (pingHeartbeat < mPingMinHeartbeat) {
                            pingHeartbeat = mPingMinHeartbeat;
                        }
                        userLog("Decreased ping heartbeat to ", pingHeartbeat, "s");
                    } else if (mPostAborted) {
                        // There's no point in throwing here; this can happen in two cases
                        // 1) An alarm, which indicates minutes without activity; no sense
                        //    backing off
                        // 2) ExchangeService abort, due to sync of mailbox.  Again, we want to
                        //    keep on trying to ping
                        userLog("Ping aborted; retry");
                    } else if (pingLength < 2000) {
                        userLog("Abort or NAT type return < 2 seconds; throwing IOException");
                        throw e;
                    } else {
                        userLog("NAT type IOException");
                    }
                } else if (hasMessage && message.contains("roken pipe")) {
                    // The "broken pipe" error (uppercase or lowercase "b") seems to be an
                    // internal error, so let's not throw an exception (which leads to delays)
                    // but rather simply run through the loop again
                } else {
                    throw e;
                }
            }
        } else if (forcePing) {
            // In this case, there aren't any boxes that are pingable, but there are boxes
            // waiting (for IOExceptions)
            userLog("pingLoop waiting 60s for any pingable boxes");
            sleep(60 * DateUtils.SECOND_IN_MILLIS, true);
        } else if (pushCount > 0) {
            // If we want to Ping, but can't just yet, wait a little bit
            // TODO Change sleep to wait and use notify from ExchangeService when a sync ends
            sleep(2 * DateUtils.SECOND_IN_MILLIS, false);
            pingWaitCount++;
            //userLog("pingLoop waited 2s for: ", (pushCount - canPushCount), " box(es)");
        } else if (uninitCount > 0) {
            // In this case, we're doing an initial sync of at least one mailbox.  Since this
            // is typically a one-time case, I'm ok with trying again every 10 seconds until
            // we're in one of the other possible states.
            userLog("pingLoop waiting for initial sync of ", uninitCount, " box(es)");
            sleep(10 * DateUtils.SECOND_IN_MILLIS, true);
        } else if (inboxId == -1) {
            // In this case, we're still syncing mailboxes, so sleep for only a short time
            sleep(45 * DateUtils.SECOND_IN_MILLIS, true);
        } else {
            // We've got nothing to do, so we'll check again in 20 minutes at which time
            // we'll update the folder list, check for policy changes and/or remote wipe, etc.
            // Let the device sleep in the meantime...
            userLog(ACCOUNT_MAILBOX_SLEEP_TEXT);
            sleep(ACCOUNT_MAILBOX_SLEEP_TIME, true);
        }
    }

    // Save away the current heartbeat
    mPingHeartbeat = pingHeartbeat;
}

From source file:com.vuze.android.remote.fragment.TorrentListFragment.java

private LastUpdatedInfo getLastUpdatedString() {
    FragmentActivity activity = getActivity();
    if (activity == null) {
        return null;
    }/*from w  ww. j a  v a  2  s. c om*/
    long lastUpdated = sessionInfo == null ? 0 : sessionInfo.getLastTorrentListReceivedOn();
    long sinceMS = System.currentTimeMillis() - lastUpdated;
    String since = DateUtils.getRelativeDateTimeString(activity, lastUpdated, DateUtils.SECOND_IN_MILLIS,
            DateUtils.WEEK_IN_MILLIS, 0).toString();
    String s = activity.getResources().getString(R.string.last_updated, since);

    return new LastUpdatedInfo(sinceMS, s);
}

From source file:com.vuze.android.remote.fragment.FilesFragment.java

@Override
public void onExtraViewVisibilityChange(final View view, int visibility) {
    if (pullRefreshHandler != null) {
        pullRefreshHandler.removeCallbacksAndMessages(null);
        pullRefreshHandler = null;/*from   ww w .j  a  v a2 s.co m*/
    }
    if (visibility != View.VISIBLE) {
        return;
    }

    pullRefreshHandler = new Handler(Looper.getMainLooper());
    pullRefreshHandler.postDelayed(new Runnable() {
        @Override
        public void run() {
            FragmentActivity activity = getActivity();
            if (activity == null) {
                return;
            }
            long sinceMS = System.currentTimeMillis() - lastUpdated;
            String since = DateUtils.getRelativeDateTimeString(activity, lastUpdated,
                    DateUtils.SECOND_IN_MILLIS, DateUtils.WEEK_IN_MILLIS, 0).toString();
            String s = activity.getResources().getString(R.string.last_updated, since);

            TextView tvSwipeText = (TextView) view.findViewById(R.id.swipe_text);
            tvSwipeText.setText(s);

            if (pullRefreshHandler != null) {
                pullRefreshHandler.postDelayed(this,
                        sinceMS < DateUtils.MINUTE_IN_MILLIS ? DateUtils.SECOND_IN_MILLIS
                                : sinceMS < DateUtils.HOUR_IN_MILLIS ? DateUtils.MINUTE_IN_MILLIS
                                        : DateUtils.HOUR_IN_MILLIS);
            }
        }
    }, 0);
}

From source file:com.androzic.MapFragment.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.action_add_waypoint:
        double[] loc = application.getMapCenter();
        Waypoint waypoint = new Waypoint("", "", loc[0], loc[1]);
        waypoint.date = Calendar.getInstance().getTime();
        int wpt = application.addWaypoint(waypoint);
        waypoint.name = "WPT" + wpt;
        application.saveDefaultWaypoints();
        refreshMap();/*from  w w w  . ja v  a  2 s  .c  om*/
        return true;
    case R.id.action_follow:
        setFollowing(!following);
        return true;
    case R.id.action_next_nav_point:
        application.navigationService.nextRouteWaypoint();
        return true;
    case R.id.action_prev_nav_point:
        application.navigationService.prevRouteWaypoint();
        return true;
    case R.id.action_stop_navigation:
        application.stopNavigation();
        return true;
    case R.id.action_search:
        getActivity().onSearchRequested();
        return true;
    case R.id.action_locate: {
        final Location l = application.getLastKnownSystemLocation();
        final long now = System.currentTimeMillis();
        final long fixed = l != null ? l.getTime() : 0L;
        if ((now - fixed) < 1000 * 60 * 60 * 12) // we do not take into account locations older then 12 hours
        {
            wait(new Waitable() {
                @Override
                public void waitFor() {
                    if (application.ensureVisible(l.getLatitude(), l.getLongitude()))
                        mapChanged();
                    else
                        conditionsChanged();
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(application,
                                    DateUtils.getRelativeTimeSpanString(fixed, now, DateUtils.SECOND_IN_MILLIS),
                                    Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            });
        } else {
            Toast.makeText(application, getString(R.string.msg_nolastknownlocation), Toast.LENGTH_LONG).show();
        }
        return true;
    }
    case R.id.action_locating:
        application.enableLocating(!application.isLocating());
        return true;
    case R.id.action_tracking:
        application.enableTracking(!application.isTracking());
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

From source file:com.androzic.vnspeech.MapFragment.java

private void moveToWhereAmI() {
    final Location l = application.getLastKnownSystemLocation();
    final long now = System.currentTimeMillis();
    final long fixed = l != null ? l.getTime() : 0L;
    if ((now - fixed) < 1000 * 60 * 60 * 12) // we do not take into account locations older then 12 hours
    {/*  w w  w.j  a v  a 2 s.  co m*/
        wait(new Waitable() {
            @Override
            public void waitFor() {
                application.ensureVisible(l.getLatitude(), l.getLongitude());
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(application,
                                DateUtils.getRelativeTimeSpanString(fixed, now, DateUtils.SECOND_IN_MILLIS),
                                Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    } else {
        Toast.makeText(application, getString(R.string.msg_nolastknownlocation), Toast.LENGTH_LONG).show();
    }
}

From source file:com.ludoscity.findmybikes.activities.NearbyActivity.java

private Runnable createUpdateRefreshRunnableCode() {
    return new Runnable() {

        private boolean mPagerReady = false;
        private NumberFormat mNumberFormat = NumberFormat.getInstance();

        /*private final long startTime = System.currentTimeMillis();
        private long lastRunTime;/*from   w w w  .jav  a2s.  c om*/
        private long lastUpdateTime = System.currentTimeMillis();   //Update should be run automatically ?
        */
        @Override
        public void run() {

            long now = System.currentTimeMillis();

            if (mRedrawMarkersTask == null && getListPagerAdapter().isViewPagerReady()
                    && (!mPagerReady || mRefreshTabs)) {
                //When restoring, we don't need to setup everything from here
                if (!mStationMapFragment.isRestoring()) { //TODO figure out how to properly determine restoration
                    setupTabPages();
                    if (isLookingForBike()) //onPageSelected is called by framework on B tab restoration
                        onPageSelected(StationListPagerAdapter.BIKE_STATIONS);
                }

                mPagerReady = true;
            }

            //Update not already in progress
            if (mPagerReady && mDownloadWebTask == null && mRedrawMarkersTask == null
                    && mFindNetworkTask == null) {

                long runnableLastRefreshTimestamp = DBHelper.getLastUpdateTimestamp(getApplicationContext());

                long difference = now - runnableLastRefreshTimestamp;

                StringBuilder pastStringBuilder = new StringBuilder();
                StringBuilder futureStringBuilder = new StringBuilder();

                if (DBHelper.isBikeNetworkIdAvailable(getApplicationContext())) {
                    //First taking care of past time...
                    if (difference < DateUtils.MINUTE_IN_MILLIS)
                        pastStringBuilder.append(getString(R.string.moments));
                    else
                        pastStringBuilder.append(getString(R.string.il_y_a))
                                .append(mNumberFormat.format(difference / DateUtils.MINUTE_IN_MILLIS))
                                .append(" ").append(getString(R.string.min_abbreviated));
                }
                //mStatusTextView.setText(Long.toString(difference / DateUtils.MINUTE_IN_MILLIS) +" "+ getString(R.string.minsAgo) + " " + getString(R.string.fromCitibik_es) );

                //long differenceInMinutes = difference / DateUtils.MINUTE_IN_MILLIS;

                //from : http://stackoverflow.com/questions/25355611/how-to-get-time-difference-between-two-dates-in-android-app
                //long differenceInSeconds = difference / DateUtils.SECOND_IN_MILLIS;
                // formatted will be HH:MM:SS or MM:SS
                //String formatted = DateUtils.formatElapsedTime(differenceInSeconds);

                //... then about next update
                if (Utils.Connectivity.isConnected(getApplicationContext())) {

                    getListPagerAdapter().setRefreshEnableAll(true);
                    if (!mSearchFAB.isEnabled()) {
                        mSearchFAB.show();
                        mSearchFAB.setEnabled(true);

                        if (mOnboardingSnackBar != null && mOnboardingSnackBar.getView().getTag() != null)
                            if (!checkOnboarding(eONBOARDING_LEVEL.ONBOARDING_LEVEL_FULL,
                                    eONBOARDING_STEP.ONBOARDING_STEP_SEARCH_SHOWCASE))
                                checkOnboarding(eONBOARDING_LEVEL.ONBOARDING_LEVEL_LIGHT,
                                        eONBOARDING_STEP.ONBOARDING_STEP_MAIN_CHOICE_HINT);

                        mStatusBar.setBackgroundColor(
                                ContextCompat.getColor(NearbyActivity.this, R.color.theme_primary_dark));
                    }

                    if (DBHelper.isBikeNetworkIdAvailable(getApplicationContext())) {

                        if (!DBHelper.getAutoUpdate(getApplicationContext())) {
                            futureStringBuilder.append(getString(R.string.pull_to_refresh));

                        } else {

                            //Should come from something keeping tabs on time, maybe this runnable itself
                            long wishedUpdateTime = runnableLastRefreshTimestamp
                                    + NearbyActivity.this.getApplicationContext().getResources()
                                            .getInteger(R.integer.update_auto_interval_minute) * 1000 * 60; //comes from Prefs
                            //Debug
                            //long wishedUpdateTime = runnableLastRefreshTimestamp + 15 * 1000;  //comes from Prefs

                            if (now >= wishedUpdateTime) {

                                mDownloadWebTask = new DownloadWebTask();
                                mDownloadWebTask.execute();

                            } else {

                                futureStringBuilder.append(getString(R.string.nextUpdate)).append(" ");
                                long differenceSecond = (wishedUpdateTime - now) / DateUtils.SECOND_IN_MILLIS;

                                // formatted will be HH:MM:SS or MM:SS
                                futureStringBuilder.append(DateUtils.formatElapsedTime(differenceSecond));
                            }
                        }

                        if (difference >= NearbyActivity.this.getApplicationContext().getResources()
                                .getInteger(R.integer.outdated_data_time_minute) * 60 * 1000
                                && !mDataOutdated) {

                            mDataOutdated = true;

                            if (mDownloadWebTask == null) { //Auto update didn't kick in. If task cancels it will execute same code then

                                mRefreshMarkers = true;
                                refreshMap();
                                mStatusBar.setBackgroundColor(
                                        ContextCompat.getColor(NearbyActivity.this, R.color.theme_accent));
                                getListPagerAdapter().setOutdatedDataAll(true);
                            }

                        }
                    }
                } else {
                    futureStringBuilder.append(getString(R.string.no_connectivity));

                    getListPagerAdapter().setRefreshEnableAll(false);
                    mSearchFAB.setEnabled(false);
                    mSearchFAB.hide();

                    if (getListPagerAdapter()
                            .getHighlightedStationForPage(StationListPagerAdapter.BIKE_STATIONS) != null
                            && mOnboardingSnackBar != null && mOnboardingSnackBar.getView().getTag() != null
                            && !((String) mOnboardingSnackBar.getView().getTag())
                                    .equalsIgnoreCase("NO_CONNECTIVITY"))
                        checkOnboarding(eONBOARDING_LEVEL.ONBOARDING_LEVEL_LIGHT,
                                eONBOARDING_STEP.ONBOARDING_STEP_MAIN_CHOICE_HINT);

                    mStatusBar.setBackgroundColor(
                            ContextCompat.getColor(NearbyActivity.this, R.color.theme_accent));
                }

                if (mDownloadWebTask == null)
                    mStatusTextView.setText(String.format(getString(R.string.status_string),
                            pastStringBuilder.toString(), futureStringBuilder.toString()));

                //pulling the trigger on auto select
                if (mDownloadWebTask == null && mRedrawMarkersTask == null && mFindNetworkTask == null
                        && !mClosestBikeAutoSelected
                        && getListPagerAdapter()
                                .isRecyclerViewReadyForItemSelection(StationListPagerAdapter.BIKE_STATIONS)
                        && mStationMapFragment.isMapReady()) {

                    //Requesting raw string with availability
                    String rawClosest = getListPagerAdapter().retrieveClosestRawIdAndAvailability(true);
                    getListPagerAdapter().highlightStationforId(true,
                            Utils.extractClosestAvailableStationIdFromProcessedString(rawClosest));

                    getListPagerAdapter().smoothScrollHighlightedInViewForPage(
                            StationListPagerAdapter.BIKE_STATIONS, isAppBarExpanded());
                    final StationItem closestBikeStation = getListPagerAdapter()
                            .getHighlightedStationForPage(StationListPagerAdapter.BIKE_STATIONS);
                    mStationMapFragment.setPinOnStation(true, closestBikeStation.getId());
                    getListPagerAdapter().notifyStationAUpdate(closestBikeStation.getLocation(),
                            mCurrentUserLatLng);
                    hideSetupShowTripDetailsWidget();
                    getListPagerAdapter().setupBTabStationARecap(closestBikeStation, mDataOutdated);

                    if (isLookingForBike()) {
                        if (mTripDetailsWidget.getVisibility() == View.INVISIBLE) {
                            mDirectionsLocToAFab.show();
                        }

                        mAutoSelectBikeFab.hide();
                        mStationMapFragment.setMapPaddingRight(0);

                        if (mStationMapFragment.getMarkerBVisibleLatLng() == null) {
                            mStationListViewPager.setCurrentItem(StationListPagerAdapter.DOCK_STATIONS, true);

                            mFavoritesSheetFab.showFab();

                            //if onboarding not happening...
                            if (!checkOnboarding(eONBOARDING_LEVEL.ONBOARDING_LEVEL_FULL,
                                    eONBOARDING_STEP.ONBOARDING_STEP_SEARCH_SHOWCASE)
                                    && !checkOnboarding(eONBOARDING_LEVEL.ONBOARDING_LEVEL_LIGHT,
                                            eONBOARDING_STEP.ONBOARDING_STEP_MAIN_CHOICE_HINT)) {
                                //...open favorites sheet
                                final Handler handler = new Handler();
                                handler.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {

                                        if (!mFavoritePickerFAB.isShowRunning()) {
                                            mFavoritesSheetFab.showSheet();
                                        } else
                                            handler.postDelayed(this, 10);
                                    }
                                }, 50);

                            }
                        } else {
                            animateCameraToShowUserAndStation(closestBikeStation);
                        }
                    }

                    //Bug on older API levels. Dismissing by hand fixes it.
                    // First biggest bug happened here. Putting defensive code
                    //TODO: investigate how state is maintained, Snackbar is destroyed by framework on screen orientation change
                    //TODO: Refactor this spgathetti is **TOP** priosity
                    //and probably long background state.
                    if (mFindBikesSnackbar != null) {

                        mFindBikesSnackbar.dismiss();
                    }

                    Handler handler = new Handler();

                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {

                            if (mDataOutdated) {

                                mFindBikesSnackbar = Utils.Snackbar.makeStyled(mCoordinatorLayout,
                                        R.string.auto_bike_select_outdated, Snackbar.LENGTH_LONG,
                                        ContextCompat.getColor(NearbyActivity.this, R.color.theme_accent));

                            } else if (!closestBikeStation.isLocked()
                                    && closestBikeStation.getFree_bikes() > DBHelper
                                            .getCriticalAvailabilityMax(NearbyActivity.this)) {

                                mFindBikesSnackbar = Utils.Snackbar.makeStyled(mCoordinatorLayout,
                                        R.string.auto_bike_select_found, Snackbar.LENGTH_LONG,
                                        ContextCompat.getColor(NearbyActivity.this, R.color.snackbar_green));
                            } else {

                                mFindBikesSnackbar = Utils.Snackbar.makeStyled(mCoordinatorLayout,
                                        R.string.auto_bike_select_none, Snackbar.LENGTH_LONG,
                                        ContextCompat.getColor(NearbyActivity.this, R.color.theme_accent));
                            }

                            if (mOnboardingSnackBar == null)
                                mFindBikesSnackbar.show();
                        }
                    }, 500);

                    mClosestBikeAutoSelected = true;
                    //launch twitter task if not already running, pass it the raw String
                    if (Utils.Connectivity.isConnected(getApplicationContext()) && //data network available
                    mUpdateTwitterTask == null && //not already tweeting
                    rawClosest.length() > 32 + StationRecyclerViewAdapter.AOK_AVAILABILITY_POSTFIX.length() && //validate format - 32 is station ID length
                    (rawClosest.contains(StationRecyclerViewAdapter.AOK_AVAILABILITY_POSTFIX)
                            || rawClosest.contains(StationRecyclerViewAdapter.BAD_AVAILABILITY_POSTFIX)) && //validate content
                    !mDataOutdated) {

                        mUpdateTwitterTask = new UpdateTwitterStatusTask();
                        mUpdateTwitterTask.execute(rawClosest);

                    }
                }

                //Checking if station is closest bike
                if (mDownloadWebTask == null && mRedrawMarkersTask == null && mFindNetworkTask == null
                        && mStationMapFragment.isMapReady()) {

                    if (!isStationAClosestBike()) {
                        if (mStationMapFragment.getMarkerBVisibleLatLng() == null) {
                            mClosestBikeAutoSelected = false;
                        } else if (isLookingForBike() && !mClosestBikeAutoSelected) {
                            mStationMapFragment.setMapPaddingRight(
                                    (int) getResources().getDimension(R.dimen.map_fab_padding));
                            mAutoSelectBikeFab.show();
                            animateCameraToShowUserAndStation(getListPagerAdapter()
                                    .getHighlightedStationForPage(StationListPagerAdapter.BIKE_STATIONS));
                        }
                    }
                }
            }

            //UI will be refreshed every second
            int nextTimeMillis = 1000;

            if (!mPagerReady) //Except on init
                nextTimeMillis = 100;

            mUpdateRefreshHandler.postDelayed(mUpdateRefreshRunnableCode, nextTimeMillis);
        }
    };
}