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.appsaur.tarucassist.AlarmReceiver.java

public void setAlarm(Context context, Calendar calendar, int ID) {
    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 time
    Calendar c = Calendar.getInstance();
    long currentTime = c.getTimeInMillis();
    long diffTime = calendar.getTimeInMillis() - currentTime;

    // Start alarm using notification time
    mAlarmManager.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + diffTime, 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.ap.mobile.services.GCMMessageListenerService.java

/**
 * Called when message is received.//from  www .  j a v  a 2  s . co m
 * 
 * @param from SenderID of the sender.
 * @param data Data bundle containing message data as key/value pairs. For
 *        Set of keys use data.keySet().
 */
// [START receive_message]
@Override
public void onMessageReceived(String from, Bundle data) {
    Log.i(TAG, "from=" + from);
    Log.i(TAG, "data=" + data.toString());
    String notificationType = data
            .getString(com.ap.common.models.http.HttpStatusConstants.NOTIFICATION_PROPERTY_NOTIFICATION_TYPE);
    String uuid = data.getString(com.ap.common.models.http.HttpStatusConstants.NOTIFICATION_PROPERTY_UUID);
    String careGiverUUID = data
            .getString(com.ap.common.models.http.HttpStatusConstants.NOTIFICATION_PROPERTY_CARE_GIVER_UUID);
    String careType = data
            .getString(com.ap.common.models.http.HttpStatusConstants.NOTIFICATION_PROPERTY_CARETYPE);
    Log.d(TAG, "notificationType: " + notificationType);
    Log.d(TAG, "uuid: " + uuid);
    Log.d(TAG, "careGiverUUID: " + careGiverUUID);
    Log.d(TAG, "careType: " + careType);
    if (careType != null && careType.equals(String.valueOf(CareType.CareRecipient.getCareTypeId()))) {
        CommandInfo commandInfo = new CommandInfo();
        commandInfo.setCommand(notificationType);
        commandInfo.setUuid(uuid);
        final Intent messageQueueIntent = new Intent(Constants.MESSAGE_COMMAND_QUEUE);
        messageQueueIntent.putExtra(Constants.MESSAGE_COMMAND, commandInfo);
        LocalBroadcastManager.getInstance(this.getApplicationContext()).sendBroadcast(messageQueueIntent);

        UserPreference userPreference = UserPreference.getCurrentUserPreference(this.getApplicationContext());
        if (userPreference == null) {
            return;
        }
        Log.i(TAG, "userPreference.uuid=" + userPreference.getUuid());
        Log.i(TAG, "uuid=" + uuid);
        if (notificationType.equalsIgnoreCase(NotificationType.START_SERVICE.name())
                && uuid.equals(userPreference.getUuid())) {
            if (!DefaultSafeSeniorMonitorService.isRunning()) {
                Log.i(TAG, "DefaultSafeSeniorMonitorService is not running.");
            }
            Intent safeSeniorMonitorServiceIntent = new Intent(this.getApplicationContext(),
                    DefaultSafeSeniorMonitorService.class);
            Log.i(TAG, "Starting safeSeniorServiceIntent @ " + SystemClock.elapsedRealtime());
            this.getApplicationContext().startService(safeSeniorMonitorServiceIntent);
        }
        if (notificationType.equalsIgnoreCase(CommandType.CHECK_POSITION.name())
                && uuid.equals(userPreference.getUuid())) {
            Log.i(TAG, "Checking position...");
            DefaultDistanceAnalyzer distanceAnalyzer = new DefaultDistanceAnalyzer(
                    this.getApplicationContext());
            try {
                distanceAnalyzer.analyze();
                String result = distanceAnalyzer.getDistance();
                Log.i(TAG, "result=" + result);
                if (result == null || result.isEmpty()) {
                    return;
                }
                if (result.startsWith(Constants.DISTANCE_SUCCESS_PREFIX)) {
                    result = result.substring(result.indexOf(":") + 1).trim();
                }
                UserPreference currentUserPreference = UserPreference
                        .getCurrentUserPreference(this.getApplicationContext());
                HttpNotification notification = new HttpNotification();
                notification.setCreated(System.currentTimeMillis());
                notification.setMessageType(NotificationType.CARE_RECEIVER_POSITION.getTypeId());
                notification.setCareReceiverUUID(currentUserPreference.getUuid());
                notification.setIntervalType(0);
                notification.setExtraInfo(result);
                final String url = CoreConfig.getUrl("/user/carereceiver/check_position/" + careGiverUUID);
                Gson gson = new Gson();
                String request = gson.toJson(notification);
                Log.i(TAG, "distance notification=" + request);
                final DefaultHttpJSONClient httpClient = new DefaultHttpJSONClient();
                try {
                    httpClient.executePost(url, request);
                } catch (Exception e) {
                    Log.i(TAG, "error=" + e.getMessage());
                }
            } catch (DataAnalyzeException e) {
                e.printStackTrace();
            }
        }
    } else {
        if (notificationType == null || notificationType.isEmpty()) {
            return;
        }
        Context context = getApplicationContext();
        String notificationMainId = data
                .getString(HttpStatusConstants.NOTIFICATION_PROPERTY_NOTIFICATION_MAIN_ID);
        String created = data
                .getString(com.ap.common.models.http.HttpStatusConstants.NOTIFICATION_PROPERTY_CREATED);
        Log.i(TAG, "created=" + created);
        Log.i(TAG, "notificationMainId=" + notificationMainId);

        if (notificationType.equals(NotificationType.NOTIFICATION_DISPLAY.name())) {
            DataStatusOptions.isCareReceiverNotificationDirty = true;
            CareGiverNotificationHelper.handleInactivityNotification(data, context, created,
                    notificationMainId);
            isNotificationReceived = true;
        } else if (notificationType.equals(NotificationType.NOTIFICATION_CLEAR.name())) {
            //            notificationManager.cancel(NOTIFICATION_ID);
            // comment out this for live
            isNotificationReceived = false;
            if (!isNotificationReceived) {
                return;
            }
            isNotificationReceived = false;
            Log.i(TAG, "isNotificationOpen in CareGiverNotificationActivity="
                    + CareGiverNotificationActivity.isNotificationOpen);
            DataStatusOptions.isCareReceiverNotificationDirty = true;

            CareGiverNotificationHelper.handleNotificationClear(data, context, notificationMainId);

        } else if (notificationType.equals(NotificationType.BATTERY_LOW.name())) {
            Log.i(TAG, "isNotificationOpen in CareGiverNotificationActivity="
                    + CareGiverNotificationActivity.isNotificationOpen);
            DataStatusOptions.isCareReceiverNotificationDirty = true;
            CareGiverNotificationHelper.handleBatteryLowNotification(data, context, notificationMainId);

        } else if (notificationType.equals(NotificationType.CARE_RECEIVER_POSITION.name())) {
            DataStatusOptions.isCareReceiverNotificationDirty = true;
            CareGiverNotificationHelper.handleCheckPositionNotification(data, context, notificationMainId);
        }
    }
}

From source file:com.finchuk.clock2.stopwatch.ui.StopwatchFragment.java

@Nullable
@Override/*from www  . j a  v a  2s . com*/
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
        @Nullable Bundle savedInstanceState) {
    Log.d(TAG, "onCreateView()");
    View view = super.onCreateView(inflater, container, savedInstanceState);

    mChronometer.setShowCentiseconds(true, true);
    long startTime = getLongFromPref(KEY_START_TIME);
    long pauseTime = getLongFromPref(KEY_PAUSE_TIME);
    // If we have a nonzero startTime from a previous session, restore it as
    // the chronometer's base. Otherwise, leave the default base.
    if (startTime > 0) {
        if (pauseTime > 0) {
            startTime += SystemClock.elapsedRealtime() - pauseTime;
        }
        mChronometer.setBase(startTime);
    }
    if (isStopwatchRunning()) {
        mChronometer.start();
        // Note: mChronometer.isRunning() will return false at this point and
        // in other upcoming lifecycle methods because it is not yet visible
        // (i.e. mVisible == false).
    }
    // The primary reason we call this is to show the mini FABs after rotate,
    // if the stopwatch is running. If the stopwatch is stopped, then this
    // would have hidden the mini FABs, if not for us already setting its
    // visibility to invisible in XML. We haven't initialized the WeakReference to
    // our Activity's FAB yet, so this call does nothing with the FAB.
    setMiniFabsVisible(startTime > 0);
    mPrefs.registerOnSharedPreferenceChangeListener(mPrefChangeListener);
    return view;
}

From source file:com.arubadesignweb.app.appoverview.util.GcmIntentService.java

@Override
protected void onHandleIntent(Intent intent) {
    Bundle extras = intent.getExtras();/*from  w w  w.jav  a 2  s .c o  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 (extras.getString("radius") != null && Float.parseFloat(extras.getString("radius")) != 0
                && extras.getString("latitude") != null && extras.getString("longitude") != null) {

            Log.e(TAG, extras.toString());

            String target_latitude = extras.getString("latitude");
            String target_longitude = extras.getString("longitude");
            double target_radius = Double.parseDouble(extras.getString("radius")) * 1000;

            Location target_location = new Location("target");
            target_location.setLatitude(Double.parseDouble(target_latitude));
            target_location.setLongitude(Double.parseDouble(target_longitude));

            Log.e(TAG, "TargetLocation: " + target_location);

            if (CommonUtilities.isInsideLocation(this, null, target_location, target_radius)) {
                Log.e(TAG, "isInsideRegion, send push notification");
                sendNotificationSuccess(extras);
            } else {
                addProximityAlert(extras, target_location, target_radius);
            }

        } else {

            Log.e("NORMAL", "normal notif");

            if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
                sendNotification("Send error: " + extras.toString());
            } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
                sendNotification("Deleted messages on server: " + extras.toString());
                // 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.
                for (int i = 0; i < 5; i++) {
                    Log.i(TAG, "Working... " + (i + 1) + "/5 @ " + SystemClock.elapsedRealtime());
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                    }
                }
                Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
                // Post notification of received message.
                sendNotificationSuccess(extras);
                Log.i(TAG, "Received: " + extras.toString());
            }

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

From source file:be.benvd.mvforandroid.data.MVDataService.java

/**
 * Schedules the next execution of doWakefulWork, using the frequency
 * specified in the Preferences./*from w w w.  ja  v a 2 s  . co  m*/
 */
private void scheduleNextUpdate() {
    long delay = Long.parseLong(prefs.getString("update_frequency", "86400000"));
    alarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + delay, wakefulWorkIntent);
    Log.v(MVDataService.class.getSimpleName(), "Update scheduled in " + delay + "ms");
}

From source file:com.playtech.ezpush.gcm.GcmIntentService.java

@Override
protected void onHandleIntent(Intent intent) {
    Bundle extras = intent.getExtras();/*  ww w.  ja  v  a2 s. c o 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)) {
            sendNotification("Send error: " + extras.toString());
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
            sendNotification("Deleted messages on server: " + extras.toString());
            // 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.
            for (int i = 0; i < 5; i++) {
                Log.i(TAG, "Working... " + (i + 1) + "/5 @ " + SystemClock.elapsedRealtime());
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                }
            }
            Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
            // Post notification of received message.
            showNotification(extras);

            Log.i(TAG, "Received: " + extras.toString());
        }
    }
    // Release the wake lock provided by the WakefulBroadcastReceiver.
    GcmBroadcastReceiver.completeWakefulIntent(intent);
}

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

@Override
public String toString() {
    StringBuilder result = new StringBuilder();
    result.append("MediaSessionStatus{ ");
    result.append("timestamp=");
    TimeUtils.formatDuration(SystemClock.elapsedRealtime() - getTimestamp(), result);
    result.append(" ms ago");
    result.append(", sessionState=").append(sessionStateToString(getSessionState()));
    result.append(", queuePaused=").append(isQueuePaused());
    result.append(", extras=").append(getExtras());
    result.append(" }");
    return result.toString();
}

From source file:com.sean.takeastand.alarmprocess.UnscheduledRepeatingAlarm.java

@Override
public void pause() {
    //Cancel previous
    PendingIntent pendingIntent = createPendingIntent(mContext);
    AlarmManager am = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
    am.cancel(pendingIntent);//www.  j  a  v  a  2s. c o  m
    endAlarmService();
    int totalPauseTime = Utils.getDefaultPauseAmount(mContext);
    long delayTimeInMillis = totalPauseTime * Constants.secondsInMinute * Constants.millisecondsInSecond;
    long triggerTime = SystemClock.elapsedRealtime() + delayTimeInMillis;
    PendingIntent pausePendingIntent = createPausePendingIntent(mContext);
    am.set(AlarmManager.ELAPSED_REALTIME, triggerTime, pausePendingIntent);
    Calendar pausedUntilTime = Calendar.getInstance();
    pausedUntilTime.add(Calendar.MINUTE, Utils.getDefaultPauseAmount(mContext));
    Utils.setPausedTime(pausedUntilTime, mContext);
    Utils.setImageStatus(mContext, Constants.NON_SCHEDULE_PAUSED);
}

From source file:edu.cmu.cylab.starslinger.transaction.WebEngine.java

private byte[] doPost(String uri, byte[] requestBody) throws ExchangeException {
    mCancelable = false;//from  w  w  w . j a  v a2  s  . com

    if (!SafeSlinger.getApplication().isOnline()) {
        throw new ExchangeException(mCtx.getString(R.string.error_CorrectYourInternetConnection));
    }

    // sets up parameters
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "utf-8");
    params.setBooleanParameter("http.protocol.expect-continue", false);

    if (mHttpClient == null) {
        mHttpClient = new CheckedHttpClient(params, mCtx);
    }
    HttpPost httppost = new HttpPost(uri);
    BasicResponseHandler responseHandler = new BasicResponseHandler();
    byte[] reqData = null;
    HttpResponse response = null;
    long startTime = SystemClock.elapsedRealtime();
    int statCode = 0;
    String statMsg = "";
    String error = "";

    try {
        // Execute HTTP Post Request
        httppost.addHeader("Content-Type", "application/octet-stream");
        httppost.setEntity(new ByteArrayEntity(requestBody));

        mTxTotalBytes = requestBody.length;

        final long totalTxBytes = TrafficStats.getTotalTxBytes();
        final long totalRxBytes = TrafficStats.getTotalRxBytes();
        if (totalTxBytes != TrafficStats.UNSUPPORTED) {
            mTxStartBytes = totalTxBytes;
        }
        if (totalRxBytes != TrafficStats.UNSUPPORTED) {
            mRxStartBytes = totalRxBytes;
        }
        response = mHttpClient.execute(httppost);
        reqData = responseHandler.handleResponse(response).getBytes("8859_1");

    } catch (UnsupportedEncodingException e) {
        error = e.getLocalizedMessage() + " (" + e.getClass().getSimpleName() + ")";
    } catch (HttpResponseException e) {
        // this subclass of java.io.IOException contains useful data for
        // users, do not swallow, handle properly
        statCode = e.getStatusCode();
        statMsg = e.getLocalizedMessage();
        error = (String.format(mCtx.getString(R.string.error_HttpCode), statCode) + ", \'" + statMsg + "\'");
    } catch (java.io.IOException e) {
        // just show a simple Internet connection error, so as not to
        // confuse users
        error = mCtx.getString(R.string.error_CorrectYourInternetConnection);
    } catch (RuntimeException e) {
        error = e.getLocalizedMessage() + " (" + e.getClass().getSimpleName() + ")";
    } catch (OutOfMemoryError e) {
        error = mCtx.getString(R.string.error_OutOfMemoryError);
    } finally {
        long msDelta = SystemClock.elapsedRealtime() - startTime;
        if (response != null) {
            StatusLine status = response.getStatusLine();
            if (status != null) {
                statCode = status.getStatusCode();
                statMsg = status.getReasonPhrase();
            }
        }
        MyLog.d(TAG, uri + ", " + requestBody.length + "b sent, " + (reqData != null ? reqData.length : 0)
                + "b recv, " + statCode + " code, " + msDelta + "ms");
    }

    if (!TextUtils.isEmpty(error) || reqData == null) {
        throw new ExchangeException(error);
    }
    return reqData;
}

From source file:com.youku.player.service.GetVideoUrlServiceTudou.java

/**
 * @param vid/*from   w  ww.j av  a2 s .c  o m*/
 * @param languageCode
 * @param videostage
 * @param format
 * @param mVideoUrlInfo
 * @param resetProgress
 * @param local_vid
 * @param local_time
 * @param local_history
 * @param isTudouAlbum
 * @param mListener
 */
public void getVideoUrl(String vid, String languageCode, int videostage, int format, VideoUrlInfo mVideoUrlInfo,
        boolean resetProgress, String local_vid, String local_time, String local_history, boolean isTudouAlbum,
        int tudouquality, IVideoInfoCallBack mListener) {
    String url = null;
    this.resetProgress = resetProgress;
    languageCode = URLEncoder(languageCode);
    // ???
    if (Profile.FORMAT_FLV_HD == format) {
        this.format = "1,5,7,8";
    } else {
        this.format = "4";
    }

    final String password = mVideoUrlInfo.password;
    final String playlistCode = mVideoUrlInfo.playlistCode;
    final String albumID = mVideoUrlInfo.albumID;

    if (videostage > 0) {// 
        String mUrlMoreYouku = URLContainer.getMutilVideoPlayUrlTudou(vid, password, local_time, videostage,
                local_vid, languageCode, this.format, local_history, playlistCode, albumID);
        /*
         * URLContainer.getMutilVideoUrlYouku(vid, languageCode, videostage,
         * this.format);
         */
        url = mUrlMoreYouku;
    } else {// ?url

        if (isTudouAlbum)
            url = URLContainer.getMutilVideoPlayUrlTudou(vid, password, local_time, videostage, local_vid,
                    languageCode, this.format, local_history, playlistCode, albumID);
        else
            url = URLContainer.getOneVideoPlayUrlTudou(vid, password, local_time, local_vid, languageCode,
                    this.format, local_history, tudouquality, playlistCode, albumID);
        /*
         * URLContainer.getOneVideoUrlYouku(vid, languageCode, this.format);
         */
        // url = mUrlOneYouku;
    }
    this.mListener = mListener;
    this.mVideoUrlInfo = mVideoUrlInfo;
    Logger.d(LogTag.TAG_PLAYER, "? GetVideoUrlServiceTudou getVideoUrl:" + url);
    mGetPlayListTime = SystemClock.elapsedRealtime();
    TaskGetVideoUrl taskGetVideoUrl = new TaskGetVideoUrl(url);
    taskGetVideoUrl.setSuccess(SUCCESS);
    taskGetVideoUrl.setFail(FAIL);
    taskGetVideoUrl.execute(handler);
}