Example usage for android.text.format DateUtils formatElapsedTime

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

Introduction

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

Prototype

public static String formatElapsedTime(long elapsedSeconds) 

Source Link

Document

Formats an elapsed time in the form "MM:SS" or "H:MM:SS" for display on the call-in-progress screen.

Usage

From source file:com.scooter1556.sms.android.activity.FullScreenPlayerActivity.java

private void updateDuration(MediaMetadataCompat metadata) {
    if (metadata == null) {
        return;// w w  w . j a  v  a2  s  .co m
    }

    int duration = (int) metadata.getLong(MediaMetadataCompat.METADATA_KEY_DURATION);
    seekbar.setMax(duration);
    end.setText(DateUtils.formatElapsedTime(duration / 1000));
}

From source file:com.murati.oszk.audiobook.ui.FullScreenPlayerActivity.java

private void updateProgress() {
    if (mLastPlaybackState == null) {
        return;//from w  w w.j a  v  a  2 s. c  o  m
    }

    //TODO: fix current position
    long currentPosition = mLastPlaybackState.getPosition();
    if (mLastPlaybackState.getState() == PlaybackStateCompat.STATE_PLAYING) {
        // Calculate the elapsed time between the last position update and now and unless
        // paused, we can assume (delta * speed) + current position is approximately the
        // latest position. This ensure that we do not repeatedly call the getPlaybackState()
        // on MediaControllerCompat.
        long timeDelta = SystemClock.elapsedRealtime() - mLastPlaybackState.getLastPositionUpdateTime();
        currentPosition += (long) timeDelta * mLastPlaybackState.getPlaybackSpeed();
    }
    mSeekbar.setProgress((int) currentPosition);

    try {
        if (mSeekbar.getMax() < currentPosition) {
            mSeekbar.setMax((int) currentPosition + 30000);
            mEnd.setText(DateUtils.formatElapsedTime(mSeekbar.getMax() / 1000));
        }
    } catch (Exception ex) {
        //TODO: fix length detection
    }
}

From source file:org.kontalk.ui.AudioDialog.java

private void animate(final CircularSeekBar progressBar, final AnimatorListener listener, final float progress,
        final float maxProgress, final long duration) {
    mProgressBarAnimator = ObjectAnimator.ofFloat(progressBar, "progress", maxProgress);
    mProgressBarAnimator.setInterpolator(new LinearInterpolator());
    mProgressBarAnimator.setDuration(duration);

    mProgressBarAnimator.addListener(new AnimatorListener() {

        @Override//w w  w. j  a  va 2 s.c o m
        public void onAnimationCancel(final Animator animation) {
        }

        @Override
        public void onAnimationEnd(final Animator animation) {
            if (mStatus == STATUS_RECORDING)
                stopRecord();
        }

        @Override
        public void onAnimationRepeat(final Animator animation) {
        }

        @Override
        public void onAnimationStart(final Animator animation) {
            progressBar.setOnTouchListener(new OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if (mStatus == STATUS_RECORDING) {
                        return true;
                    }
                    if (event.getAction() == android.view.MotionEvent.ACTION_DOWN
                            && (mStatus == STATUS_PLAYING || mStatus == STATUS_PAUSED)) {
                        progressBar.setPointerAlpha(135);
                        progressBar.setPointerAlphaOnTouch(100);
                        mCheckSeek = mStatus;
                        pauseAudio();
                    } else if (event.getAction() == android.view.MotionEvent.ACTION_UP) {
                        progressBar.setPointerAlpha(0);
                        progressBar.setPointerAlphaOnTouch(0);
                        mData.getPlayer().seekTo(mPlayerSeekTo);
                        if (mCheckSeek == STATUS_PLAYING)
                            resumeAudio();
                    } else if (event.getAction() == android.view.MotionEvent.ACTION_MOVE
                            && (mStatus == STATUS_PLAYING || mStatus == STATUS_PAUSED)) {
                        mPlayerSeekTo = (int) (progressBar.getProgress() / mTimeCircle);
                        mTimeTxt.setText(DateUtils.formatElapsedTime(mPlayerSeekTo / 1000));
                    }
                    return false;
                }
            });
        }
    });
    if (listener != null) {
        mProgressBarAnimator.addListener(listener);
    }
    mProgressBarAnimator.addUpdateListener(new AnimatorUpdateListener() {
        public void onAnimationUpdate(final ValueAnimator animation) {
            progressBar.setProgress((Float) animation.getAnimatedValue());
            long time = animation.getCurrentPlayTime();
            mTimeTxt.setText(DateUtils.formatElapsedTime(time / 1000));
        }
    });
    progressBar.setProgress(progress);
    mProgressBarAnimator.start();
    if (progress > 0) {
        mProgressBarAnimator.setCurrentPlayTime((long) (progress * MAX_AUDIO_DURATION / 100));
    }
}

From source file:com.todoroo.astrid.notes.EditNoteActivity.java

@Override
public void timerStopped(Task t) {
    String elapsedTime = DateUtils.formatElapsedTime(t.getElapsedSeconds());
    addComment(String.format("%s %s\n%s %s", //$NON-NLS-1$
            getContext().getString(R.string.TEA_timer_comment_stopped),
            DateUtilities.getTimeString(getContext(), newDate()),
            getContext().getString(R.string.TEA_timer_comment_spent), elapsedTime),
            UserActivity.ACTION_TASK_COMMENT, t.getUuid(), false);
}

From source file:im.vector.adapters.VectorMessagesAdapter.java

/**
 * Format a second time range./*  ww  w  . j a v a  2  s.  co  m*/
 * @param seconds the seconds time
 * @return the formatted string
 */
private static String vectorRemainingTimeToString(Context context, int seconds) {
    if (seconds < 0) {
        return "";
    } else if (seconds <= 1) {
        return "< 1s";
    } else if (seconds < 60) {
        return context.getString(R.string.attachment_remaining_time_seconds, seconds);
    } else if (seconds < 3600) {
        return context.getString(R.string.attachment_remaining_time_minutes, seconds / 60, seconds % 60);
    } else {
        return DateUtils.formatElapsedTime(seconds);
    }
}

From source file:com.android.incallui.CallCardFragment.java

@Override
public void setPrimaryCallElapsedTime(boolean show, long duration) {
    if (show) {/*from  w  w  w  .j  ava 2 s  .co  m*/
        if (mElapsedTime.getVisibility() != View.VISIBLE) {
            AnimUtils.fadeIn(mElapsedTime, AnimUtils.DEFAULT_DURATION);
        }
        String callTimeElapsed = DateUtils.formatElapsedTime(duration / 1000);
        mElapsedTime.setText(callTimeElapsed);

        String durationDescription = InCallDateUtils.formatDuration(getView().getContext(), duration);
        mElapsedTime
                .setContentDescription(!TextUtils.isEmpty(durationDescription) ? durationDescription : null);
    } else {
        // hide() animation has no effect if it is already hidden.
        AnimUtils.fadeOut(mElapsedTime, AnimUtils.DEFAULT_DURATION);
    }
}

From source file:im.neon.adapters.VectorMessagesAdapter.java

/**
 * Format a second time range./*  w w  w  . j  av  a 2 s . com*/
 * @param seconds the seconds time
 * @return the formatted string
 */
private static String vectorRemainingTimeToString(Context context, int seconds) {
    if (seconds < 0) {
        return "";
    } else if (seconds <= 1) {
        return "< 1s";
    } else if (seconds < 60) {
        return context.getString(R.string.attachment_remaining_time_seconds, seconds);
    } else if (seconds < 3600) {
        return context.getString(R.string.attachment_remaining_time_minutes, (seconds / 60), (seconds % 60));
    } else {
        return DateUtils.formatElapsedTime(seconds);
    }
}

From source file:org.proninyaroslav.libretorrent.services.TorrentTaskService.java

private NotificationCompat.InboxStyle makeDetailNotifyInboxStyle() {
    NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();

    String titleTemplate = getString(R.string.torrent_count_notify_template);

    int downloadingCount = 0;

    for (TorrentDownload task : torrentTasks.values()) {
        if (task == null) {
            continue;
        }/*from   www  .  j  av a  2s  .  com*/

        String template;
        TorrentStateCode code = task.getStateCode();

        if (code == TorrentStateCode.DOWNLOADING) {
            ++downloadingCount;
            template = getString(R.string.downloading_torrent_notify_template);
            inboxStyle.addLine(String.format(template, task.getProgress(),
                    (task.getETA() == -1) ? Utils.INFINITY_SYMBOL : DateUtils.formatElapsedTime(task.getETA()),
                    Formatter.formatFileSize(this, task.getDownloadSpeed()), task.getTorrent().getName()));

        } else if (code == TorrentStateCode.SEEDING) {
            template = getString(R.string.seeding_torrent_notify_template);
            inboxStyle.addLine(String.format(template, getString(R.string.torrent_status_seeding),
                    Formatter.formatFileSize(this, task.getUploadSpeed()), task.getTorrent().getName()));
        } else {
            String stateString = "";

            switch (task.getStateCode()) {
            case PAUSED:
                stateString = getString(R.string.torrent_status_paused);
                break;
            case STOPPED:
                stateString = getString(R.string.torrent_status_stopped);
                break;
            case CHECKING:
                stateString = getString(R.string.torrent_status_checking);
                break;
            }

            template = getString(R.string.other_torrent_notify_template);
            inboxStyle.addLine(String.format(template, stateString, task.getTorrent().getName()));
        }
    }

    inboxStyle.setBigContentTitle(String.format(titleTemplate, downloadingCount, torrentTasks.size()));

    inboxStyle.setSummaryText(
            (isNetworkOnline ? getString(R.string.network_online) : getString(R.string.network_offline)));

    return inboxStyle;
}

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;// w w  w. j a  v  a2  s. com
        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);
        }
    };
}