List of usage examples for android.text.format DateUtils SECOND_IN_MILLIS
long SECOND_IN_MILLIS
To view the source code for android.text.format DateUtils SECOND_IN_MILLIS.
Click Source Link
From source file:net.simonvt.cathode.ui.fragment.SearchShowFragment.java
@Override public Loader<SimpleCursor> onCreateLoader(int id, Bundle args) { StringBuilder where = new StringBuilder(); where.append(ShowColumns.ID).append(" in ("); final int showCount = searchShowIds.size(); String[] ids = new String[showCount]; for (int i = 0; i < showCount; i++) { ids[i] = String.valueOf(searchShowIds.get(i)); where.append("?"); if (i < showCount - 1) { where.append(","); }//from w w w . j av a2 s . c o m } where.append(")"); SimpleCursorLoader loader = new SimpleCursorLoader(getActivity(), Shows.SHOWS, ShowDescriptionAdapter.PROJECTION, where.toString(), ids, sortBy.getSortOrder()); loader.setUpdateThrottle(2 * DateUtils.SECOND_IN_MILLIS); return loader; }
From source file:net.niyonkuru.koodroid.service.SessionService.java
private void logout() { final ContentResolver cr = getContentResolver(); final String email = mSettings.email(); /* clear application settings */ cr.delete(Settings.CONTENT_URI, null, null); try {/*from ww w . ja va 2s . c om*/ /* allow a 5 second window for batch operations to finish */ Thread.sleep(5 * DateUtils.SECOND_IN_MILLIS); } catch (InterruptedException ignored) { } /* clear database data */ cr.delete(Subscribers.CONTENT_URI, Subscribers.SUBSCRIBER_EMAIL + "='" + email + "'", null); CookieManager cookieManager = CookieManager.getInstance(); if (cookieManager != null) { cookieManager.removeAllCookie(); } stopSelf(); }
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 *//*from w ww .j a v a 2 s .c om*/ // 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:net.niyonkuru.koodroid.service.SessionService.java
/** * Create a DefaultHttpClient Object with several parameters set * * @return a new DefaultHttpClient Object */// ww w. j a va2s . c o m private static DefaultHttpClient getHttpClient(Context context) { HttpParams params = new BasicHttpParams(); // Use generous timeouts for slow mobile networks int timeout = (int) (25 * DateUtils.SECOND_IN_MILLIS); HttpConnectionParams.setConnectionTimeout(params, timeout); HttpConnectionParams.setSoTimeout(params, timeout); /* Inexplicably speeds up POST requests? */ HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setUserAgent(params, buildUserAgent(context)); HttpConnectionParams.setSocketBufferSize(params, 8192); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 443)); ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry); return new DefaultHttpClient(cm, params); }
From source file:com.vuze.android.remote.activity.RcmActivity.java
@Override public void onExtraViewVisibilityChange(final View view, int visibility) { {/*from w w w. j av a 2 s . c o m*/ if (visibility != View.VISIBLE) { if (pullRefreshHandler != null) { pullRefreshHandler.removeCallbacksAndMessages(null); pullRefreshHandler = null; } return; } if (pullRefreshHandler != null) { pullRefreshHandler.removeCallbacks(null); pullRefreshHandler = null; } pullRefreshHandler = new Handler(Looper.getMainLooper()); pullRefreshHandler.postDelayed(new Runnable() { @Override public void run() { if (isFinishing()) { return; } long sinceMS = System.currentTimeMillis() - lastUpdated; String since = DateUtils.getRelativeDateTimeString(RcmActivity.this, lastUpdated, DateUtils.SECOND_IN_MILLIS, DateUtils.WEEK_IN_MILLIS, 0).toString(); String s = getResources().getString(R.string.last_updated, since); TextView tvSwipeText = (TextView) view.findViewById(R.id.swipe_text); tvSwipeText.setText(s); if (pullRefreshHandler == null) { return; } 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.namelessdev.mpdroid.NotificationService.java
/** * A simple method to enable lock screen seeking on 4.3 and higher. * * @param controlFlags The control flags you set beforehand, so that we can add our * required flag// w ww .j av a2 s . c o m */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) private void enableSeeking(final int controlFlags) { mRemoteControlClient .setTransportControlFlags(controlFlags | RemoteControlClient.FLAG_KEY_MEDIA_POSITION_UPDATE); /* Allows Android to show the song position */ mRemoteControlClient .setOnGetPlaybackPositionListener(new RemoteControlClient.OnGetPlaybackPositionListener() { /** * Android's callback that queries us for the elapsed time * Here, we are guessing the elapsed time using the last time we * updated the elapsed time and its value at the time. * * @return The guessed song position */ @Override public long onGetPlaybackPosition() { /** * If we don't know the position, return * a negative value as per the API spec. */ long result = -1L; if (lastStatusRefresh > 0L) { result = lastKnownElapsed + new Date().getTime() - lastStatusRefresh; } return result; } }); /* Allows Android to seek */ mRemoteControlClient .setPlaybackPositionUpdateListener(new RemoteControlClient.OnPlaybackPositionUpdateListener() { /** * Android's callback for when the user seeks using the remote * control. * * @param newPositionMs The position in MS where we should seek */ @Override public void onPlaybackPositionUpdate(final long newPositionMs) { try { app.oMPDAsyncHelper.oMPD.seek(newPositionMs / DateUtils.SECOND_IN_MILLIS); mRemoteControlClient.setPlaybackState(getRemoteState(getStatus()), newPositionMs, 1.0f); } catch (final MPDServerException e) { Log.e(TAG, "Could not seek", e); } } }); }
From source file:com.android.exchange.service.EasSyncHandler.java
/** * Send one Sync POST to the Exchange server, and handle the response. * @return One of {@link #SYNC_RESULT_FAILED}, {@link #SYNC_RESULT_MORE_AVAILABLE}, or * {@link #SYNC_RESULT_DONE} as appropriate for the server response. * @param syncResult//from w w w . j a va 2s. co m * @param numWindows */ private int performOneSync(SyncResult syncResult, int numWindows) { final String syncKey = getSyncKey(); if (syncKey == null) { return SYNC_RESULT_FAILED; } final boolean initialSync = syncKey.equals("0"); final EasResponse resp; try { final Serializer s = buildEasRequest(syncKey, initialSync, numWindows); final long timeout = initialSync ? 120 * DateUtils.SECOND_IN_MILLIS : COMMAND_TIMEOUT; resp = sendHttpClientPost("Sync", s.toByteArray(), timeout); } catch (final IOException e) { LogUtils.e(TAG, e, "Sync error:"); syncResult.stats.numIoExceptions++; return SYNC_RESULT_FAILED; } catch (final CertificateException e) { LogUtils.e(TAG, e, "Certificate error:"); syncResult.stats.numAuthExceptions++; return SYNC_RESULT_FAILED; } final int result; try { final int responseResult; final int code = resp.getStatus(); if (code == HttpStatus.SC_OK) { // A successful sync can have an empty response -- this indicates no change. // In the case of a compressed stream, resp will be non-empty, but parse() handles // that case. if (!resp.isEmpty()) { responseResult = parse(resp); } else { responseResult = SYNC_RESULT_DONE; } } else { LogUtils.e(TAG, "Sync failed with Status: " + code); responseResult = SYNC_RESULT_FAILED; } if (responseResult == SYNC_RESULT_DONE || responseResult == SYNC_RESULT_MORE_AVAILABLE) { result = responseResult; } else if (resp.isProvisionError() || responseResult == SYNC_RESULT_PROVISIONING_ERROR) { final EasProvision provision = new EasProvision(mContext, mAccount.mId, this); if (provision.provision(syncResult, mAccount.mId)) { // We handled the provisioning error, so loop. LogUtils.d(TAG, "Provisioning error handled during sync, retrying"); result = SYNC_RESULT_MORE_AVAILABLE; } else { syncResult.stats.numAuthExceptions++; result = SYNC_RESULT_FAILED; } } else if (resp.isAuthError() || responseResult == SYNC_RESULT_DENIED) { syncResult.stats.numAuthExceptions++; result = SYNC_RESULT_FAILED; } else { syncResult.stats.numParseExceptions++; result = SYNC_RESULT_FAILED; } } finally { resp.close(); } cleanup(result); if (initialSync && result != SYNC_RESULT_FAILED) { // TODO: Handle Automatic Lookback } return result; }
From source file:de.Maxr1998.xposed.maxlock.ui.LockFragment.java
private void setupPatternLayout() { // Pattern View lockPatternView = (LockPatternView) rootView.findViewById(R.id.pattern_view); // Pattern Listener patternListener = new LockPatternView.OnPatternListener() { @Override//from ww w . j a v a 2s . com public void onPatternStart() { lockPatternView.removeCallbacks(mLockPatternViewReloader); } @Override public void onPatternCleared() { lockPatternView.removeCallbacks(mLockPatternViewReloader); lockPatternView.setDisplayMode(LockPatternView.DisplayMode.Correct); } @Override public void onPatternCellAdded(List<LockPatternView.Cell> pattern) { } @Override public void onPatternDetected(List<LockPatternView.Cell> pattern) { key.setLength(0); key.append(pattern); if (!checkInput()) { lockPatternView.setDisplayMode(LockPatternView.DisplayMode.Wrong); lockPatternView.postDelayed(mLockPatternViewReloader, DateUtils.SECOND_IN_MILLIS); } } }; // Layout switch (getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) { case Configuration.SCREENLAYOUT_SIZE_LARGE: case Configuration.SCREENLAYOUT_SIZE_XLARGE: { final int size = getResources().getDimensionPixelSize( com.haibison.android.lockpattern.R.dimen.alp_42447968_lockpatternview_size); ViewGroup.LayoutParams lp = lockPatternView.getLayoutParams(); lp.width = size; lp.height = size; lockPatternView.setLayoutParams(lp); break; } } lockPatternView.setOnPatternListener(patternListener); lockPatternView.setInStealthMode(!prefs.getBoolean(Common.PATTERN_SHOW_PATH, true)); lockPatternView.setTactileFeedbackEnabled(prefs.getBoolean(Common.PATTERN_FEEDBACK, true)); }
From source file:io.plaidapp.ui.DribbbleShot.java
void bindShot(final boolean postponeEnterTransition) { final Resources res = getResources(); // load the main image final int[] imageSize = shot.images.bestSize(); Glide.with(this).load(shot.images.best()).listener(shotLoadListener) .diskCacheStrategy(DiskCacheStrategy.SOURCE).priority(Priority.IMMEDIATE) .override(imageSize[0], imageSize[1]).into(imageView); imageView.setOnClickListener(shotClick); shotSpacer.setOnClickListener(shotClick); if (postponeEnterTransition) postponeEnterTransition();/*from w w w .j a v a 2 s . c o m*/ imageView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { imageView.getViewTreeObserver().removeOnPreDrawListener(this); calculateFabPosition(); if (postponeEnterTransition) startPostponedEnterTransition(); return true; } }); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { ((FabOverlapTextView) title).setText(shot.title); } else { ((TextView) title).setText(shot.title); } if (!TextUtils.isEmpty(shot.description)) { final Spanned descText = shot.getParsedDescription( ContextCompat.getColorStateList(this, R.color.dribbble_links), ContextCompat.getColor(this, R.color.dribbble_link_highlight)); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { ((FabOverlapTextView) description).setText(descText); } else { HtmlUtils.setTextWithNiceLinks((TextView) description, descText); } } else { description.setVisibility(View.GONE); } NumberFormat nf = NumberFormat.getInstance(); likeCount.setText( res.getQuantityString(R.plurals.likes, (int) shot.likes_count, nf.format(shot.likes_count))); likeCount.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ((AnimatedVectorDrawable) likeCount.getCompoundDrawables()[1]).start(); if (shot.likes_count > 0) { PlayerSheet.start(DribbbleShot.this, shot); } } }); if (shot.likes_count == 0) { likeCount.setBackground(null); // clear touch ripple if doesn't do anything } viewCount.setText( res.getQuantityString(R.plurals.views, (int) shot.views_count, nf.format(shot.views_count))); viewCount.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ((AnimatedVectorDrawable) viewCount.getCompoundDrawables()[1]).start(); } }); share.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ((AnimatedVectorDrawable) share.getCompoundDrawables()[1]).start(); new ShareDribbbleImageTask(DribbbleShot.this, shot).execute(); } }); if (shot.user != null) { playerName.setText(shot.user.name.toLowerCase()); Glide.with(this).load(shot.user.getHighQualityAvatarUrl()).transform(circleTransform) .placeholder(R.drawable.avatar_placeholder).override(largeAvatarSize, largeAvatarSize) .into(playerAvatar); View.OnClickListener playerClick = new View.OnClickListener() { @Override public void onClick(View v) { Intent player = new Intent(DribbbleShot.this, PlayerActivity.class); if (shot.user.shots_count > 0) { // legit user object player.putExtra(PlayerActivity.EXTRA_PLAYER, shot.user); } else { // search doesn't fully populate the user object, // in this case send the ID not the full user player.putExtra(PlayerActivity.EXTRA_PLAYER_NAME, shot.user.username); player.putExtra(PlayerActivity.EXTRA_PLAYER_ID, shot.user.id); } ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(DribbbleShot.this, playerAvatar, getString(R.string.transition_player_avatar)); startActivity(player, options.toBundle()); } }; playerAvatar.setOnClickListener(playerClick); playerName.setOnClickListener(playerClick); if (shot.created_at != null) { shotTimeAgo .setText( DateUtils .getRelativeTimeSpanString(shot.created_at.getTime(), System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS) .toString().toLowerCase()); } } else { playerName.setVisibility(View.GONE); playerAvatar.setVisibility(View.GONE); shotTimeAgo.setVisibility(View.GONE); } commentAnimator = new CommentAnimator(); commentsList.setItemAnimator(commentAnimator); adapter = new CommentsAdapter(shotDescription, commentFooter, shot.comments_count, getResources().getInteger(R.integer.comment_expand_collapse_duration)); commentsList.setAdapter(adapter); commentsList.addItemDecoration(new InsetDividerDecoration(CommentViewHolder.class, res.getDimensionPixelSize(R.dimen.divider_height), res.getDimensionPixelSize(R.dimen.keyline_1), ContextCompat.getColor(this, R.color.divider))); if (shot.comments_count != 0) { loadComments(); } checkLiked(); }
From source file:com.novoda.downloadmanager.lib.DownloadNotifier.java
/** * Return given duration in a human-friendly format. For example, "4 * minutes" or "1 second". Returns only largest meaningful unit of time, * from seconds up to hours./*from w w w . j a v a 2 s . c om*/ */ public CharSequence formatDuration(long millis) { final Resources res = mContext.getResources(); if (millis >= DateUtils.HOUR_IN_MILLIS) { final int hours = (int) ((millis + 1800000) / DateUtils.HOUR_IN_MILLIS); return res.getQuantityString(R.plurals.dl__duration_hours, hours, hours); } else if (millis >= DateUtils.MINUTE_IN_MILLIS) { final int minutes = (int) ((millis + 30000) / DateUtils.MINUTE_IN_MILLIS); return res.getQuantityString(R.plurals.dl__duration_minutes, minutes, minutes); } else { final int seconds = (int) ((millis + 500) / DateUtils.SECOND_IN_MILLIS); return res.getQuantityString(R.plurals.dl__duration_seconds, seconds, seconds); } }