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.negaheno.android.NotificationsController.java

private void scheduleNotificationDelay(boolean onlineReason) {
    try {/*www.  j  av  a2  s  .  com*/
        FileLog.e("tmessages", "delay notification start");
        AlarmManager alarm = (AlarmManager) ApplicationLoader.applicationContext
                .getSystemService(Context.ALARM_SERVICE);
        PendingIntent pintent = PendingIntent.getService(ApplicationLoader.applicationContext, 0,
                new Intent(ApplicationLoader.applicationContext, NotificationDelay.class), 0);
        SharedPreferences preferences = ApplicationLoader.applicationContext
                .getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
        if (onlineReason) {
            alarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 3 * 1000, pintent);
        } else {
            alarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 500, pintent);
        }
    } catch (Exception e) {
        FileLog.e("tmessages", e);
    }
}

From source file:com.google.android.exoplayer2.ext.mediasession.MediaSessionConnector.java

private void updateMediaSessionPlaybackState() {
    PlaybackStateCompat.Builder builder = new PlaybackStateCompat.Builder();
    if (player == null) {
        builder.setActions(buildPlaybackActions()).setState(PlaybackStateCompat.STATE_NONE, 0, 0, 0);
        mediaSession.setPlaybackState(builder.build());
        return;/*from   w w  w . ja  va2  s. c  o m*/
    }

    Map<String, CustomActionProvider> currentActions = new HashMap<>();
    for (CustomActionProvider customActionProvider : customActionProviders) {
        PlaybackStateCompat.CustomAction customAction = customActionProvider.getCustomAction();
        if (customAction != null) {
            currentActions.put(customAction.getAction(), customActionProvider);
            builder.addCustomAction(customAction);
        }
    }
    customActionMap = Collections.unmodifiableMap(currentActions);

    int sessionPlaybackState = playbackException != null ? PlaybackStateCompat.STATE_ERROR
            : mapPlaybackState(player.getPlaybackState(), player.getPlayWhenReady());
    if (playbackException != null) {
        if (errorMessageProvider != null) {
            Pair<Integer, String> message = errorMessageProvider.getErrorMessage(playbackException);
            builder.setErrorMessage(message.first, message.second);
        }
        if (player.getPlaybackState() != Player.STATE_IDLE) {
            playbackException = null;
        }
    }
    long activeQueueItemId = queueNavigator != null ? queueNavigator.getActiveQueueItemId(player)
            : MediaSessionCompat.QueueItem.UNKNOWN_ID;
    Bundle extras = new Bundle();
    extras.putFloat(EXTRAS_PITCH, player.getPlaybackParameters().pitch);
    builder.setActions(buildPlaybackActions()).setActiveQueueItemId(activeQueueItemId)
            .setBufferedPosition(player.getBufferedPosition())
            .setState(sessionPlaybackState, player.getCurrentPosition(), player.getPlaybackParameters().speed,
                    SystemClock.elapsedRealtime())
            .setExtras(extras);
    mediaSession.setPlaybackState(builder.build());
}

From source file:com.t2.compassionMeditation.Graphs1Activity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.i(TAG, this.getClass().getSimpleName() + ".onCreate()");

    // We don't want the screen to timeout in this activity
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

    this.requestWindowFeature(Window.FEATURE_NO_TITLE); // This needs to happen BEFORE setContentView
    setContentView(R.layout.graphs_activity_layout);
    mInstance = this;

    sharedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    mLoggingEnabled = SharedPref.getBoolean(this, "enable_logging", true);
    mDatabaseEnabled = SharedPref.getBoolean(this, "database_enabled", false);
    mAntHrmEnabled = SharedPref.getBoolean(this, "enable_ant_hrm", false);

    mInternalSensorMonitoring = SharedPref.getBoolean(this, "inernal_sensor_monitoring_enabled", false);

    if (mAntHrmEnabled) {
        mHeartRateSource = HEARTRATE_ANT;
    } else {//from w  w  w .  j a v  a  2 s .co m
        mHeartRateSource = HEARTRATE_ZEPHYR;
    }

    // The session start time will be used as session id
    // Note this also sets session start time
    // **** This session ID will be prepended to all JSON data stored
    //      in the external database until it's changed (by the start
    //      of a new session.
    Calendar cal = Calendar.getInstance();
    SharedPref.setBioSessionId(sharedPref, cal.getTimeInMillis());

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.US);
    String sessionDate = sdf.format(new Date());
    String userId = SharedPref.getString(this, "SelectedUser", "");
    long sessionId = SharedPref.getLong(this, "bio_session_start_time", 0);

    mDataOutHandler = new DataOutHandler(this, userId, sessionDate, mAppId,
            DataOutHandler.DATA_TYPE_EXTERNAL_SENSOR, sessionId);

    if (mDatabaseEnabled) {
        TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
        String myNumber = telephonyManager.getLine1Number();

        String remoteDatabaseUri = SharedPref.getString(this, "database_sync_name",
                getString(R.string.database_uri));
        //            remoteDatabaseUri += myNumber; 

        Log.d(TAG, "Initializing database at " + remoteDatabaseUri); // TODO: remove
        try {
            mDataOutHandler.initializeDatabase(dDatabaseName, dDesignDocName, dDesignDocId, byDateViewName,
                    remoteDatabaseUri);
        } catch (DataOutHandlerException e) {
            Log.e(TAG, e.toString());
            e.printStackTrace();
        }
        mDataOutHandler.setRequiresAuthentication(false);

    }

    mBioDataProcessor.initialize(mDataOutHandler);

    if (mLoggingEnabled) {
        mDataOutHandler.enableLogging(this);
    }

    if (mLogCatEnabled) {
        mDataOutHandler.enableLogCat();
    }

    // Log the version
    try {
        PackageManager packageManager = getPackageManager();
        PackageInfo info = packageManager.getPackageInfo(getPackageName(), 0);
        mApplicationVersion = info.versionName;
        String versionString = mAppId + " application version: " + mApplicationVersion;

        DataOutPacket packet = new DataOutPacket();
        packet.add(DataOutHandlerTags.version, versionString);
        try {
            mDataOutHandler.handleDataOut(packet);
        } catch (DataOutHandlerException e) {
            Log.e(TAG, e.toString());
            e.printStackTrace();
        }

    } catch (NameNotFoundException e) {
        Log.e(TAG, e.toString());
    }

    // Set up UI elements
    Resources resources = this.getResources();
    AssetManager assetManager = resources.getAssets();

    mPauseButton = (Button) findViewById(R.id.buttonPause);
    mAddMeasureButton = (Button) findViewById(R.id.buttonAddMeasure);
    mTextInfoView = (TextView) findViewById(R.id.textViewInfo);
    mMeasuresDisplayText = (TextView) findViewById(R.id.measuresDisplayText);

    // Don't actually show skin conductance meter unless we get samples
    ImageView image = (ImageView) findViewById(R.id.imageView1);
    image.setImageResource(R.drawable.signal_bars0);

    // Check to see of there a device configured for EEG, if so then show the skin conductance meter
    String tmp = SharedPref.getString(this, "EEG", null);

    if (tmp != null) {
        image.setVisibility(View.VISIBLE);
    } else {
        image.setVisibility(View.INVISIBLE);
    }

    // Initialize SPINE by passing the fileName with the configuration properties
    try {
        mManager = SPINEFactory.createSPINEManager("SPINETestApp.properties", resources);
    } catch (InstantiationException e) {
        Log.e(TAG, "Exception creating SPINE manager: " + e.toString());
        e.printStackTrace();
    }

    try {
        currentMindsetData = new MindsetData(this);
    } catch (Exception e1) {
        Log.e(TAG, "Exception creating MindsetData: " + e1.toString());
        e1.printStackTrace();
    }

    // Establish nodes for BSPAN

    // Create a broadcast receiver. Note that this is used ONLY for command messages from the service
    // All data from the service goes through the mail SPINE mechanism (received(Data data)).
    // See public void received(Data data)
    this.mCommandReceiver = new SpineReceiver(this);

    int itemId = 0;
    eegPos = itemId; // eeg always comes first
    mBioParameters.clear();

    // First create GraphBioParameters for each of the EEG static params (ie mindset)
    for (itemId = 0; itemId < MindsetData.NUM_BANDS + 2; itemId++) { // 2 extra, for attention and meditation
        GraphBioParameter param = new GraphBioParameter(itemId, MindsetData.spectralNames[itemId], "", true);
        param.isShimmer = false;
        mBioParameters.add(param);
    }

    // Now create all of the potential dynamic GBraphBioParameters (GSR, EMG, ECG, EEG, HR, Skin Temp, Resp Rate
    //       String[] paramNamesStringArray = getResources().getStringArray(R.array.parameter_names);
    String[] paramNamesStringArray = getResources().getStringArray(R.array.parameter_names_less_eeg);

    for (String paramName : paramNamesStringArray) {
        if (paramName.equalsIgnoreCase("not assigned"))
            continue;

        GraphBioParameter param = new GraphBioParameter(itemId, paramName, "", true);

        if (paramName.equalsIgnoreCase("gsr")) {
            gsrPos = itemId;
            param.isShimmer = true;
            param.shimmerSensorConstant = SPINESensorConstants.SHIMMER_GSR_SENSOR;
            param.shimmerNode = getShimmerNode();
        }

        if (paramName.equalsIgnoreCase("emg")) {
            emgPos = itemId;
            param.isShimmer = true;
            param.shimmerSensorConstant = SPINESensorConstants.SHIMMER_EMG_SENSOR;
            param.shimmerNode = getShimmerNode();
        }

        if (paramName.equalsIgnoreCase("ecg")) {
            ecgPos = itemId;
            param.isShimmer = true;
            param.shimmerSensorConstant = SPINESensorConstants.SHIMMER_ECG_SENSOR;
            param.shimmerNode = getShimmerNode();
        }

        if (paramName.equalsIgnoreCase("heart rate")) {
            heartRatePos = itemId;
            param.isShimmer = false;
        }

        if (paramName.equalsIgnoreCase("resp rate")) {
            respRatePos = itemId;
            param.isShimmer = false;
        }

        if (paramName.equalsIgnoreCase("skin temp")) {
            skinTempPos = itemId;
            param.isShimmer = false;
        }

        if (paramName.equalsIgnoreCase("EHealth Airflow")) {
            eHealthAirFlowPos = itemId;
            param.isShimmer = false;
        }

        if (paramName.equalsIgnoreCase("EHealth Temp")) {
            eHealthTempPos = itemId;
            param.isShimmer = false;
        }

        if (paramName.equalsIgnoreCase("EHealth SpO2")) {
            eHealthSpO2Pos = itemId;
            param.isShimmer = false;
        }

        if (paramName.equalsIgnoreCase("EHealth Heartrate")) {
            eHealthHeartRatePos = itemId;
            param.isShimmer = false;
        }

        if (paramName.equalsIgnoreCase("EHealth GSR")) {
            eHealthGSRPos = itemId;
            param.isShimmer = false;
        }

        itemId++;
        mBioParameters.add(param);
    }

    // Since These are static nodes (Non-spine) we have to manually put them in the active node list
    Node mindsetNode = null;
    mindsetNode = new Node(new Address("" + Constants.RESERVED_ADDRESS_MINDSET)); // Note that the sensor id 0xfff1 (-15) is a reserved id for this particular sensor
    mManager.getActiveNodes().add(mindsetNode);

    Node zepherNode = null;
    zepherNode = new Node(new Address("" + Constants.RESERVED_ADDRESS_ZEPHYR));
    mManager.getActiveNodes().add(zepherNode);

    // The arduino node is programmed to look like a static Spine node
    // Note that currently we don't have  to turn it on or off - it's always streaming
    // Since Spine (in this case) is a static node we have to manually put it in the active node list
    // Since the 
    final int RESERVED_ADDRESS_ARDUINO_SPINE = 1; // 0x0001
    mSpineNode = new Node(new Address("" + RESERVED_ADDRESS_ARDUINO_SPINE));
    mManager.getActiveNodes().add(mSpineNode);

    final String sessionName;

    // Check to see if we were requested to play back a previous session
    try {
        Bundle bundle = getIntent().getExtras();

        if (bundle != null) {
            sessionName = bundle.getString(BioZenConstants.EXTRA_SESSION_NAME);

            AlertDialog.Builder alert = new AlertDialog.Builder(this);
            alert.setTitle("Replay Session " + sessionName + "?");
            alert.setMessage("Make sure to turn off all Bluetooth Sensors!");

            alert.setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {

                    try {
                        mDataOutHandler.logNote("Replaying data from session " + sessionName);
                    } catch (DataOutHandlerException e) {
                        Log.e(TAG, e.toString());
                        e.printStackTrace();
                    }

                    replaySessionData(sessionName);
                    AlertDialog.Builder alert1 = new AlertDialog.Builder(mInstance);
                    alert1.setTitle("INFO");
                    alert1.setMessage("Replay of session complete!");
                    alert1.show();

                }
            });
            alert.show();
        }

    } catch (Exception e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
    }

    if (mInternalSensorMonitoring) {
        // IntentSender Launches our service scheduled with with the alarm manager 
        mBigBrotherService = PendingIntent.getService(Graphs1Activity.this, 0,
                new Intent(Graphs1Activity.this, BigBrotherService.class), 0);

        long firstTime = SystemClock.elapsedRealtime();
        // Schedule the alarm!
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
        am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, mPollingPeriod * 1000,
                mBigBrotherService);

        // Tell the user about what we did.
        Toast.makeText(Graphs1Activity.this, R.string.service_scheduled, Toast.LENGTH_LONG).show();

    }

    //testFIRFilter();

    //       testHR();

}

From source file:com.stasbar.knowyourself.Utils.java

public static long now() {
    return SystemClock.elapsedRealtime();
}

From source file:de.ub0r.android.websms.WebSMSReceiver.java

/**
 * Schedules resend of a message.//from  www  . j  av  a  2 s .  c  o m
 *
 * @param context context
 * @param specs   {@link de.ub0r.android.websms.connector.common.ConnectorSpec}
 * @param command {@link de.ub0r.android.websms.connector.common.ConnectorCommand}
 */
private static void scheduleMessageResend(final Context context, final ConnectorSpec specs,
        final ConnectorCommand command) {

    long msgId = command.getMsgId();

    final Intent resendIntent = new Intent(Connector.ACTION_RESEND);
    command.setToIntent(resendIntent);
    specs.setToIntent(resendIntent);

    AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + RESEND_DELAY_MS,
            PendingIntent.getBroadcast(context, (int) msgId, resendIntent, PendingIntent.FLAG_CANCEL_CURRENT));
}

From source file:com.example.cody.tapwater.activities.MainActivity.java

@Override
public void onResume() {
    super.onResume();
    System.out.println("Alarm manager setup");
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
    String prompts = prefs.getString("prompts", "5");
    String beginStr = prefs.getString("begin_time", "");
    String endStr = prefs.getString("end_time", "");
    Calendar beginCal = Calendar.getInstance();
    Calendar endCal = Calendar.getInstance();
    try {/* w  w  w . j a  v  a 2 s  .com*/
        beginCal.setTime(sdf.parse(beginStr));
        endCal.setTime(sdf.parse(endStr));
    } catch (ParseException e) {
        e.printStackTrace();
    }
    long interval = notificationIntervalCalculation(Integer.valueOf(prompts), beginCal, endCal);
    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
    Intent i = new Intent(context, NotificationService.class);
    PendingIntent pi = PendingIntent.getService(context, 0, i, 0);
    am.cancel(pi);

    // by my own convention, minutes <= 0 means notifications are disabled
    if (interval > 0) {
        am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + interval,
                interval, pi);
    }
}

From source file:com.gelakinetic.mtgfam.activities.MainActivity.java

@Override
protected void onDestroy() {
    super.onDestroy();
    try {/* ww w .j  a  va 2s.c o m*/
        unregisterReceiver(endTimeReceiver);
        unregisterReceiver(startTimeReceiver);
        unregisterReceiver(cancelTimeReceiver);

        if (endTime > SystemClock.elapsedRealtime()) {
            //Timer Active
        } else {
            Intent i = new Intent(this, RoundTimerService.class);
            stopService(i);
        }

    } catch (IllegalArgumentException e) {
        // EAT IT
    }
}

From source file:com.saulcintero.moveon.services.MoveOnService.java

public static void pausePractice() {
    pause = true;//from   w  w w  .  j ava 2 s.  com
    lengthChrono = SystemClock.elapsedRealtime();

    if (prefs.getInt("practice_display5",
            TypesOfPractices.BASIC_PRACTICE.getTypes()) == TypesOfPractices.HIIT_PRACTICE.getTypes())
        pausableCountDownTimer.pause();

    if (prefs.getBoolean("speak", false))
        TextToSpeechUtils.say(mContext, mContext.getString(R.string.tts_pause_practice));
}

From source file:com.saulcintero.moveon.services.MoveOnService.java

public static void resumePractice() {
    accumulatedTime = accumulatedTime + (((lengthChrono / 1000) - (elapsedRealtime / 1000)));
    elapsedRealtime = SystemClock.elapsedRealtime();
    pause = false;/* w  w w.j  a  v a2 s .c  o m*/
    resumelocations = true;

    if (prefs.getInt("practice_display5",
            TypesOfPractices.BASIC_PRACTICE.getTypes()) == TypesOfPractices.HIIT_PRACTICE.getTypes())
        pausableCountDownTimer.resume();

    if (prefs.getBoolean("speak", false))
        TextToSpeechUtils.say(mContext, mContext.getString(R.string.tts_resume_practice));
}