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.bayapps.android.robophish.ui.tv.TvPlaybackFragment.java

protected void startProgressAutomation() {
    if (mHandler != null && mRunnable != null) {
        mHandler.removeCallbacks(mRunnable);
    }/*from w  w w . ja  v  a  2  s . co  m*/
    mRunnable = new Runnable() {
        @Override
        public void run() {
            long elapsedTime = SystemClock.elapsedRealtime() - mLastPositionUpdateTime;
            int currentPosition = Math.min(mDuration, (int) (mLastPosition + elapsedTime));
            mPlaybackControlsRow.setCurrentTime(currentPosition);
            mHandler.postDelayed(this, getUpdatePeriod());
        }
    };
    mHandler.postDelayed(mRunnable, getUpdatePeriod());
    setFadingEnabled(true);
}

From source file:android.support.v7.media.MediaItemStatus.java

@Override
public String toString() {
    StringBuilder result = new StringBuilder();
    result.append("MediaItemStatus{ ");
    result.append("timestamp=");
    TimeUtils.formatDuration(SystemClock.elapsedRealtime() - getTimestamp(), result);
    result.append(" ms ago");
    result.append(", playbackState=").append(playbackStateToString(getPlaybackState()));
    result.append(", contentPosition=").append(getContentPosition());
    result.append(", contentDuration=").append(getContentDuration());
    result.append(", extras=").append(getExtras());
    result.append(" }");
    return result.toString();
}

From source file:com.yanzhenjie.album.fragment.AlbumFragment.java

@Override
protected void onCameraBack(String imagePath) {
    // Add media lib.
    if (mMediaScanner == null) {
        mMediaScanner = new MediaScanner(getContext());
    }/* w  w w.  j  a  va  2  s .  c  o  m*/
    mMediaScanner.scan(imagePath);

    String name = new File(imagePath).getName();
    AlbumImage image = new AlbumImage(0, imagePath, name, SystemClock.elapsedRealtime());
    image.setChecked(true);

    mCheckedImages.add(image);
    setCheckedCountUI(mCheckedImages.size());

    List<AlbumImage> images = mAlbumFolders.get(0).getImages();
    if (images.size() > 0) {
        images.add(0, image);

        if (mCurrentFolderPosition == 0) {
            mAlbumContentAdapter.notifyItemInserted(mHasCamera ? 1 : 0);
        } else
            showImageFromFolder(0);
    } else {
        images.add(image);
        showImageFromFolder(0);
    }
}

From source file:com.cypress.cysmart.BLEServiceFragments.CSCService.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.cyclingspeed_n_cadence, container, false);
    mDistanceRan = (TextView) rootView.findViewById(R.id.cycling_distance);
    mCadence = (TextView) rootView.findViewById(R.id.cadence);
    mCaloriesBurnt = (TextView) rootView.findViewById(R.id.calories_burnt);
    mTimer = (Chronometer) rootView.findViewById(R.id.time_counter);
    mWeightEdittext = (EditText) rootView.findViewById(R.id.weight_data);
    mWeightEdittext.setRawInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
    mWeightEdittext.addTextChangedListener(new DecimalTextWatcher(mWeightEdittext));
    mProgressDialog = new ProgressDialog(getActivity());

    // Setting up chart
    setupChart(rootView);//from w  w  w. j ava2  s. c  o  m

    // Start/Stop listener
    Button start_stop_btn = (Button) rootView.findViewById(R.id.start_stop_btn);
    start_stop_btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Button btn = (Button) v;
            String buttonText = btn.getText().toString();
            String startText = getResources().getString(R.string.blood_pressure_start_btn);
            String stopText = getResources().getString(R.string.blood_pressure_stop_btn);
            weightString = mWeightEdittext.getText().toString();

            if (weightString.equalsIgnoreCase("")) {
                weightInt = 0;
                if (buttonText.equalsIgnoreCase(startText)) {
                    Toast.makeText(getActivity(), getResources().getString(R.string.csc_weight_toast_empty),
                            Toast.LENGTH_SHORT).show();
                    mCaloriesBurnt.setText("0.00");
                }
            }

            if (weightString.equalsIgnoreCase(".") || weightString.equalsIgnoreCase("0.")
                    || weightString.equalsIgnoreCase("0")) {
                weightInt = 0;
                if (buttonText.equalsIgnoreCase(startText)) {
                    Toast.makeText(getActivity(), getResources().getString(R.string.csc_weight_toast_empty),
                            Toast.LENGTH_SHORT).show();
                }
            }

            if (weightInt <= 1.0 && weightInt != 0) {
                if (buttonText.equalsIgnoreCase(startText)) {
                    Toast.makeText(getActivity(), getResources().getString(R.string.csc_weight_toast_zero),
                            Toast.LENGTH_SHORT).show();
                    mCaloriesBurnt.setText("0.00");
                }
            }

            if (weightInt <= 200) {
                if (buttonText.equalsIgnoreCase(startText)) {
                    btn.setText(stopText);
                    mCaloriesBurnt.setText("0.00");
                    mWeightEdittext.setEnabled(false);
                    if (mNotifyCharacteristic != null) {
                        stopBroadcastDataNotify(mNotifyCharacteristic);

                    }
                    getGattData();
                    mTimer.start();
                    mTimer.setBase(SystemClock.elapsedRealtime());
                    mTimer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
                        @Override
                        public void onChronometerTick(Chronometer chronometer) {
                            showCaloriesBurnt();
                        }
                    });
                } else {
                    mWeightEdittext.setEnabled(true);
                    btn.setText(startText);
                    stopBroadcastDataNotify(mNotifyCharacteristic);
                    mTimer.stop();
                }
            } else {
                if (buttonText.equalsIgnoreCase(startText)) {
                    Toast.makeText(getActivity(), getResources().getString(R.string.csc_weight_toast_greater),
                            Toast.LENGTH_SHORT).show();
                    btn.setText(stopText);
                    mCaloriesBurnt.setText("0.00");
                    mWeightEdittext.setEnabled(false);
                    if (mNotifyCharacteristic != null) {
                        stopBroadcastDataNotify(mNotifyCharacteristic);
                    }
                    getGattData();
                    mTimer.start();
                    mTimer.setBase(SystemClock.elapsedRealtime());
                    mTimer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
                        @Override
                        public void onChronometerTick(Chronometer chronometer) {
                            showCaloriesBurnt();
                        }
                    });
                } else {
                    mWeightEdittext.setEnabled(true);
                    btn.setText(startText);
                    stopBroadcastDataNotify(mNotifyCharacteristic);
                    mCaloriesBurnt.setText("0.00");
                    mTimer.stop();
                }
            }

        }
    });
    setHasOptionsMenu(true);
    return rootView;
}

From source file:com.sublimis.urgentcallfilter.Magic.java

private void insertSetRingDuration() {
    long currentTime = SystemClock.elapsedRealtime();

    if (mData != null && mData.length() > 0) {
        int i = mData.length() - 1;

        JSONObject flame = jsonGetObject(mData, i);

        if (flame != null) {
            long timestamp = jsonGetLong(flame, jsonTimestampKey, 0);
            long ringDurationOld = jsonGetLong(flame, jsonRingDurationKey, 0);

            if (timestamp + Config.maxRingDuration > currentTime) {
                if (ringDurationOld <= 0) {
                    jsonPutLong(flame, jsonRingDurationKey, currentTime - timestamp);

                    try {
                        mData.put(i, flame);
                    } catch (Exception e) {
                    }/*from w  w  w  . j a  va 2 s  .co  m*/
                }
            }
        }
    }
}

From source file:alaindc.crowdroid.SendIntentService.java

private void handleActionReceivedData(String response) {

    // Data got from server response
    int timeout; // sec
    double radius; // meters
    int sensor;//from  w ww  .jav  a2s. co m
    double latitude, longitude;

    // Update view sending a broadcast intent
    Intent intent = new Intent(Constants.INTENT_RECEIVED_DATA);
    intent.putExtra(Constants.INTENT_RECEIVED_DATA_EXTRA_DATA, response);
    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

    try {
        JSONArray jsonArray = new JSONArray(response);
        JSONObject jsonObject = jsonArray.getJSONObject(0);

        sensor = jsonObject.getInt("sensor");
        // For time homogeneity
        timeout = jsonObject.getInt("timeout");
        // For space homogeneity
        radius = jsonObject.getDouble("radius");
        latitude = jsonObject.getDouble("lat");
        longitude = jsonObject.getDouble("long");

    } catch (JSONException e) {
        return;
    }

    if (sensor == Constants.TYPE_TEL) {
        SharedPreferences sharedPref = getApplicationContext().getSharedPreferences(Constants.PREF_FILE,
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putBoolean(Constants.THROUGHPUT_TAKEN, false);
        editor.commit();
    }

    Intent geofenceIntent = new Intent(getApplicationContext(), GeofenceIntentService.class);
    geofenceIntent.putExtra(Constants.EXTRA_GEOFENCE_SENSORTYPE, sensor);
    geofenceIntent.putExtra(Constants.EXTRA_GEOFENCE_LATITUDE, latitude);
    geofenceIntent.putExtra(Constants.EXTRA_GEOFENCE_LONGITUDE, longitude);
    geofenceIntent.putExtra(Constants.EXTRA_GEOFENCE_RADIUS, String.valueOf(radius));
    geofenceIntent.putExtra(Constants.EXTRA_GEOFENCE_EXPIRE_MILLISEC, String.valueOf(timeout * 1000));
    getApplicationContext().startService(geofenceIntent);

    // Set timeout based on server response
    alarmMgr = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
    Intent intentAlarm = new Intent(getApplicationContext(), SendIntentService.class);
    intentAlarm.setAction(Constants.ACTION_SENDDATA + sensor);
    intentAlarm.putExtra(Constants.EXTRA_TYPE_OF_SENSOR_TO_SEND, sensor);
    alarmIntent = PendingIntent.getService(getApplicationContext(), 0, intentAlarm, 0);

    int seconds = timeout;
    alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + seconds * 1000,
            alarmIntent);
}

From source file:at.alladin.rmbt.android.test.RMBTLoopService.java

@Override
public void onCreate() {
    Log.d(TAG, "created");
    super.onCreate();

    partialWakeLock = ((PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE))
            .newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "RMBTLoopWakeLock");
    partialWakeLock.acquire();/* w  w  w .ja  va  2 s  .co  m*/

    alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    readConfig();

    geoLocation = new LocalGeoLocation(this);
    geoLocation.start();

    notificationBuilder = createNotificationBuilder();

    startForeground(NotificationIDs.LOOP_ACTIVE, notificationBuilder.build());
    final IntentFilter actionFilter = new IntentFilter(RMBTService.BROADCAST_TEST_FINISHED);
    actionFilter.addAction(RMBTService.BROADCAST_TEST_ABORTED);
    registerReceiver(receiver, actionFilter);

    final IntentFilter rmbtTaskActionFilter = new IntentFilter(RMBTTask.BROADCAST_TEST_START);
    registerReceiver(rmbtTaskReceiver, rmbtTaskActionFilter);

    final Intent alarmIntent = new Intent(ACTION_ALARM, null, this, getClass());
    alarm = PendingIntent.getService(this, 0, alarmIntent, 0);

    if (ConfigHelper.isLoopModeWakeLock(this)) {
        Log.d(TAG, "using dimWakeLock");
        dimWakeLock = ((PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE))
                .newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP
                        | PowerManager.ON_AFTER_RELEASE, "RMBTLoopDimWakeLock");
        dimWakeLock.acquire();

        final Intent wakeupAlarmIntent = new Intent(ACTION_WAKEUP_ALARM, null, this, getClass());
        wakeupAlarm = PendingIntent.getService(this, 0, wakeupAlarmIntent, 0);

        final long now = SystemClock.elapsedRealtime();
        alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, now + 10000, 10000, wakeupAlarm);
    }

    bindService(new Intent(getApplicationContext(), RMBTService.class), this, BIND_AUTO_CREATE);
}

From source file:com.onesignal.OneSignal.java

public static void init(Context context, String googleProjectNumber, String oneSignalAppId,
        NotificationOpenedHandler inNotificationOpenedHandler) {
    if (mInitBuilder == null)
        mInitBuilder = new OneSignal.Builder();

    osUtils = new OSUtils();

    deviceType = osUtils.getDeviceType();

    // START: Init validation
    try {//w w w  . jav a 2s .  c o  m
        UUID.fromString(oneSignalAppId);
    } catch (Throwable t) {
        Log(LOG_LEVEL.FATAL,
                "OneSignal AppId format is invalid.\nExample: 'b2f7f966-d8cc-11e4-bed1-df8f05be55ba'\n", t);
        return;
    }

    if ("b2f7f966-d8cc-11e4-bed1-df8f05be55ba".equals(oneSignalAppId)
            || "5eb5a37e-b458-11e3-ac11-000c2940e62c".equals(oneSignalAppId))
        Log(LOG_LEVEL.WARN,
                "OneSignal Example AppID detected, please update to your app's id found on OneSignal.com");

    if (deviceType == 1) {
        try {
            Double.parseDouble(googleProjectNumber);
            if (googleProjectNumber.length() < 8 || googleProjectNumber.length() > 16)
                throw new IllegalArgumentException(
                        "Google Project number (Sender_ID) should be a 10 to 14 digit number in length.");
        } catch (Throwable t) {
            Log(LOG_LEVEL.FATAL,
                    "Google Project number (Sender_ID) format is invalid. Please use the 10 to 14 digit number found in the Google Developer Console for your project.\nExample: '703322744261'\n",
                    t);
            subscribableStatus = -6;
        }

        try {
            Class.forName("com.google.android.gms.gcm.GoogleCloudMessaging");
        } catch (ClassNotFoundException e) {
            Log(LOG_LEVEL.FATAL,
                    "The GCM Google Play services client library was not found. Please make sure to include it in your project.",
                    e);
            subscribableStatus = -4;
        }
    }

    mGoogleProjectNumber = googleProjectNumber;

    try {
        Class.forName("android.support.v4.view.MenuCompat");
        try {
            Class.forName("android.support.v4.content.WakefulBroadcastReceiver");
            Class.forName("android.support.v4.app.NotificationManagerCompat");
        } catch (ClassNotFoundException e) {
            Log(LOG_LEVEL.FATAL,
                    "The included Android Support Library v4 is to old or incomplete. Please update your project's android-support-v4.jar to the latest revision.",
                    e);
            subscribableStatus = -5;
        }
    } catch (ClassNotFoundException e) {
        Log(LOG_LEVEL.FATAL,
                "Could not find the Android Support Library v4. Please make sure android-support-v4.jar has been correctly added to your project.",
                e);
        subscribableStatus = -3;
    }

    if (initDone) {
        if (context != null)
            appContext = context.getApplicationContext();

        if (inNotificationOpenedHandler != null)
            notificationOpenedHandler = inNotificationOpenedHandler;

        if (notificationOpenedHandler != null)
            fireCallbackForOpenedNotifications();

        return;
    }

    // END: Init validation
    boolean contextIsActivity = (context instanceof Activity);

    foreground = contextIsActivity;
    appId = oneSignalAppId;
    appContext = context.getApplicationContext();
    if (contextIsActivity)
        ActivityLifecycleHandler.curActivity = (Activity) context;
    else
        ActivityLifecycleHandler.nextResumeIsFirstActivity = true;
    notificationOpenedHandler = inNotificationOpenedHandler;
    lastTrackedTime = SystemClock.elapsedRealtime();

    OneSignalStateSynchronizer.initUserState(appContext);
    appContext.startService(new Intent(appContext, SyncService.class));

    if (android.os.Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB_MR2)
        ((Application) appContext).registerActivityLifecycleCallbacks(new ActivityLifecycleListener());
    else
        ActivityLifecycleListenerCompat.startListener();

    try {
        Class.forName("com.amazon.device.iap.PurchasingListener");
        trackAmazonPurchase = new TrackAmazonPurchase(appContext);
    } catch (ClassNotFoundException e) {
    }

    // Re-register user if the app id changed, this might happen when a dev is testing.
    String oldAppId = getSavedAppId();
    if (oldAppId != null) {
        if (!oldAppId.equals(appId)) {
            Log(LOG_LEVEL.DEBUG, "APP ID changed, clearing user id as it is no longer valid.");
            SaveAppId(appId);
            OneSignalStateSynchronizer.resetCurrentState();
        }
    } else
        SaveAppId(appId);

    if (foreground || getUserId() == null)
        startRegistrationOrOnSession();

    if (notificationOpenedHandler != null)
        fireCallbackForOpenedNotifications();

    if (TrackGooglePurchase.CanTrack(appContext))
        trackGooglePurchase = new TrackGooglePurchase(appContext);

    initDone = true;
}

From source file:com.cypress.cysmart.BLEServiceFragments.RSCService.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.runningspeed_n_cadence, container, false);
    mDistanceRan = (TextView) rootView.findViewById(R.id.running_distance);
    mAverageSpeed = (TextView) rootView.findViewById(R.id.running_speed);
    mCaloriesBurnt = (TextView) rootView.findViewById(R.id.calories_burnt);
    mTimer = (Chronometer) rootView.findViewById(R.id.time_counter);
    mWeightEdittext = (EditText) rootView.findViewById(R.id.weight_data);
    mWeightEdittext.setRawInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
    mWeightEdittext.addTextChangedListener(new DecimalTextWatcher(mWeightEdittext));
    mProgressDialog = new ProgressDialog(getActivity());

    // Setting up chart
    setupChart(rootView);//from   w w  w.jav  a  2  s. com

    // Start/Stop listener
    Button start_stop_btn = (Button) rootView.findViewById(R.id.start_stop_btn);
    start_stop_btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Button btn = (Button) v;
            String buttonText = btn.getText().toString();
            String startText = getResources().getString(R.string.blood_pressure_start_btn);
            String stopText = getResources().getString(R.string.blood_pressure_stop_btn);
            weightString = mWeightEdittext.getText().toString();
            if (weightString.equalsIgnoreCase("")) {
                weightInt = 0;
                if (buttonText.equalsIgnoreCase(startText)) {
                    Toast.makeText(getActivity(), getResources().getString(R.string.csc_weight_toast_empty),
                            Toast.LENGTH_SHORT).show();
                    mCaloriesBurnt.setText("0.00");
                }
            }

            if (weightString.equalsIgnoreCase(".") || weightString.equalsIgnoreCase("0.")
                    || weightString.equalsIgnoreCase("0")) {
                weightInt = 0;
                if (buttonText.equalsIgnoreCase(startText)) {
                    Toast.makeText(getActivity(), getResources().getString(R.string.csc_weight_toast_empty),
                            Toast.LENGTH_SHORT).show();
                }
            }

            if (weightInt <= 1.0 && weightInt != 0) {
                if (buttonText.equalsIgnoreCase(startText)) {
                    Toast.makeText(getActivity(), getResources().getString(R.string.csc_weight_toast_zero),
                            Toast.LENGTH_SHORT).show();
                    mCaloriesBurnt.setText("0.00");
                }
            }

            if (weightInt <= 200) {
                if (buttonText.equalsIgnoreCase(startText)) {
                    btn.setText(stopText);
                    mCaloriesBurnt.setText("0.00");
                    mWeightEdittext.setEnabled(false);
                    if (mNotifyCharacteristic != null) {
                        stopBroadcastDataNotify(mNotifyCharacteristic);
                    }
                    getGattData();
                    mTimer.start();
                    mTimer.setBase(SystemClock.elapsedRealtime());
                    mTimer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
                        @Override
                        public void onChronometerTick(Chronometer chronometer) {
                            showCaloriesBurnt();
                        }
                    });
                } else {
                    mWeightEdittext.setEnabled(true);
                    btn.setText(startText);
                    stopBroadcastDataNotify(mNotifyCharacteristic);
                    mTimer.stop();
                }
            } else {
                if (buttonText.equalsIgnoreCase(startText)) {
                    Toast.makeText(getActivity(), getResources().getString(R.string.csc_weight_toast_greater),
                            Toast.LENGTH_SHORT).show();
                    btn.setText(stopText);
                    mCaloriesBurnt.setText("0.00");
                    mWeightEdittext.setEnabled(false);
                    if (mNotifyCharacteristic != null) {
                        stopBroadcastDataNotify(mNotifyCharacteristic);

                    }
                    getGattData();
                    mTimer.start();
                    mTimer.setBase(SystemClock.elapsedRealtime());
                    mTimer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
                        @Override
                        public void onChronometerTick(Chronometer chronometer) {
                            showCaloriesBurnt();
                        }
                    });
                } else {
                    mWeightEdittext.setEnabled(true);
                    btn.setText(startText);
                    stopBroadcastDataNotify(mNotifyCharacteristic);
                    mCaloriesBurnt.setText("0.00");
                    mTimer.stop();
                }
            }

        }
    });
    setHasOptionsMenu(true);
    return rootView;
}

From source file:com.android.deskclock.data.TimerNotificationBuilderN.java

/**
 * @param timer the timer on which to base the chronometer display
 * @return the time at which the chronometer will/did reach 0:00 in realtime
 *///from   w ww  .jav  a  2 s . com
private static long getChronometerBase(Timer timer) {
    // The in-app timer display rounds *up* to the next second for positive timer values. Mirror
    // that behavior in the notification's Chronometer by padding in an extra second as needed.
    final long remaining = timer.getRemainingTime();
    final long adjustedRemaining = remaining < 0 ? remaining : remaining + SECOND_IN_MILLIS;

    // Chronometer will/did reach 0:00 adjustedRemaining milliseconds from now.
    return SystemClock.elapsedRealtime() + adjustedRemaining;
}