Example usage for android.os SystemClock elapsedRealtime

List of usage examples for android.os SystemClock elapsedRealtime

Introduction

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

Prototype

@CriticalNative
native public static long elapsedRealtime();

Source Link

Document

Returns milliseconds since boot, including time spent in sleep.

Usage

From source file:com.android.im.imps.HttpDataChannel.java

@Override
public boolean resume() {
    long now = SystemClock.elapsedRealtime();
    if (now - mLastActive > mKeepAliveMillis) {
        shutdown();//from  w w w.  ja va  2 s . c o m
        return false;
    } else {
        mSuspended = false;

        // Send a polling request after resume in case we missed some
        // updates while we are suspended.
        Primitive polling = new Primitive(ImpsTags.Polling_Request);
        polling.setSession(mConnection.getSession().getID());
        sendPrimitive(polling);
        startHeartbeat();

        return true;
    }
}

From source file:com.example.android.supportv7.media.LocalPlayer.java

@Override
public void getStatus(final PlaylistItem item, final boolean update) {
    if (mState == STATE_PLAYING || mState == STATE_PAUSED) {
        // use mSeekToPos if we're currently seeking (mSeekToPos is reset
        // when seeking is completed)
        item.setDuration(mMediaPlayer.getDuration());
        item.setPosition(mSeekToPos > 0 ? mSeekToPos : mMediaPlayer.getCurrentPosition());
        item.setTimestamp(SystemClock.elapsedRealtime());
    }//from w w  w .j  a  v a2 s  .c  om
    if (update && mCallback != null) {
        mCallback.onPlaylistReady();
    }
}

From source file:com.example.isaac.nileswestlitcenter.GcmIntentService.java

@Override
protected void onHandleIntent(Intent intent) {
    Bundle extras = intent.getExtras();// w  ww.  j a  va  2  s. co  m
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
    // The getMessageType() intent parameter must be the intent you received
    // in your BroadcastReceiver.
    String messageType = gcm.getMessageType(intent);

    if (!extras.isEmpty()) { // has effect of unparcelling Bundle
        /*
         * Filter messages based on message type. Since it is likely that GCM will be
         * extended in the future with new message types, just ignore any message types you're
         * not interested in, or that you don't recognize.
         */
        if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {

        } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {

            // If it's a regular GCM message, do some work.
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
            // This loop represents the service doing some work.

        }
        if (extras.getString("subject") != null) {
            if (intent.getExtras().getString("delete") != null) {
                if (((KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE))
                        .inKeyguardRestrictedInputMode()) {
                    //delete from arraylist
                    for (int i = 0; i < storeWhileScreenOff.size(); i++) {
                        if (storeWhileScreenOff.get(i)[1] == extras.getString("subject")
                                && storeWhileScreenOff.get(i)[2] == extras.getString("name")) {
                            storeWhileScreenOff.remove(i);
                            return;
                        }
                    }
                    //not in stored list, but on screen
                    storeWhileScreenOff.add(
                            new String[] { "true", extras.getString("subject"), extras.getString("name") });
                } else {
                    sendMessage(true, extras.getString("subject"), extras.getString("name"));
                    //                    MainActivity.deleteStudentFromList(extras.getString("subject"),extras.getString("name"));
                    //                   or MainActivity.delete(extras.getInt("id"));
                }
            } else {
                if (((KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE))
                        .inKeyguardRestrictedInputMode()) {
                    storeWhileScreenOff.add(
                            new String[] { "false", extras.getString("subject"), extras.getString("name") });
                } else {
                    sendMessage(false, extras.getString("subject"), extras.getString("name"));
                }
                Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
                // Post notification of received message.
                sendNotification(extras.getString("subject"), extras.getString("name"));
                Vibrator v = (Vibrator) this.getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
                // Vibrate for 500 milliseconds
                v.vibrate(1000);
                ((PowerManager) getSystemService(POWER_SERVICE))
                        .newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP,
                                "TAG")
                        .acquire();
                Log.i(TAG, "Received: " + extras.toString());

            }

        }
    }

    // Release the wake lock provided by the WakefulBroadcastReceiver.
    GcmBroadcastReceiver.completeWakefulIntent(intent);
}

From source file:com.nextgis.ngm_clink_monitoring.fragments.StatusBarFragment.java

@Override
public void onGpsStatusChanged(int event) {
    switch (event) {
    case GpsStatus.GPS_EVENT_SATELLITE_STATUS:

        GISApplication app = (GISApplication) getActivity().getApplication();

        if (app.getCurrentLocation() != null) {
            mIsGPSFix = (SystemClock.elapsedRealtime() - mLastLocationMillis) < 10000;
        }//  w  ww .  j a va 2s. c  om

        if (!mIsGPSFix) { // The fix has been lost.
            setLocationDefaultText();
            mDistView.setTextColor(Color.BLACK);

            if (isVisible()) {
                setLocationViewsText();
            }
        }

        break;

    case GpsStatus.GPS_EVENT_FIRST_FIX:
        mIsGPSFix = true;
        break;
    }
}

From source file:com.group13.androidsdk.mycards.NotificationService.java

private void rescheduleNotifications() {

    List<NotificationRule> rules = new ArrayList<>();
    Collections.addAll(rules, MyCardsDBManager.getInstance(this).getAllNotificationRules());
    rules.addAll(getCalendarAsNotificationRules());

    SharedPreferences prefs = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
    long lastNotifMillis = prefs.getLong("lastNotifElapsedRealtime", -2 * FIFTEEN_MINUTES);
    SharedPreferences.Editor prefEditor = prefs.edit();

    MyCardsDBManager dbm = MyCardsDBManager.getInstance(this);
    if (!(Math.abs(lastNotifMillis - SystemClock.elapsedRealtime()) < FIFTEEN_MINUTES || dbm.getDoNotDisturb()
            || dateMatchesAnyRule(new Date(), rules)
            || dbm.getCardsForReviewBefore(new Date(), null).length == 0)) {
        lastNotifMillis = SystemClock.elapsedRealtime();
        prefEditor.putLong("lastNotifElapsedRealtime", lastNotifMillis);

        sendNotification();//  w w w  . j av  a2s . c  o m
    }

    Intent intent = new Intent(this, NotificationService.class);
    PendingIntent pi = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + FIFTEEN_MINUTES, pi);

    prefEditor.putLong("lastRunElapsedRealtime", SystemClock.elapsedRealtime());
    prefEditor.apply();
}

From source file:com.appsaur.tarucassist.AlarmReceiver.java

public void setRepeatAlarm(Context context, Calendar calendar, int ID, long RepeatTime) {
    mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    // Put Reminder ID in Intent Extra
    Intent intent = new Intent(context, AlarmReceiver.class);
    intent.putExtra(BaseActivity.EXTRA_REMINDER_ID, Integer.toString(ID));
    mPendingIntent = PendingIntent.getBroadcast(context, ID, intent, PendingIntent.FLAG_CANCEL_CURRENT);

    // Calculate notification timein
    Calendar c = Calendar.getInstance();
    long currentTime = c.getTimeInMillis();
    long diffTime = calendar.getTimeInMillis() - currentTime;

    // Start alarm using initial notification time and repeat interval time
    mAlarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + diffTime,
            RepeatTime, mPendingIntent);

    // Restart alarm if device is rebooted
    ComponentName receiver = new ComponentName(context, BootReceiver.class);
    PackageManager pm = context.getPackageManager();
    pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
            PackageManager.DONT_KILL_APP);
}

From source file:com.google.android.gcm.demo.model.TaskTracker.java

/**
 * Execute this task, reporting any errors if this was an invalid execution.
 *//*from   w  ww. ja  va 2  s .  c o m*/
public void execute(LoggingService.Logger logger) {
    final long elapsedNowSecs = SystemClock.elapsedRealtime() / 1000;

    if (!cancelled) {
        if (executed && period == 0) {
            logger.log(Log.ERROR, "Attempt to execute one off task  " + tag + " multiple " + "times");
            return;
        } else {
            this.executed = true;
            this.executionTimes.add(elapsedNowSecs);
        }
    } else {
        logger.log(Log.ERROR, "Attempt to execute task  " + tag + " after it was cancelled");
        return;
    }

    // Handle periodic errors and one-offs differently.
    // We ignore drift outside this window. This could be a delay due to the JobScheduler/
    // AlarmManager, or we just don't care.
    final int driftAllowed = 10;
    if (period == 0) { // one-off task
        if (elapsedNowSecs > windowStopElapsedSecs + driftAllowed
                || elapsedNowSecs < windowStartElapsedSecs - driftAllowed) {
            logger.log(Log.ERROR, "Mistimed execution for task " + tag);
        } else {
            logger.log(Log.INFO, "Successfully executed one-off task " + tag);
        }
    } else { // periodic
        final int n = executionTimes.size(); // This is the nth execution
        if (elapsedNowSecs + driftAllowed < (createdAtElapsedSecs) + (n - 1) * this.period) {
            // Run too early.
            logger.log(Log.ERROR, "Mistimed execution for task " + tag + ": run too early");
        } else if (elapsedNowSecs - driftAllowed > (createdAtElapsedSecs) + n * period) {
            // Run too late.
            logger.log(Log.ERROR, "Mistimed execution for task " + tag + ": run too late");
        } else {
            logger.log(Log.INFO, "Successfully executed periodic task " + tag);
        }
    }
}

From source file:com.example.android.camera2video.CameraActivity.java

private static void logText(String text) {
    if (!mLogging)
        return;/*  w  ww.j  a  v a  2s  .com*/

    long tim = SystemClock.elapsedRealtime() - mLogTime;
    if (tim < 1000)
        return;

    try {
        mFileWriter.write(tim + "," + text + "\n");
    } catch (IOException e) {
        Log.e(TAG, "Logging failed:" + text);
        e.printStackTrace();
    }
}

From source file:com.handpoint.headstart.client.ui.LoginActivity.java

@Override
public void onClick(View v) {
    PasscodeFragment pf = (PasscodeFragment) getSupportFragmentManager().findFragmentById(R.id.password_layout);

    if (isPasswordValid(pf.getPassword())) {
        Intent resultIntent = new Intent();
        resultIntent.putExtra("password", pf.getPassword());
        setResult(RESULT_OK, resultIntent);
        setAttemptCount(0);/*from   www . j  av  a2  s.  c  o m*/
        setLastAttempt(0);
        finish();
    } else {
        setAttemptCount(getAttemptCount() + 1);
        if (getAttemptCount() > 2) {
            setAttemptCount(0);
            setLastAttempt(SystemClock.elapsedRealtime());
            Toast.makeText(this, getString(R.string.warn_wait_message, formatTime(ATTEMPT_DELAY)),
                    Toast.LENGTH_LONG).show();
            setResult(RESULT_CANCELED);
            finish();
            return;
        }
        Toast.makeText(this, R.string.warn_authentication_failed, Toast.LENGTH_SHORT).show();
        pf.resetPassword();
    }
}

From source file:alaindc.crowdroid.SensorsIntentService.java

@Override
protected void onHandleIntent(Intent intent) {
    if (intent != null) {
        final String action = intent.getAction();
        if (action.equals(Constants.INTENT_START_SENSORS)) {

            // Init throughput taken
            SharedPreferences sharedPref = getApplicationContext().getSharedPreferences(Constants.PREF_FILE,
                    Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putBoolean(Constants.THROUGHPUT_TAKEN, false);
            editor.commit();//from ww  w.  j a v a 2s.c om

            // Configure sensors and eventlistener
            mSensorManager = (SensorManager) getApplicationContext().getSystemService(Context.SENSOR_SERVICE);
            List<Sensor> sensorList = mSensorManager.getSensorList(Sensor.TYPE_ALL);
            for (Sensor sensor : sensorList) {
                if (Constants.isInMonitoredSensors(sensor.getType()))
                    mSensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL);
            }

            // TODO STUB: Comment this in release
            for (int type : Constants.STUBBED_MONITORED_SENSORS) {
                stub_onSensorChanged(type);
            }

        }

        if (action.equals(Constants.INTENT_START_AUDIOAMPLITUDE_SENSE)) {
            // Configure amplitude and start TEST
            amplitudeTask = new GetAmplitudeTask(this);
            amplitudeTask.getData();
        }

        if (action.equals(Constants.INTENT_STUB_SENSOR_CHANGED + Sensor.TYPE_AMBIENT_TEMPERATURE)) {
            stub_onSensorChanged(intent.getIntExtra(Constants.INTENT_STUB_SENSOR_CHANGED_TYPE, -1));
        }

        if (action.equals(Constants.INTENT_STUB_SENSOR_CHANGED + Sensor.TYPE_PRESSURE)) {
            stub_onSensorChanged(intent.getIntExtra(Constants.INTENT_STUB_SENSOR_CHANGED_TYPE, -1));
        }

        if (action.equals(Constants.INTENT_STUB_SENSOR_CHANGED + Sensor.TYPE_RELATIVE_HUMIDITY)) {
            stub_onSensorChanged(intent.getIntExtra(Constants.INTENT_STUB_SENSOR_CHANGED_TYPE, -1));
        }

        if (action.equals(Constants.INTENT_RECEIVED_AMPLITUDE)) {
            double amplitude = intent.getDoubleExtra(Constants.EXTRA_AMPLITUDE, -1);

            if (amplitude > 0) {
                SharedPreferences sharedPref = getApplicationContext().getSharedPreferences(Constants.PREF_FILE,
                        Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPref.edit();
                editor.putString(Constants.PREF_SENSOR_ + Constants.TYPE_AMPLITUDE, Double.toString(amplitude));
                editor.commit();

                // Update view
                Intent senseintent = new Intent(Constants.INTENT_UPDATE_SENSORS);
                senseintent.putExtra(Constants.INTENT_RECEIVED_DATA_EXTRA_DATA,
                        "Sensor " + Constants.getNameOfSensor(Constants.TYPE_AMPLITUDE) + " value: "
                                + Double.toString(amplitude));
                LocalBroadcastManager.getInstance(this).sendBroadcast(senseintent);
            }

            int index = Constants.getIndexAlarmForSensor(Constants.TYPE_AMPLITUDE);

            // Set the alarms for next sensing of amplitude
            alarmMgr = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
            Intent intentAlarm = new Intent(getApplicationContext(), SensorsIntentService.class);
            intentAlarm.setAction(Constants.INTENT_START_AUDIOAMPLITUDE_SENSE);
            alarmIntent = PendingIntent.getService(getApplicationContext(), 0, intentAlarm, 0);

            // TIMEOUT for another monitoring of audio
            int seconds = 30; // TODO: De-hardcode this
            alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + seconds * 1000,
                    alarmIntent);

        }
    }
}