List of usage examples for android.os SystemClock elapsedRealtime
@CriticalNative native public static long elapsedRealtime();
From source file:com.android.nfc.beam.BeamTransferManager.java
void updateStateAndNotification(int newState) { this.mState = newState; this.mLastUpdate = SystemClock.elapsedRealtime(); mHandler.removeMessages(MSG_TRANSFER_TIMEOUT); if (isRunning()) { // Update timeout timer if we're still running mHandler.sendEmptyMessageDelayed(MSG_TRANSFER_TIMEOUT, ALIVE_CHECK_MS); }//from w ww.j ava 2 s.c o m updateNotification(); if ((mState == STATE_SUCCESS || mState == STATE_FAILED || mState == STATE_CANCELLED) && !mCalledBack) { mCalledBack = true; // Notify that we're done with this transfer mCallback.onTransferComplete(this, mState == STATE_SUCCESS); } }
From source file:com.anysoftkeyboard.keyboards.views.AnyKeyboardView.java
@Override public void onDraw(Canvas canvas) { final boolean keyboardChanged = mKeyboardChanged; super.onDraw(canvas); // switching animation if (mAnimationLevel != AnimationsLevel.None && keyboardChanged && (mInAnimation != null)) { startAnimation(mInAnimation);/*from ww w. ja v a2 s . co m*/ mInAnimation = null; } // text pop out animation if (mPopOutText != null && mAnimationLevel != AnimationsLevel.None) { final int maxVerticalTravel = getHeight() / 2; final long currentAnimationTime = SystemClock.elapsedRealtime() - mPopOutTime; if (currentAnimationTime > TEXT_POP_OUT_ANIMATION_DURATION) { mPopOutText = null; } else { final float popOutPositionProgress = ((float) currentAnimationTime) / ((float) TEXT_POP_OUT_ANIMATION_DURATION); final float animationProgress = mPopOutTextReverting ? 1f - popOutPositionProgress : popOutPositionProgress; final float animationInterpolatorPosition = getPopOutAnimationInterpolator(false, animationProgress); final int y = mPopOutStartPoint.y - (int) (maxVerticalTravel * animationInterpolatorPosition); final int x = mPopOutStartPoint.x; final int alpha = mPopOutTextReverting ? (int) (255 * animationProgress) : 255 - (int) (255 * animationProgress); // drawing setPaintToKeyText(mPaint); // will disappear over time mPaint.setAlpha(alpha); mPaint.setShadowLayer(5, 0, 0, Color.BLACK); // will grow over time mPaint.setTextSize(mPaint.getTextSize() * (1.0f + animationInterpolatorPosition)); canvas.translate(x, y); canvas.drawText(mPopOutText, 0, mPopOutText.length(), 0, 0, mPaint); canvas.translate(-x, -y); //we're doing reverting twice much faster if (mPopOutTextReverting) { mPopOutTime = mPopOutTime - (int) (60 * popOutPositionProgress); } // next frame postInvalidateDelayed(1000 / 60);// doing 60 frames per second; } } //showing alpha/beta icon if needed if (BuildConfig.TESTING_BUILD) { final float textSizeForBuildSign = mPaint.getTextSize() / 2f; final float x = getWidth() - (mBuildTypeSignText.length() * textSizeForBuildSign); final float y = getHeight() - textSizeForBuildSign - getPaddingBottom(); canvas.translate(x, y); canvas.drawText(mBuildTypeSignText, 0, mBuildTypeSignText.length(), 0, 0, mBuildTypeSignPaint); canvas.translate(-x, -y); } }
From source file:com.chauthai.overscroll.BouncyAdapter.java
/** * Compute current scroll speed.//from w ww .java 2 s. co m * @param dx in {@link RecyclerView.OnScrollListener} * @param dy in {@link RecyclerView.OnScrollListener} */ private void computeScrollSpeed(int dx, int dy) { long currTime = SystemClock.elapsedRealtime(); int deltaDist = (directionVertical() ? dy : dx); if (mFirstScrollBy) { mFirstScrollBy = false; int correctedDeltaDist = deltaDist * (mLayoutManager.getReverseLayout() ? -1 : 1); if (correctedDeltaDist > 0) deltaDist = getFooterVisibleLength(); else if (correctedDeltaDist < 0) deltaDist = getHeaderVisibleLength(); if (mLayoutManager.getReverseLayout()) { deltaDist *= -1; } } mScrollSpeed = (double) deltaDist / (currTime - mPrevTime); mPrevTime = currTime; }
From source file:com.scvngr.levelup.core.test.TestThreadingUtils.java
/** * Helper method to wait for an action to occur. * * @param instrumentation the test {@link Instrumentation}. * @param activity the activity for the test being run. * @param latchRunnable the runnable that will check the condition and signal success via its * {@link java.util.concurrent.CountDownLatch}. * @param timeoutMillis the timeout duration in milliseconds. * @param isMainThreadRunnable Determine whether or not the runnable must be invoked on the main * thread./* ww w.ja v a2s.c o m*/ * @return true if the action happened before the timeout, false otherwise. */ public static boolean waitForAction(@NonNull final Instrumentation instrumentation, @NonNull final Activity activity, @NonNull final LatchRunnable latchRunnable, final long timeoutMillis, final boolean isMainThreadRunnable) { final long endTime = SystemClock.elapsedRealtime() + timeoutMillis; boolean result = true; while (true) { if (isMainThreadRunnable) { runOnMainSync(instrumentation, activity, latchRunnable); } else { latchRunnable.run(); instrumentation.waitForIdleSync(); } if (latchRunnable.getCount() == 0) { break; } if (SystemClock.elapsedRealtime() >= endTime) { result = false; break; } SystemClock.sleep(WAIT_SLEEP_MILLIS); } return result; }
From source file:com.scooter1556.sms.android.activity.VideoPlayerActivity.java
@Override public void onStateChanged(boolean playWhenReady, int playbackState) { switch (playbackState) { case ExoPlayer.STATE_BUFFERING: break;/*w w w . ja v a2 s . c o m*/ case ExoPlayer.STATE_ENDED: releasePlayer(); finish(); break; case ExoPlayer.STATE_IDLE: break; case ExoPlayer.STATE_PREPARING: break; case ExoPlayer.STATE_READY: // Set timeline timeline.setProgress((int) player.getCurrentPosition()); currentTime.setText(stringForTime(player.getCurrentPosition())); timeline.setMax((int) (player.getDuration() * 1000)); duration.setText(stringForTime(player.getDuration() * 1000)); if (player.isPlaying()) { playButton.setImageResource(R.drawable.ic_pause_light); videoOverlay.setVisibility(View.INVISIBLE); // Keep screen on getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); showController = false; surface.postDelayed(updateController, 1000); lastActionTime = SystemClock.elapsedRealtime(); } else { playButton.setImageResource(R.drawable.ic_play_light); videoOverlay.setVisibility(View.VISIBLE); } break; default: break; } }
From source file:csic.ceab.movelab.beepath.FixGet.java
private void announceFixStarted() { Intent intent = new Intent(FIX_STARTED); sendBroadcast(intent); Util.lastFixStartedAt = SystemClock.elapsedRealtime(); }
From source file:com.github.nutomic.pegasus.LocationService.java
/** * Receive start Intent, start learning an area or check if the * sound profile for the current area has changed. *///from ww w . j av a2 s . c om @Override public int onStartCommand(Intent intent, int flags, int startId) { if (intent != null) { Bundle extras = intent.getExtras(); if (extras != null) { Set<String> keys = extras.keySet(); if (keys.contains(MESSAGE_LEARN_AREA)) { // Set the area to learn now and the learn duration. mLearnUntil = SystemClock.elapsedRealtime() + extras.getLong(MESSAGE_LEARN_INTERVAL); mLearnArea = extras.getLong(MESSAGE_LEARN_AREA); } if (keys.contains(MESSAGE_UPDATE)) { // Profile/area mappings have changed, reapply profile. mCellListener.applyProfile(mCurrentCell); } } } return START_STICKY; }
From source file:mobisocial.musubi.service.AddressBookUpdateHandler.java
@Override public void onChange(boolean selfChange) { final DatabaseManager dbManager = new DatabaseManager(mContext); if (!dbManager.getIdentitiesManager().hasConnectedAccounts()) { Log.w(TAG, "no connected accounts, skipping friend import"); return;//from w w w. j ava2 s .co m } //a new meta contact appears (and the previous ones disappear) if the user merges //or if a new entry is added, we can detect the ones that have changed by //this condition long highestContactIdAlreadySeen = dbManager.getContactDataVersionManager().getMaxContactIdSeen(); //a new data item corresponds with a new contact, but its possible //that a users just adds a new contact method to an existing contact //and we need to detect that long highestDataIdAlreadySeen = dbManager.getContactDataVersionManager().getMaxDataIdSeen(); // BJD -- this didn't end up being faster once all import features were added. /*if (highestContactIdAlreadySeen == -1) { importFullAddressBook(mContext); return; }*/ long now = System.currentTimeMillis(); if (mLastRun + ONCE_PER_PERIOD > now) { //wake up when the period expires if (!mScheduled) { new Handler(mThread.getLooper()).postDelayed(new Runnable() { @Override public void run() { mScheduled = false; dispatchChange(false); } }, ONCE_PER_PERIOD - (now - mLastRun) + 1); } mScheduled = true; //skip this update return; } Log.i(TAG, "waking up to handle contact changes..."); boolean identityAdded = false, profileDataChanged = false; Date start = new Date(); assert (SYNC_EMAIL); String account_type_selection = getAccountSelectionString(); Cursor c = mContext.getContentResolver().query( ContactsContract.Data.CONTENT_URI, new String[] { ContactsContract.Data._ID, ContactsContract.Data.DATA_VERSION, ContactsContract.Data.CONTACT_ID }, "(" + ContactsContract.Data.DATA_VERSION + ">0 OR " + //maybe updated ContactsContract.Data.CONTACT_ID + ">? OR " + //definitely new or merged ContactsContract.Data._ID + ">? " + //definitely added a data item ") AND (" + ContactsContract.RawContacts.ACCOUNT_TYPE + "<>'" + mAccountType + "'" + ") AND (" + NAME_OR_OTHER_SELECTION + account_type_selection + ")", // All known contacts. new String[] { String.valueOf(highestContactIdAlreadySeen), String.valueOf(highestDataIdAlreadySeen) }, null); if (c == null) { Log.e(TAG, "no valid cursor", new Throwable()); mContext.getContentResolver().notifyChange(MusubiService.ADDRESS_BOOK_SCANNED, this); return; } HashMap<Pair<String, String>, MMyAccount> account_mapping = new HashMap<Pair<String, String>, MMyAccount>(); int max_changes = c.getCount(); TLongArrayList raw_data_ids = new TLongArrayList(max_changes); TLongArrayList versions = new TLongArrayList(max_changes); long new_max_data_id = highestDataIdAlreadySeen; long new_max_contact_id = highestContactIdAlreadySeen; TLongHashSet potentially_changed = new TLongHashSet(); try { //the cursor points to a list of raw contact data items that may have changed //the items will include a type specific field that we are interested in updating //it is possible that multiple data item entries mention the same identifier //so we build a list of contacts to update and then perform synchronization //by refreshing given that we know the top level contact id. if (DBG) Log.d(TAG, "Scanning " + c.getCount() + " contacts..."); while (c.moveToNext()) { if (DBG) Log.v(TAG, "check for updates of contact " + c.getLong(0)); long raw_data_id = c.getLong(0); long version = c.getLong(1); long contact_id = c.getLong(2); //if the contact was split or merged, then we get a higher contact id //so if we have a higher id, data version doesnt really matter if (contact_id <= highestContactIdAlreadySeen) { //the data associated with this contact may not be dirty //we just can't do the join against our table because thise //api is implmented over the content provider if (dbManager.getContactDataVersionManager().getVersion(raw_data_id) == version) continue; } else { new_max_contact_id = Math.max(new_max_contact_id, contact_id); } raw_data_ids.add(raw_data_id); versions.add(version); potentially_changed.add(contact_id); new_max_data_id = Math.max(new_max_data_id, raw_data_id); } if (DBG) Log.d(TAG, "Finished iterating over " + c.getCount() + " contacts for " + potentially_changed.size() + " candidates."); } finally { c.close(); } if (potentially_changed.size() == 0) { Log.w(TAG, "possible bug, woke up to update contacts, but no change was detected; there are extra wakes so it could be ok"); } final SQLiteDatabase db = dbManager.getDatabase(); Pattern emailPattern = getEmailPattern(); Pattern numberPattern = getNumberPattern(); //slice it up so we don't use too much system resource on keeping a lot of state in memory int total = potentially_changed.size(); sAddressBookTotal = total; sAddressBookPosition = 0; final TLongArrayList slice_of_changed = new TLongArrayList(BATCH_SIZE); final StringBuilder to_fetch = new StringBuilder(); final HashMap<Pair<String, String>, TLongHashSet> ids_for_account = new HashMap<Pair<String, String>, TLongHashSet>(); final TLongObjectHashMap<String> names = new TLongObjectHashMap<String>(); TLongIterator it = potentially_changed.iterator(); for (int i = 0; i < total && it.hasNext();) { sAddressBookPosition = i; if (BootstrapActivity.isBootstrapped()) { try { Thread.sleep(mSleepTime * SLEEP_SCALE); } catch (InterruptedException e) { } } slice_of_changed.clear(); ids_for_account.clear(); names.clear(); int max = i + BATCH_SIZE; for (; i < max && it.hasNext(); ++i) { slice_of_changed.add(it.next()); } if (DBG) Log.v(TAG, "looking up names "); to_fetch.setLength(0); to_fetch.append(ContactsContract.Contacts._ID + " IN "); SQLClauseHelper.appendArray(to_fetch, slice_of_changed.iterator()); //lookup the fields we care about from a user profile perspective c = mContext.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, new String[] { ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME, }, to_fetch.toString(), null, null); try { while (c.moveToNext()) { long id = c.getLong(0); String name = c.getString(1); if (name == null) continue; //reject names that are just the email address or are just a number //the default for android is just to propagate this as the name //if there is no name if (emailPattern.matcher(name).matches() || numberPattern.matcher(name).matches()) continue; names.put(id, name); } } finally { c.close(); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { db.beginTransactionNonExclusive(); } else { db.beginTransaction(); } long before = SystemClock.elapsedRealtime(); SliceUpdater updater = new SliceUpdater(dbManager, slice_of_changed, ids_for_account, names, account_type_selection); long after = SystemClock.elapsedRealtime(); mSleepTime = (mSleepTime + after - before) / 2; slice_of_changed.forEach(updater); profileDataChanged |= updater.profileDataChanged; identityAdded |= updater.identityAdded; db.setTransactionSuccessful(); db.endTransaction(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { db.beginTransactionNonExclusive(); } else { db.beginTransaction(); } //add all detected members to account feed for (Entry<Pair<String, String>, TLongHashSet> e : ids_for_account.entrySet()) { Pair<String, String> k = e.getKey(); TLongHashSet v = e.getValue(); MMyAccount cached_account = account_mapping.get(k); if (cached_account == null) { cached_account = lookupOrCreateAccount(dbManager, k.getValue0(), k.getValue1()); prepareAccountWhitelistFeed(dbManager.getMyAccountManager(), dbManager.getFeedManager(), cached_account); account_mapping.put(k, cached_account); } final MMyAccount account = cached_account; v.forEach(new TLongProcedure() { @Override public boolean execute(long id) { dbManager.getFeedManager().ensureFeedMember(account.feedId_, id); db.yieldIfContendedSafely(75); return true; } }); } db.setTransactionSuccessful(); db.endTransaction(); } sAddressBookTotal = sAddressBookPosition = 0; //TODO: handle deleted //for all android data ids in our table, check if they still exist in the //contacts table, probably in batches of 100 or something. if they don't //null them out. this is annoyingly non-differential. //TODO: adding friend should update accepted feed status, however, //if a crashe happens for whatever reason, then its possible that this may need to //be run for identities which actually exist in the db. so this update code //needs to do the feed accepted status change for all users that were touched //by the profile update process //update the version ids so we can be faster on subsequent runs if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { db.beginTransactionNonExclusive(); } else { db.beginTransaction(); } int changed_data_rows = raw_data_ids.size(); for (int i = 0; i < changed_data_rows; ++i) { dbManager.getContactDataVersionManager().setVersion(raw_data_ids.get(i), versions.get(i)); } db.setTransactionSuccessful(); db.endTransaction(); dbManager.getContactDataVersionManager().setMaxDataIdSeen(new_max_data_id); dbManager.getContactDataVersionManager().setMaxContactIdSeen(new_max_contact_id); ContentResolver resolver = mContext.getContentResolver(); Date end = new Date(); double time = end.getTime() - start.getTime(); time /= 1000; Log.w(TAG, "update address book " + mChangeCount++ + " took " + time + " seconds"); if (identityAdded) { //wake up the profile push resolver.notifyChange(MusubiService.WHITELIST_APPENDED, this); } if (profileDataChanged) { //refresh the ui... resolver.notifyChange(MusubiService.PRIMARY_CONTENT_CHANGED, this); } if (identityAdded || profileDataChanged) { //update the our musubi address book as needed. String accountName = mContext.getString(R.string.account_name); String accountType = mContext.getString(R.string.account_type); Account account = new Account(accountName, accountType); ContentResolver.requestSync(account, ContactsContract.AUTHORITY, new Bundle()); } dbManager.close(); mLastRun = new Date().getTime(); resolver.notifyChange(MusubiService.ADDRESS_BOOK_SCANNED, this); }
From source file:com.lastsoft.plog.adapter.PlayAdapter.java
@Override public void onBindViewHolder(final ViewHolder viewHolder, final int position) { //Log.d(TAG, "Element " + position + " set."); // Get element from your dataset at this position and replace the contents of the view // with that element //if (searchQuery.equals("") || (games.get(position).gameName.toLowerCase().contains(searchQuery.toLowerCase()))) { DateFormat outputFormatter = new SimpleDateFormat("MM/dd/yyyy"); Date theDate = plays.get(position).playDate; long diff = new Date().getTime() - theDate.getTime(); long days = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS); String output_date;/* w ww . j ava 2 s .co m*/ if (days == 0) { output_date = mActivity.getString(R.string.played_label) + mActivity.getString(R.string.less_than_a_day_ago); } else if (days == 1) { output_date = mActivity.getString(R.string.played_label) + days + mActivity.getString(R.string.day_ago_label); } else if (days <= 6) { output_date = mActivity.getString(R.string.played_label) + days + mActivity.getString(R.string.days_ago_label); } else { output_date = mActivity.getString(R.string.played_label) + outputFormatter.format(theDate); // Output : 01/20/2012 } //String output_date = outputFormatter.format(theDate); // Output : 01/20/2012 if (plays.get(position).playLocation != null) { output_date = output_date + " at " + Location.findById(Location.class, plays.get(position).playLocation.getId()).locationName; } if (plays.get(position).playNotes != null && !plays.get(position).playNotes.equals("")) { viewHolder.getPlayDescView().setVisibility(View.VISIBLE); viewHolder.getPlayDescView().setText("\"" + plays.get(position).playNotes + "\""); } else { Log.d("V1", "gone"); viewHolder.getPlayDescView().setVisibility(View.GONE); } viewHolder.getGameNameView().setText(GamesPerPlay.getBaseGame(plays.get(position)).gameName); viewHolder.getPlayDateView().setText(output_date); viewHolder.getImageView().setTransitionName("imageTrans" + position); viewHolder.getImageView().setTag("imageTrans" + position); viewHolder.getGameNameView().setTransitionName("nameTrans" + position); viewHolder.getGameNameView().setTag("nameTrans" + position); viewHolder.getPlayDateView().setTransitionName("dateTrans" + position); viewHolder.getPlayDateView().setTag("dateTrans" + position); viewHolder.getClickLayout().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (SystemClock.elapsedRealtime() - mLastClickTime < 2000) { return; } mLastClickTime = SystemClock.elapsedRealtime(); ((MainActivity) mActivity).onPlayClicked(plays.get(position), mFragment, viewHolder.getImageView(), viewHolder.getGameNameView(), viewHolder.getPlayDateView(), position, fromDrawer, playListType, sortType, searchQuery); } }); viewHolder.getOverflowLayout().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { playPopup(view, position); } }); String playPhoto; playPhoto = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/Plog/" + plays.get(position).playPhoto; if (plays.get(position).playPhoto != null && (plays.get(position).playPhoto.equals("") || new File(playPhoto).exists() == false)) { String gameThumb = GamesPerPlay.getBaseGame(plays.get(position)).gameThumb; if (gameThumb != null && !gameThumb.equals("")) { //ImageLoader.getInstance().displayImage("http:" + GamesPerPlay.getBaseGame(plays.get(position)).gameThumb, viewHolder.getImageView(), options); //ImageLoader.getInstance().loadImage("http:" + GamesPerPlay.getBaseGame(plays.get(position)).gameThumb, options, null); Picasso.with(mActivity).load("http:" + GamesPerPlay.getBaseGame(plays.get(position)).gameThumb) .fit().into(viewHolder.getImageView()); } else { viewHolder.getImageView().setImageDrawable(null); } } else { String thumbPath = playPhoto.substring(0, playPhoto.length() - 4) + "_thumb6.jpg"; if (new File(thumbPath).exists()) { //ImageLoader.getInstance().displayImage("file://" + thumbPath, viewHolder.getImageView(), options); //ImageLoader.getInstance().loadImage("file://" + playPhoto, options, null); Picasso.with(mActivity).load("file://" + thumbPath).into(viewHolder.getImageView()); } else { ImageLoader.getInstance().displayImage("file://" + playPhoto, viewHolder.getImageView(), options); //Picasso.with(mActivity).load(playPhoto).fit().into(viewHolder.getImageView()); // make a thumb String thumbPath2 = playPhoto.substring(0, playPhoto.length() - 4) + "_thumb6.jpg"; try { FileInputStream fis; fis = new FileInputStream(playPhoto); Bitmap imageBitmap = BitmapFactory.decodeStream(fis); Bitmap b = resizeImageForImageView(imageBitmap, 500); if (b != null) { try { b.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(new File(thumbPath2))); } catch (Exception ignored) { } b = null; } if (imageBitmap != null) { imageBitmap = null; } Picasso.with(mActivity).load("file://" + thumbPath2).resize(500, 500).centerCrop() .into(viewHolder.getImageView()); } catch (Exception e) { e.printStackTrace(); } //still use the og picture. next time there will be a thumb } //Picasso.with(mActivity).load(playPhoto).fetch(); //ImageLoader.getInstance().loadImage(playPhoto, options, null); } viewHolder.getPlayWinnerView().setTypeface(null, Typeface.ITALIC); /*if (plays.get(position).winners != null) { viewHolder.getPlayWinnerView().setText(mActivity.getString(R.string.winners) + plays.get(position).winners); }else{*/ String winners = Play.getWinners(plays.get(position)); if (winners == null) { viewHolder.getPlayWinnerView() .setText(mActivity.getString(R.string.winners) + mActivity.getString(R.string.none)); } else { viewHolder.getPlayWinnerView().setText(mActivity.getString(R.string.winners) + winners); } //} }
From source file:com.phearom.um.ui.FullScreenPlayerActivity.java
private void updateProgress() { if (mLastPlaybackState == null) { return;/*from w w w .j ava2s.c o m*/ } long currentPosition = mLastPlaybackState.getPosition(); if (mLastPlaybackState.getState() != PlaybackStateCompat.STATE_PAUSED) { long timeDelta = SystemClock.elapsedRealtime() - mLastPlaybackState.getLastPositionUpdateTime(); currentPosition += (int) timeDelta * mLastPlaybackState.getPlaybackSpeed(); } mSeekbar.setProgress((int) currentPosition); }