Example usage for android.os SystemClock uptimeMillis

List of usage examples for android.os SystemClock uptimeMillis

Introduction

In this page you can find the example usage for android.os SystemClock uptimeMillis.

Prototype

@CriticalNative
native public static long uptimeMillis();

Source Link

Document

Returns milliseconds since boot, not counting time spent in deep sleep.

Usage

From source file:com.shollmann.igcparser.ui.activity.FlightPreviewActivity.java

private void animateMarker() {
    final Handler handler = new Handler();
    final long start = SystemClock.uptimeMillis();
    duration = 300000;//www  .  j a va  2 s  . c  o m

    final Interpolator interpolator = new LinearInterpolator();

    handler.post(new Runnable() {
        int i = 0;

        @Override
        public void run() {
            long elapsed = SystemClock.uptimeMillis() - start;
            float t = interpolator.getInterpolation((float) elapsed / duration);
            if (i < listLatLngPoints.size()) {
                Double heading = SphericalUtil.computeHeading(markerGlider.getPosition(),
                        listLatLngPoints.get(i));
                markerGlider.setRotation(heading.floatValue());
                markerGlider.setPosition(listLatLngPoints.get(i));
            }
            i++;

            if (t < 1.0 && i < listLatLngPoints.size() && !isFinishReplay) {
                handler.postDelayed(this, replaySpeed);
            } else {
                finishReplay();
            }
        }
    });
}

From source file:org.mklab.mikity.android.CanvasFragment.java

/**
 * ???/*from  w w  w.ja v a2s  . c om*/
 */
public void runAnimation() {
    if (this.manager == null) {
        showMessageInDialog(getString(R.string.modelDataIsNotReady));
        return;
    }
    if (this.manager.isSourceReady() == false) {
        showMessageInDialog(getString(R.string.sourceDataIsNotReady));
        return;
    }

    if (this.playable == false) {
        this.timer.cancel();
    }

    if (this.isPaused == false) {
        this.startTime = SystemClock.uptimeMillis();
        this.delayTime = 0;
    }

    this.manager.prepareMovingGroupObjects();

    prepareTimeTable();

    this.stopTime = this.manager.getStopTime();

    if (this.isPaused) {
        this.delayTime += SystemClock.uptimeMillis() - this.pausedTime;
    }
    this.isPaused = false;

    this.animationTask = new AnimationTask(this.startTime, this.stopTime, getObjectGroupManager(),
            getObjectRender(), this.delayTime);
    this.animationTask.setSpeedScale(this.animationSpeedRate / 1000.0);
    this.animationTask.addAnimationTaskListener(new AnimationTaskListener() {

        /**
         * {@inheritDoc}
         */
        public void tearDownAnimation() {
            CanvasFragment.this.playable = true;
            if (CanvasFragment.this.isRepeating) {
                runAnimation();
            }
        }

        /**
         * {@inheritDoc}
         */
        public void setUpAnimation() {
            // nothing to do
        }
    });

    this.playable = false;
    this.timer = new Timer();
    this.timer.schedule(this.animationTask, 0, 30);
}

From source file:de.tlabs.ssr.g1.client.SourcesView.java

@Override
public boolean onScroll(MotionEvent firstEvent, MotionEvent thisEvent, float distanceX, float distanceY) {

    // transform sound source or surface?
    if (lastTouchSoundSource != null) { // transform sound source
        synchronized (GlobalData.audioScene) {
            // is lastTouchSoundSource selected?
            if (!lastTouchSoundSource.isSelected()) {
                // select only this source
                GlobalData.audioScene.deselectAllSoundSources();
                GlobalData.audioScene.selectSoundSource(lastTouchSoundSource);
            }//from w w w.  java 2 s .  c o  m

            // save positions of sources if this is first scroll event
            if (!scrolling) {
                scrolling = true;
                firstScrollPoint[0] = firstEvent.getX();
                firstScrollPoint[1] = firstEvent.getY();
                ArrayList<SoundSource> selectedSources = GlobalData.audioScene.getSelectedSoundSources();
                int numSources = selectedSources.size();
                for (int i = 0; i < numSources; i++) { // loop through all currently selected sources
                    selectedSources.get(i).getXY(point);
                    GlobalData.audioScene.mapPoint(point);
                    viewportTransformation.mapPoints(point);
                    selectedSources.get(i).savePosition(point);
                }
            }

            // enough time elapsed to do next position update?
            long currentTime = SystemClock.uptimeMillis();
            if (currentTime - lastSendTime < MAX_POSITION_UPDATE_FREQ)
                return true;
            lastSendTime = currentTime;

            // translate or rotate?
            if (transformationMode == TransformationMode.TRANSLATE) { // translate
                // generate server request string
                String strMsg = "<request>";
                ArrayList<SoundSource> selectedSources = GlobalData.audioScene.getSelectedSoundSources();
                int numSources = selectedSources.size();
                SoundSource soundSource;
                for (int i = 0; i < numSources; i++) { // loop through all currently selected sources
                    soundSource = selectedSources.get(i);

                    // if source is fixed, skip it
                    if (soundSource.isPositionFixed())
                        continue;

                    strMsg += "<source id='" + soundSource.getId() + "'>";
                    // transform screen coords into object coords, consider offset
                    point[0] = soundSource.getSavedX() + thisEvent.getX() - firstScrollPoint[0];
                    point[1] = soundSource.getSavedY() + thisEvent.getY() - firstScrollPoint[1];
                    inverseViewportTransformation.mapPoints(point);

                    if (soundSource.getSourceModel() == SoundSource.SourceModel.PLANE) { // recalculate orientation for plane waves
                        float norm = FloatMath.sqrt(point[0] * point[0] + point[1] * point[1]); // for plane waves, if source is movable
                        if (norm != 0.0f) {
                            float newAzimuth;
                            if (point[1] >= 0.0f)
                                newAzimuth = (float) (Math.acos(point[0] / norm) / Math.PI * 180.0f) - 180.0f
                                        + GlobalData.audioScene.getReference().getAzimuth();
                            else
                                newAzimuth = (float) -(Math.acos(point[0] / norm) / Math.PI * 180.0f) - 180.0f
                                        + GlobalData.audioScene.getReference().getAzimuth();
                            strMsg += "<orientation azimuth='" + String.valueOf(newAzimuth) + "'/>";
                        }
                    }

                    GlobalData.audioScene.inverseMapPoint(point);
                    strMsg += "<position x='" + String.valueOf(point[0]) + "' y='" + String.valueOf(point[1])
                            + "'/>";
                    strMsg += "</source>";
                }
                strMsg += "</request>\0";

                // send changes to server
                sendToServer(strMsg);
            } else { // rotate
                // not implemented
            }
        }
    } else { // transform surface
        if (!scrolling) {
            scrolling = true;
            firstScrollPoint[0] = thisEvent.getX();
            firstScrollPoint[1] = thisEvent.getY();
            currentSavedTranslation[0] = currentTranslation[0];
            currentSavedTranslation[1] = currentTranslation[1];
        }

        // translate or rotate?
        if (transformationMode == TransformationMode.TRANSLATE) { // translate
            if (currentOrientation == Configuration.ORIENTATION_PORTRAIT) {
                point[0] = thisEvent.getX() - firstScrollPoint[0];
                point[1] = thisEvent.getY() - firstScrollPoint[1];
            } else if (currentOrientation == Configuration.ORIENTATION_LANDSCAPE) {
                point[0] = thisEvent.getY() - firstScrollPoint[1];
                point[1] = -(thisEvent.getX() - firstScrollPoint[0]);
            }
            setCurrentTranslation(currentSavedTranslation[0] + point[0], currentSavedTranslation[1] + point[1]);
        } else { // rotate
            // not implemented
        }
    }

    return true;
}

From source file:com.cs4644.vt.theonering.MainActivity.java

private void startScan(final UUID[] servicesToScan, final String deviceNameToScanFor) {
    Log.d(TAG, "startScan");

    // Stop current scanning (if needed)
    stopScanning();/*w  w  w  .  ja v a 2 s  . co  m*/

    // Configure scanning
    BluetoothAdapter bluetoothAdapter = BleUtils.getBluetoothAdapter(getApplicationContext());
    if (BleUtils.getBleStatus(this) != BleUtils.STATUS_BLE_ENABLED) {
        Log.w(TAG, "startScan: BluetoothAdapter not initialized or unspecified address.");
    } else {
        mScanner = new BleDevicesScanner(bluetoothAdapter, servicesToScan,
                new BluetoothAdapter.LeScanCallback() {
                    @Override
                    public void onLeScan(final BluetoothDevice device, final int rssi, byte[] scanRecord) {
                        final String deviceName = device.getName();
                        Log.d(TAG, "Discovered device: " + (deviceName != null ? deviceName : "<unknown>"));

                        BluetoothDeviceData previouslyScannedDeviceData = null;
                        if (deviceNameToScanFor == null
                                || (deviceName != null && deviceName.equalsIgnoreCase(deviceNameToScanFor))) { // Workaround for bug in service discovery. Discovery filtered by service uuid is not working on Android 4.3, 4.4
                            if (mScannedDevices == null)
                                mScannedDevices = new ArrayList<>(); // Safeguard

                            // Check that the device was not previously found
                            for (BluetoothDeviceData deviceData : mScannedDevices) {
                                if (deviceData.device.getAddress().equals(device.getAddress())) {
                                    previouslyScannedDeviceData = deviceData;
                                    break;
                                }
                            }

                            BluetoothDeviceData deviceData;
                            if (previouslyScannedDeviceData == null) {
                                // Add it to the mScannedDevice list
                                deviceData = new BluetoothDeviceData();
                                mScannedDevices.add(deviceData);
                            } else {
                                deviceData = previouslyScannedDeviceData;
                            }

                            deviceData.device = device;
                            deviceData.rssi = rssi;
                            deviceData.scanRecord = scanRecord;
                            decodeScanRecords(deviceData);

                            // Update device data
                            long currentMillis = SystemClock.uptimeMillis();
                            if (previouslyScannedDeviceData == null
                                    || currentMillis - mLastUpdateMillis > kMinDelayToUpdateUI) { // Avoid updating when not a new device has been found and the time from the last update is really short to avoid updating UI so fast that it will become unresponsive
                                mLastUpdateMillis = currentMillis;

                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        updateUI();
                                    }
                                });
                            }
                        }
                    }
                });

        // Start scanning
        mScanner.start();
    }

    // Update UI
    updateUI();
}

From source file:io.requery.android.database.sqlite.SQLiteConnectionPool.java

private SQLiteConnection waitForConnection(String sql, int connectionFlags,
        CancellationSignal cancellationSignal) {
    final boolean wantPrimaryConnection = (connectionFlags & CONNECTION_FLAG_PRIMARY_CONNECTION_AFFINITY) != 0;

    final ConnectionWaiter waiter;
    final int nonce;
    synchronized (mLock) {
        throwIfClosedLocked();/*  www .  j a va2s. c  om*/

        // Abort if canceled.
        if (cancellationSignal != null) {
            cancellationSignal.throwIfCanceled();
        }

        // Try to acquire a connection.
        SQLiteConnection connection = null;
        if (!wantPrimaryConnection) {
            connection = tryAcquireNonPrimaryConnectionLocked(sql, connectionFlags); // might throw
        }
        if (connection == null) {
            connection = tryAcquirePrimaryConnectionLocked(connectionFlags); // might throw
        }
        if (connection != null) {
            return connection;
        }

        // No connections available.  Enqueue a waiter in priority order.
        final int priority = getPriority(connectionFlags);
        final long startTime = SystemClock.uptimeMillis();
        waiter = obtainConnectionWaiterLocked(Thread.currentThread(), startTime, priority,
                wantPrimaryConnection, sql, connectionFlags);
        ConnectionWaiter predecessor = null;
        ConnectionWaiter successor = mConnectionWaiterQueue;
        while (successor != null) {
            if (priority > successor.mPriority) {
                waiter.mNext = successor;
                break;
            }
            predecessor = successor;
            successor = successor.mNext;
        }
        if (predecessor != null) {
            predecessor.mNext = waiter;
        } else {
            mConnectionWaiterQueue = waiter;
        }

        nonce = waiter.mNonce;
    }

    // Set up the cancellation listener.
    if (cancellationSignal != null) {
        cancellationSignal.setOnCancelListener(new CancellationSignal.OnCancelListener() {
            @Override
            public void onCancel() {
                synchronized (mLock) {
                    if (waiter.mNonce == nonce) {
                        cancelConnectionWaiterLocked(waiter);
                    }
                }
            }
        });
    }
    try {
        // Park the thread until a connection is assigned or the pool is closed.
        // Rethrow an exception from the wait, if we got one.
        long busyTimeoutMillis = CONNECTION_POOL_BUSY_MILLIS;
        long nextBusyTimeoutTime = waiter.mStartTime + busyTimeoutMillis;
        for (;;) {
            // Detect and recover from connection leaks.
            if (mConnectionLeaked.compareAndSet(true, false)) {
                synchronized (mLock) {
                    wakeConnectionWaitersLocked();
                }
            }

            // Wait to be unparked (may already have happened), a timeout, or interruption.
            LockSupport.parkNanos(this, busyTimeoutMillis * 1000000L);

            // Clear the interrupted flag, just in case.
            Thread.interrupted();

            // Check whether we are done waiting yet.
            synchronized (mLock) {
                throwIfClosedLocked();

                final SQLiteConnection connection = waiter.mAssignedConnection;
                final RuntimeException ex = waiter.mException;
                if (connection != null || ex != null) {
                    recycleConnectionWaiterLocked(waiter);
                    if (connection != null) {
                        return connection;
                    }
                    throw ex; // rethrow!
                }

                final long now = SystemClock.uptimeMillis();
                if (now < nextBusyTimeoutTime) {
                    busyTimeoutMillis = now - nextBusyTimeoutTime;
                } else {
                    logConnectionPoolBusyLocked(now - waiter.mStartTime, connectionFlags);
                    busyTimeoutMillis = CONNECTION_POOL_BUSY_MILLIS;
                    nextBusyTimeoutTime = now + busyTimeoutMillis;
                }
            }
        }
    } finally {
        // Remove the cancellation listener.
        if (cancellationSignal != null) {
            cancellationSignal.setOnCancelListener(null);
        }
    }
}

From source file:com.dwdesign.tweetings.fragment.BaseStatusesListFragment.java

@Override
public void onStart() {
    super.onStart();
    mTickerStopped = false;/*from  w w  w. j av a2  s  .  c  o  m*/
    mHandler = new Handler();

    mTicker = new Runnable() {

        @Override
        public void run() {
            if (mTickerStopped)
                return;
            if (mListView != null && !mBusy) {
                getListAdapter().notifyDataSetChanged();
            }
            final long now = SystemClock.uptimeMillis();
            final long next = now + TICKER_DURATION - now % TICKER_DURATION;
            mHandler.postAtTime(mTicker, next);
        }
    };
    mTicker.run();

    final IntentFilter filter = new IntentFilter();
    filter.addAction(BROADCAST_MULTI_SELECT_STATE_CHANGED);
    filter.addAction(BROADCAST_MULTI_SELECT_ITEM_CHANGED);
    registerReceiver(mStateReceiver, filter);

    onPostStart();
}

From source file:org.mklab.mikity.android.CanvasFragment.java

/**
 * ????/*from ww w.j  a v a  2s. c  o  m*/
 */
public void pauseAnimation() {
    if (this.isPaused) {
        return;
    }

    if (this.animationTask != null) {
        this.timer.cancel();
        this.isPaused = true;
        this.playable = true;
        setPuasedTime(SystemClock.uptimeMillis());
    }
}

From source file:com.cw.litenote.note.Note.java

@Override
public void onBackPressed() {
    System.out.println("Note / _onBackPressed");
    // web view can go back
    String tagStr = "current" + viewPager.getCurrentItem() + "linkWebView";
    CustomWebView linkWebView = (CustomWebView) viewPager.findViewWithTag(tagStr);
    if (linkWebView.canGoBack()) {
        linkWebView.goBack();//from  www .j a  v  a  2  s.c o m
    } else if (isPictureMode()) {
        // dispatch touch event to show buttons
        long downTime = SystemClock.uptimeMillis();
        long eventTime = SystemClock.uptimeMillis() + 100;
        float x = 0.0f;
        float y = 0.0f;
        // List of meta states found here: developer.android.com/reference/android/view/KeyEvent.html#getMetaState()
        int metaState = 0;
        MotionEvent event = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_UP, x, y, metaState);
        dispatchTouchEvent(event);
        event.recycle();

        // in order to make sure ImageViewBackButton is effective to be clicked
        mPagerHandler = new Handler();
        mPagerHandler.postDelayed(mOnBackPressedRun, 500);
    } else if (isTextMode()) {
        // back to view all mode
        setViewAllMode();
        setOutline(act);
    } else {
        System.out.println("Note / _onBackPressed / view all mode");
        stopAV();
        finish();
    }
}

From source file:com.wb.launcher3.Folder.java

public void onDragOver(DragObject d) {
    final DragView dragView = d.dragView;
    final int scrollOffset = mScrollView.getScrollY();
    final float[] r = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset, dragView, null);
    r[0] -= getPaddingLeft();//from   w  ww  . j  a va2s.  c  o m
    r[1] -= getPaddingTop();

    final long downTime = SystemClock.uptimeMillis();
    final MotionEvent translatedEv = MotionEvent.obtain(downTime, downTime, MotionEvent.ACTION_MOVE, d.x, d.y,
            0);

    if (!mAutoScrollHelper.isEnabled()) {
        mAutoScrollHelper.setEnabled(true);
    }

    final boolean handled = mAutoScrollHelper.onTouch(this, translatedEv);
    translatedEv.recycle();

    if (handled) {
        mReorderAlarm.cancelAlarm();
    } else {
        mTargetCell = mContent.findNearestArea((int) r[0], (int) r[1] + scrollOffset, 1, 1, mTargetCell);
        if (isLayoutRtl()) {
            mTargetCell[0] = mContent.getCountX() - mTargetCell[0] - 1;
        }
        if (mTargetCell[0] != mPreviousTargetCell[0] || mTargetCell[1] != mPreviousTargetCell[1]) {
            mReorderAlarm.cancelAlarm();
            mReorderAlarm.setOnAlarmListener(mReorderAlarmListener);
            mReorderAlarm.setAlarm(REORDER_DELAY);
            mPreviousTargetCell[0] = mTargetCell[0];
            mPreviousTargetCell[1] = mTargetCell[1];
            mDragMode = DRAG_MODE_REORDER;
        } else {
            mDragMode = DRAG_MODE_NONE;
        }
    }
    //*/
}

From source file:org.telegram.messenger.NotificationsController.java

public void processLoadedUnreadMessages(final HashMap<Long, Integer> dialogs,
        final ArrayList<TLRPC.Message> messages, final ArrayList<TLRPC.User> users,
        final ArrayList<TLRPC.Chat> chats, final ArrayList<TLRPC.EncryptedChat> encryptedChats) {
    MessagesController.getInstance().putUsers(users, true);
    MessagesController.getInstance().putChats(chats, true);
    MessagesController.getInstance().putEncryptedChats(encryptedChats, true);

    notificationsQueue.postRunnable(new Runnable() {
        @Override//from  w  w w.ja v a2s  .  co  m
        public void run() {
            pushDialogs.clear();
            pushMessages.clear();
            pushMessagesDict.clear();
            total_unread_count = 0;
            personal_count = 0;
            SharedPreferences preferences = ApplicationLoader.applicationContext
                    .getSharedPreferences("Notifications", Context.MODE_PRIVATE);
            HashMap<Long, Boolean> settingsCache = new HashMap<>();

            if (messages != null) {
                for (TLRPC.Message message : messages) {
                    long mid = message.id;
                    if (message.to_id.channel_id != 0) {
                        mid |= ((long) message.to_id.channel_id) << 32;
                    }
                    if (pushMessagesDict.containsKey(mid)) {
                        continue;
                    }
                    MessageObject messageObject = new MessageObject(message, null, false);
                    if (isPersonalMessage(messageObject)) {
                        personal_count++;
                    }
                    long dialog_id = messageObject.getDialogId();
                    long original_dialog_id = dialog_id;
                    if ((messageObject.messageOwner.flags & TLRPC.MESSAGE_FLAG_MENTION) != 0) {
                        dialog_id = messageObject.messageOwner.from_id;
                    }
                    Boolean value = settingsCache.get(dialog_id);
                    if (value == null) {
                        int notifyOverride = getNotifyOverride(preferences, dialog_id);
                        value = !(notifyOverride == 2 || (!preferences.getBoolean("EnableAll", true)
                                || ((int) dialog_id < 0) && !preferences.getBoolean("EnableGroup", true))
                                && notifyOverride == 0);
                        settingsCache.put(dialog_id, value);
                    }
                    if (!value || dialog_id == openned_dialog_id && ApplicationLoader.isScreenOn) {
                        continue;
                    }
                    pushMessagesDict.put(mid, messageObject);
                    pushMessages.add(0, messageObject);
                    if (original_dialog_id != dialog_id) {
                        pushDialogsOverrideMention.put(original_dialog_id, 1);
                    }
                }
            }
            for (HashMap.Entry<Long, Integer> entry : dialogs.entrySet()) {
                long dialog_id = entry.getKey();
                Boolean value = settingsCache.get(dialog_id);
                if (value == null) {
                    int notifyOverride = getNotifyOverride(preferences, dialog_id);
                    Integer override = pushDialogsOverrideMention.get(dialog_id);
                    if (override != null && override == 1) {
                        pushDialogsOverrideMention.put(dialog_id, 0);
                        notifyOverride = 1;
                    }
                    value = !(notifyOverride == 2 || (!preferences.getBoolean("EnableAll", true)
                            || ((int) dialog_id < 0) && !preferences.getBoolean("EnableGroup", true))
                            && notifyOverride == 0);
                    settingsCache.put(dialog_id, value);
                }
                if (!value) {
                    continue;
                }
                int count = entry.getValue();
                pushDialogs.put(dialog_id, count);
                total_unread_count += count;
            }
            if (total_unread_count == 0) {
                AndroidUtilities.runOnUIThread(new Runnable() {
                    @Override
                    public void run() {
                        popupMessages.clear();
                        NotificationCenter.getInstance()
                                .postNotificationName(NotificationCenter.pushMessagesUpdated);
                    }
                });
            }
            showOrUpdateNotification(SystemClock.uptimeMillis() / 1000 < 60);

            if (preferences.getBoolean("badgeNumber", true)) {
                setBadge(total_unread_count);
            }
        }
    });
}