Example usage for android.text.format DateUtils MINUTE_IN_MILLIS

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

Introduction

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

Prototype

long MINUTE_IN_MILLIS

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

Click Source Link

Usage

From source file:com.numenta.core.service.DataSyncService.java

/**
 * This method is execute periodically and update {@link com.numenta.core.data.CoreDatabase}
 * with new data from the//  ww w. j  a  va2 s .  com
 * server.
 */
protected void synchronizeWithServer() throws IOException {
    Log.i(TAG, "synchronizeWithServer");

    if (_synchronizingWithServer) {
        return;
    }
    if (!NetUtils.isConnected()) {
        // Not connected, skip until we connect
        return;
    }

    final CoreDatabase database = HTMApplication.getDatabase();
    if (database == null) {
        return;
    }
    synchronized (this) {
        if (_synchronizingWithServer) {
            return;
        }
        _synchronizingWithServer = true;
    }
    String result = null;
    try {
        // Guard against blocking the UI Thread
        if (Looper.myLooper() == Looper.getMainLooper()) {
            throw new IllegalStateException("You should not access the database from the UI thread");
        }

        fireRefreshStateEvent(_synchronizingWithServer);

        final Context context = _service.getApplicationContext();
        final long now = System.currentTimeMillis();

        // Check if enough time has passed since we checked for new data
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        final long lastConnectedTime = prefs.getLong(PREF_LAST_CONNECTED_TIME, 0);
        if (now - lastConnectedTime < DataUtils.METRIC_DATA_INTERVAL) {
            return;
        }

        // Calculate hours since last update. This information will be
        // passed to the user together with error message
        final CharSequence hoursSinceData = DateUtils.getRelativeTimeSpanString(database.getLastTimestamp(),
                now, DateUtils.MINUTE_IN_MILLIS);

        Future<?> pendingIO = null;
        try {
            // Try to connect to server
            if (_htmClient == null) {
                _htmClient = _service.connectToServer();
            }
            if (_htmClient == null) {
                throw new IOException("Unable to connect to server");
            }

            // Update last connected time
            SharedPreferences.Editor editor = prefs.edit();
            editor.putLong(PREF_LAST_CONNECTED_TIME, now);
            editor.apply();

            // Start by downloading all the metrics available from backend
            // in a background IO thread
            pendingIO = _service.getIOThreadPool().submit(new Callable<Void>() {
                @Override
                public Void call() throws Exception {

                    try {
                        // First load metrics
                        loadAllMetrics();

                        // Load all annotations after metrics
                        loadAllAnnotations();

                        // Load all data after annotations
                        loadAllData();

                        // Synchronize notifications after data
                        synchronizeNotifications();

                        // Synchronize application data last
                        HTMApplication.getInstance().loadApplicationData(_htmClient);

                    } catch (android.database.sqlite.SQLiteFullException e) {
                        // Try to delete old records to make room if possible
                        Log.e(TAG, "Failed to save data into database", e);
                        database.deleteOldRecords();
                    }
                    return null;
                }
            });
            // Wait for metric data to finish
            pendingIO.get();
        } catch (InterruptedException e) {
            // Cancel pending tasks
            if (!pendingIO.isDone()) {
                pendingIO.cancel(true);
            }
            Log.w(TAG, "Interrupted while loading data");
        } catch (ExecutionException e) {
            // Cancel pending tasks
            if (!pendingIO.isDone()) {
                pendingIO.cancel(true);
            }
            Throwable original = e.getCause();
            if (original instanceof AuthenticationException) {
                _service.fireAuthenticationFailedEvent();
            } else if (original instanceof ObjectNotFoundException) {
                Log.e(TAG, "Error loading data", e);
                result = context.getString(R.string.refresh_update_error, hoursSinceData);
            } else if (original instanceof IOException) {
                Log.e(TAG, "Unable to connect", e);
                result = context.getString(R.string.refresh_server_unreachable, hoursSinceData);
            } else {
                Log.e(TAG, "Error loading data", e);
                result = context.getString(R.string.refresh_update_error, hoursSinceData);
            }
        } catch (AuthenticationException e) {
            _service.fireAuthenticationFailedEvent();
        } catch (HTMException e) {
            Log.e(TAG, "Error loading data", e);
            result = context.getString(R.string.refresh_update_error, hoursSinceData);
        } catch (IOException e) {
            Log.e(TAG, "Unable to connect", e);
            result = context.getString(R.string.refresh_server_unreachable, hoursSinceData);
        }
    } finally {
        _synchronizingWithServer = false;
        fireRefreshStateEvent(_synchronizingWithServer, result);
    }
}

From source file:com.lambdasoup.quickfit.alarm.AlarmService.java

/**
 * sets the alarm with the alarm manager for the next occurrence of any scheduled event according
 * to the current db state//from  www. jav  a 2s.c  om
 */
@WorkerThread
private void setNextAlarm() {
    try (SQLiteDatabase db = dbHelper.getReadableDatabase();
            Cursor cursor = db.rawQuery(QUERY_SELECT_MIN_NEXT_ALERT, null)) {
        // if cursor is empty, no schedules exist, no alarms to set
        if (cursor.moveToFirst()) {
            long nextAlarmMillis = cursor
                    .getLong(cursor.getColumnIndexOrThrow(ScheduleEntry.COL_NEXT_ALARM_MILLIS));

            AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
            PendingIntent alarmReceiverIntent = PendingIntent.getBroadcast(this, PENDING_INTENT_ALARM_RECEIVER,
                    AlarmReceiver.getIntentOnAlarm(this), PendingIntent.FLAG_UPDATE_CURRENT);
            alarmManager.cancel(alarmReceiverIntent);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, nextAlarmMillis,
                        alarmReceiverIntent);
            } else {
                alarmManager.setWindow(AlarmManager.RTC_WAKEUP, nextAlarmMillis, DateUtils.MINUTE_IN_MILLIS,
                        alarmReceiverIntent);
            }
        }
    }
}

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

/** Helper method to set the contents and visibility of each field */
public synchronized void bindView(View view, NoteOrUpdate item) {
    // name/*  www . ja v  a2 s . com*/
    final TextView nameView = (TextView) view.findViewById(R.id.title);
    {
        nameView.setText(item.title);
        Linkify.addLinks(nameView, Linkify.ALL);
    }

    // date
    final TextView date = (TextView) view.findViewById(R.id.date);
    {
        CharSequence dateString = DateUtils.getRelativeTimeSpanString(item.createdAt, DateUtilities.now(),
                DateUtils.MINUTE_IN_MILLIS, DateUtils.FORMAT_ABBREV_RELATIVE);
        date.setText(dateString);
    }

    // picture
    final ImageView commentPictureView = (ImageView) view.findViewById(R.id.comment_picture);
    setupImagePopupForCommentView(view, commentPictureView, item.commentBitmap, fragment);
}

From source file:com.krayzk9s.imgurholo.tools.ImageUtils.java

public static void updateInfoFont(JSONParcelable imageData, TextView infoText) {
    try {//from w  ww.  j  a  v a2  s.co m
        String albumText = "";
        if (imageData.getJSONObject().has("is_album") && imageData.getJSONObject().getBoolean("is_album"))
            albumText = "[album] ";
        if (!imageData.getJSONObject().getString("section").equals("null"))
            albumText += "/r/" + imageData.getJSONObject().getString("section") + " " + Html.fromHtml("&#8226;")
                    + " ";
        Calendar calendar = Calendar.getInstance();
        long now = calendar.getTimeInMillis();
        infoText.setText(albumText
                + DateUtils.getRelativeTimeSpanString(imageData.getJSONObject().getLong("datetime") * 1000, now,
                        DateUtils.MINUTE_IN_MILLIS)
                + " " + Html.fromHtml("&#8226;") + " ");
    } catch (JSONException e) {
        Log.e("Error!", e.toString());
    }
}

From source file:com.battlelancer.seriesguide.ui.ActivityFragment.java

private void schedulePeriodicDataRefresh(boolean enableRefresh) {
    if (mHandler == null) {
        mHandler = new Handler();
    }// www. java  2 s .c om
    mHandler.removeCallbacks(mDataRefreshRunnable);
    if (enableRefresh) {
        mHandler.postDelayed(mDataRefreshRunnable, 5 * DateUtils.MINUTE_IN_MILLIS);
    }
}

From source file:com.stasbar.knowyourself.timer.CountingTimerView.java

/**
 * Update the time to display. Separates that time into the hours, minutes, seconds and
 * hundredths. If update is true, the view is invalidated so that it will draw again.
 *
 * @param time new time to display - in milliseconds
 * @param showHundredths flag to show hundredths resolution
 *//*  w w  w .j av a  2  s.c o m*/
// TODO:showHundredths S/B attribute or setter - i.e. unchanging over object life
public void setTime(long time, boolean showHundredths) {
    final int oldLength = getDigitsLength();
    boolean neg = false, showNeg = false;
    if (time < 0) {
        time = -time;
        neg = showNeg = true;
    }

    int hours = (int) (time / DateUtils.HOUR_IN_MILLIS);
    int remainder = (int) (time % DateUtils.HOUR_IN_MILLIS);

    int minutes = (int) (remainder / DateUtils.MINUTE_IN_MILLIS);
    remainder = (int) (remainder % DateUtils.MINUTE_IN_MILLIS);

    int seconds = (int) (remainder / DateUtils.SECOND_IN_MILLIS);
    remainder = (int) (remainder % DateUtils.SECOND_IN_MILLIS);

    int hundredths = remainder / 10;

    if (hours > 999) {
        hours = 0;
    }

    // The time can be between 0 and -1 seconds, but the "truncated" equivalent time of hours
    // and minutes and seconds could be zero, so since we do not show fractions of seconds
    // when counting down, do not show the minus sign.
    // TODO:does it matter that we do not look at showHundredths?
    if (hours == 0 && minutes == 0 && seconds == 0) {
        showNeg = false;
    }

    // If not showing hundredths, round up to the next second.
    if (!showHundredths) {
        if (!neg && hundredths != 0) {
            seconds++;
            if (seconds == 60) {
                seconds = 0;
                minutes++;
                if (minutes == 60) {
                    minutes = 0;
                    hours++;
                }
            }
        }
    }

    // Hours may be empty.
    final UiDataModel uiDataModel = UiDataModel.getUiDataModel();
    if (hours > 0) {
        final int hoursLength = hours >= 10 ? 2 : 1;
        mHours = uiDataModel.getFormattedNumber(showNeg, hours, hoursLength);
    } else {
        mHours = null;
    }

    // Minutes are never empty and forced to two digits when hours exist.
    final boolean showNegMinutes = showNeg && hours == 0;
    final int minutesLength = minutes >= 10 || hours > 0 ? 2 : 1;
    mMinutes = uiDataModel.getFormattedNumber(showNegMinutes, minutes, minutesLength);

    // Seconds are always two digits
    mSeconds = uiDataModel.getFormattedNumber(seconds, 2);

    // Hundredths are optional but forced to two digits when displayed.
    if (showHundredths) {
        mHundredths = uiDataModel.getFormattedNumber(hundredths, 2);
    } else {
        mHundredths = null;
    }

    int newLength = getDigitsLength();
    if (oldLength != newLength) {
        if (oldLength > newLength) {
            resetTextSize();
        }
        mRemeasureText = true;
    }

    setContentDescription(getTimeStringForAccessibility(hours, minutes, seconds, showNeg, getResources()));
    postInvalidateOnAnimation();
}

From source file:com.actinarium.nagbox.service.NagboxService.java

private void handleOnAlarmFired() {
    final long now = System.currentTimeMillis();

    Task[] tasksToRemind = NagboxDbOps.getTasksToRemind(mDatabase, now);
    if (tasksToRemind.length == 0) {
        Log.i(TAG, "Alarm fired/check requested, but there was nothing to remind about");
        return;/*  w  w w.j a va2 s. co m*/
    }

    NotificationHelper.fireNotification(this, tasksToRemind);

    // Update the status and the time of the next fire where needed.
    List<Task> tasksToUpdate = new ArrayList<>(tasksToRemind.length);
    for (Task task : tasksToRemind) {
        boolean isModified = false;
        if (task.isSeen()) {
            task.setIsSeen(false);
            isModified = true;
        }

        // Using the loop because the alarm might've fired long ago (e.g. before system reboot),
        // so we need to make sure that nextFireAt is indeed in the future
        while (task.nextFireAt <= now) {
            task.nextFireAt += task.interval * DateUtils.MINUTE_IN_MILLIS;
            isModified = true;
        }

        if (isModified) {
            tasksToUpdate.add(task);
        }
    }

    final int updateSize = tasksToUpdate.size();
    if (updateSize == 0) {
        Log.w(TAG, "Strangely enough, there was nothing to update when alarm fired");
        rescheduleAlarm();
        return;
    }

    // Otherwise update the tasks that need it
    NagboxDbOps.Transaction transaction = NagboxDbOps.startTransaction(mDatabase);
    for (int i = 0; i < updateSize; i++) {
        final Task task = tasksToUpdate.get(i);
        transaction.updateTaskStatus(task);
    }
    boolean isSuccess = transaction.commit();

    if (!isSuccess) {
        Log.e(TAG, "Couldn't update status of the tasks when alarm fired");
    } else {
        // Notify all affected task items
        final ContentResolver contentResolver = getContentResolver();
        for (int i = 0; i < updateSize; i++) {
            contentResolver.notifyChange(TasksTable.getUriForItem(tasksToUpdate.get(i).id), null);
        }
    }

    // Finally, schedule the alarm to fire the next time it's ought to fire
    rescheduleAlarm();
}

From source file:org.site_monitor.activity.MainActivity.java

private void scheduleTimer() {
    if (countDownTimer != null) {
        countDownTimer.cancel();/*from   w ww . j  a  v  a 2 s  .  co m*/
    }
    final long nextAlarmTime = alarmUtil.getNextAlarmTime(this);
    final long nextAlarmInterval = alarmUtil.getCountUntilNextAlarmTime(this);
    if (nextAlarmInterval > 0) {
        timerBannerView.setVisibility(View.VISIBLE);
        countDownTimer = new CountDownTimer(nextAlarmInterval, TimeUtil._1_SEC * 5) {
            public void onTick(long millisUntilFinished) {
                chronometer.setText(DateUtils.getRelativeTimeSpanString(nextAlarmTime));
                chronometer.setText(DateUtils.getRelativeTimeSpanString(nextAlarmTime,
                        System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS));
            }

            public void onFinish() {
                chronometer.setText(R.string.imminent);
            }
        }.start();
    } else {
        timerBannerView.setVisibility(View.GONE);
    }
}

From source file:org.chromium.chrome.browser.ntp.snippets.SnippetArticleViewHolder.java

public void onBindViewHolder(SnippetArticle article) {
    super.onBindViewHolder();

    mArticle = article;// w  ww . j a  v a2 s.  c  o  m
    updateLayout();

    mHeadlineTextView.setText(mArticle.mTitle);

    // DateUtils.getRelativeTimeSpanString(...) calls through to TimeZone.getDefault(). If this
    // has never been called before it loads the current time zone from disk. In most likelihood
    // this will have been called previously and the current time zone will have been cached,
    // but in some cases (eg instrumentation tests) it will cause a strict mode violation.
    StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
    try {
        long time = SystemClock.elapsedRealtime();
        CharSequence relativeTimeSpan = DateUtils.getRelativeTimeSpanString(
                mArticle.mPublishTimestampMilliseconds, System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS);
        RecordHistogram.recordTimesHistogram("Android.StrictMode.SnippetUIBuildTime",
                SystemClock.elapsedRealtime() - time, TimeUnit.MILLISECONDS);

        // We format the publisher here so that having a publisher name in an RTL language
        // doesn't mess up the formatting on an LTR device and vice versa.
        String publisherAttribution = String.format(PUBLISHER_FORMAT_STRING,
                BidiFormatter.getInstance().unicodeWrap(mArticle.mPublisher), relativeTimeSpan);
        mPublisherTextView.setText(publisherAttribution);
    } finally {
        StrictMode.setThreadPolicy(oldPolicy);
    }

    // The favicon of the publisher should match the textview height.
    int widthSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
    int heightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
    mPublisherTextView.measure(widthSpec, heightSpec);
    mPublisherFaviconSizePx = mPublisherTextView.getMeasuredHeight();

    mArticleSnippetTextView.setText(mArticle.mPreviewText);

    // If there's still a pending thumbnail fetch, cancel it.
    cancelImageFetch();

    // If the article has a thumbnail already, reuse it. Otherwise start a fetch.
    // mThumbnailView's visibility is modified in updateLayout().
    if (mThumbnailView.getVisibility() == View.VISIBLE) {
        if (mArticle.getThumbnailBitmap() != null) {
            mThumbnailView.setImageBitmap(mArticle.getThumbnailBitmap());
        } else {
            mThumbnailView.setImageResource(R.drawable.ic_snippet_thumbnail_placeholder);
            mImageCallback = new FetchImageCallback(this, mArticle);
            mNewTabPageManager.getSuggestionsSource().fetchSuggestionImage(mArticle, mImageCallback);
        }
    }

    // Set the favicon of the publisher.
    try {
        fetchFaviconFromLocalCache(new URI(mArticle.mUrl), true);
    } catch (URISyntaxException e) {
        setDefaultFaviconOnView();
    }
}

From source file:com.todoroo.astrid.adapter.UpdateAdapter.java

private void setupUserActivityRow(View view, UserActivity activity, User user) {
    final AsyncImageView pictureView = (AsyncImageView) view.findViewById(R.id.picture);
    {//from  ww w  . jav  a2s .  c  o m
        if (user.containsNonNullValue(USER_PICTURE)) {
            String pictureUrl = user.getPictureUrl(USER_PICTURE, RemoteModel.PICTURE_THUMB);
            pictureView.setUrl(pictureUrl);
        } else {
            pictureView.setUrl(null);
        }
        pictureView.setVisibility(View.VISIBLE);
    }

    final AsyncImageView commentPictureView = (AsyncImageView) view.findViewById(R.id.comment_picture);
    {
        String pictureThumb = activity.getPictureUrl(UserActivity.PICTURE, RemoteModel.PICTURE_MEDIUM);
        String pictureFull = activity.getPictureUrl(UserActivity.PICTURE, RemoteModel.PICTURE_LARGE);
        Bitmap updateBitmap = null;
        if (TextUtils.isEmpty(pictureThumb))
            updateBitmap = activity.getPictureBitmap(UserActivity.PICTURE);
        setupImagePopupForCommentView(view, commentPictureView, pictureThumb, pictureFull, updateBitmap,
                activity.getValue(UserActivity.MESSAGE), fragment, imageCache);
    }

    // name
    final TextView nameView = (TextView) view.findViewById(R.id.title);
    {
        nameView.setText(
                getUpdateComment((AstridActivity) fragment.getActivity(), activity, user, linkColor, fromView));
        nameView.setMovementMethod(new LinkMovementMethod());
        nameView.setTextColor(color);
    }

    // date
    final TextView date = (TextView) view.findViewById(R.id.date);
    {
        CharSequence dateString = DateUtils.getRelativeTimeSpanString(
                activity.getValue(UserActivity.CREATED_AT), DateUtilities.now(), DateUtils.MINUTE_IN_MILLIS,
                DateUtils.FORMAT_ABBREV_RELATIVE);
        date.setText(dateString);
    }
}