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:cc.softwarefactory.lokki.android.services.LocationService.java

private void setTemporalTimer() {
    AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
    Intent alarmIntent = new Intent(this, LocationService.class);
    alarmIntent.putExtra(ALARM_TIMER, 1);
    PendingIntent alarmCallback = PendingIntent.getService(this, 0, alarmIntent, 0);
    alarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + INTERVAL_1_MIN,
            alarmCallback);//w w  w  .ja v a 2s.c  om
    Log.e(TAG, "Time created.");
}

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

@Override
public void onLocationChanged(Location location) {
    if (location == null) {
        return;//from  w ww  .  j a v  a 2 s  . c  o m
    }

    GISApplication app = (GISApplication) getActivity().getApplication();
    app.setCurrentLocation(location);
    mLastLocationMillis = SystemClock.elapsedRealtime();

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());

    int nFormat = prefs.getInt(FoclSettingsConstantsUI.KEY_PREF_COORD_FORMAT + "_int", Location.FORMAT_DEGREES);

    mLatText = FoclLocationUtil.formatLatitude(location.getLatitude(), nFormat, getResources())
            + getString(R.string.coord_lat);

    mLongText = FoclLocationUtil.formatLongitude(location.getLongitude(), nFormat, getResources())
            + getString(R.string.coord_lon);

    DecimalFormat df = new DecimalFormat("0");

    double altitude = location.getAltitude();
    mAltText = df.format(altitude) + getString(R.string.altitude_unit);

    float accuracy = location.getAccuracy();
    mAccText = df.format(accuracy) + getString(R.string.accuracy_unit);

    // TODO: prevPointLocation
    Location prevPointLocation = new Location("");
    prevPointLocation.setLatitude(9);
    prevPointLocation.setLongitude(36);
    float distance = location.distanceTo(prevPointLocation);

    mDistText = df.format(distance) + getString(R.string.distance_unit);
    mDistView.setTextColor(distance > FoclConstants.MAX_DISTANCE_FROM_PREV_POINT ? 0xFF880000 : 0xFF008800);

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

From source file:com.kescoode.android.yong.volley.toolbox.BasicNetwork.java

@Override
public NetworkResponse performRequest(Request<?> request) throws VolleyError {
    long requestStart = SystemClock.elapsedRealtime();
    while (true) {
        HttpResponse httpResponse = null;
        byte[] responseContents = null;
        Map<String, String> responseHeaders = Collections.emptyMap();
        try {//from  w  ww  .  j av a2 s.c o  m
            // Gather headers.
            Map<String, String> headers = new HashMap<String, String>();
            addCacheHeaders(headers, request.getCacheEntry());
            httpResponse = mHttpStack.performRequest(request, headers);
            StatusLine statusLine = httpResponse.getStatusLine();
            int statusCode = statusLine.getStatusCode();

            responseHeaders = convertHeaders(httpResponse.getAllHeaders());
            // Handle cache validation.
            if (statusCode == HttpStatus.SC_NOT_MODIFIED) {

                Entry entry = request.getCacheEntry();
                if (entry == null) {
                    return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, null, responseHeaders, true,
                            SystemClock.elapsedRealtime() - requestStart);
                }

                // A HTTP 304 response does not have all header fields. We
                // have to use the header fields from the cache entry plus
                // the new ones from the response.
                // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5
                entry.responseHeaders.putAll(responseHeaders);
                return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, entry.data, entry.responseHeaders, true,
                        SystemClock.elapsedRealtime() - requestStart);
            }

            // Handle moved resources
            if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
                    || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                String newUrl = responseHeaders.get("Location");
                request.setRedirectUrl(newUrl);
            }

            // Some responses such as 204s do not have content.  We must check.
            if (httpResponse.getEntity() != null) {
                responseContents = entityToBytes(request, httpResponse.getEntity());
            } else {
                // Add 0 byte response as a way of honestly representing a
                // no-content request.
                responseContents = new byte[0];
            }

            // if the request is slow, log it.
            long requestLifetime = SystemClock.elapsedRealtime() - requestStart;
            logSlowRequests(requestLifetime, request, responseContents, statusLine);

            if (statusCode < 200 || statusCode > 299) {
                throw new IOException();
            }
            return new NetworkResponse(statusCode, responseContents, responseHeaders, false,
                    SystemClock.elapsedRealtime() - requestStart);
        } catch (SocketTimeoutException e) {
            attemptRetryOnException("socket", request, new TimeoutError());
        } catch (ConnectTimeoutException e) {
            attemptRetryOnException("connection", request, new TimeoutError());
        } catch (MalformedURLException e) {
            throw new RuntimeException("Bad URL " + request.getUrl(), e);
        } catch (IOException e) {
            int statusCode = 0;
            NetworkResponse networkResponse = null;
            if (httpResponse != null) {
                statusCode = httpResponse.getStatusLine().getStatusCode();
            } else {
                throw new NoConnectionError(e);
            }
            if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
                    || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                VolleyLog.e("Request at %s has been redirected to %s", request.getOriginUrl(),
                        request.getUrl());
            } else {
                VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl());
            }
            if (responseContents != null) {
                networkResponse = new NetworkResponse(statusCode, responseContents, responseHeaders, false,
                        SystemClock.elapsedRealtime() - requestStart);
                if (statusCode == HttpStatus.SC_UNAUTHORIZED || statusCode == HttpStatus.SC_FORBIDDEN) {
                    attemptRetryOnException("auth", request, new AuthFailureError(networkResponse));
                } else if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
                        || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                    attemptRetryOnException("redirect", request, new AuthFailureError(networkResponse));
                } else {
                    // TODO: Only throw ServerError for 5xx status codes.
                    throw new ServerError(networkResponse);
                }
            } else {
                throw new NetworkError(networkResponse);
            }
        }
    }
}

From source file:com.example.product.GcmIntentService.java

@Override
protected void onHandleIntent(Intent intent) {
    Bundle extras = intent.getExtras();//  ww w  .j av a  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)) {
            Log.e(TAG, "GCM_MESSAGE_TYPE_SEND_ERROR");
            //do nothing              
            //sendNotification("Send error: " + extras.toString());
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
            Log.e(TAG, "GCM_MESSAGE_TYPE_DELETED");
            //do nothing            
            //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)) {

            //? ?? Notification? .              
            // 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.
            //sendNotification("Received: " + extras.toString());                
            //test sendNotification
            sendNotification(extras);

            Log.i(TAG, "Received: " + extras.toString());

            //??  
            if (!isScreenOn(this)) {

                Log.i(TAG, "screen is off");

                //test
                Intent popupIntent = new Intent(this, ActivityPopUp.class).putExtras(extras)
                        .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                //  .
                this.startActivity(popupIntent);

            }
            //??  
            else {
                ActivityManager am = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
                List<RunningTaskInfo> runList = am.getRunningTasks(10);
                ComponentName name = runList.get(0).topActivity;
                String className = name.getClassName();
                boolean isAppRunning = false;

                Log.i(TAG, "className ==" + className);
                //? ?? AcitivityPopUp ?
                if (className.equals("com.example.product.ActivityPopUp")) {
                    isAppRunning = true;
                }

                //?? ?
                if (isAppRunning == true) {
                    Log.i(TAG, "screen is off, but popup is on");

                    //test
                    Intent popupIntent = new Intent(this, ActivityPopUp.class).putExtras(extras)
                            .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    //  .
                    this.startActivity(popupIntent);
                    // ? ?  ? 
                }
                //? ? ? 
                else {

                    // ? ? ?  ? 

                }
            }

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

From source file:com.aylanetworks.aura.GcmIntentService.java

@SuppressWarnings("unchecked")
@Override//w w  w . jav  a 2  s  .com
protected void onHandleIntent(Intent intent) {
    Bundle extras = intent.getExtras();
    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(), null);
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
            sendNotification("Deleted messages on server: " + extras.toString(), null);
            // 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.
            //PushNotification.playSound("Beep_once.ogg");
            for (int i = 0; i < 3; i++) {
                Log.i(TAG, "Working... " + (i + 1) + "/3 @ " + SystemClock.elapsedRealtime());
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                }
            }
            Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
            // Post notification of received message.
            String message = extras.getString("message");
            String sound = extras.getString("sound");
            //String other = extras.getString("other");
            sendNotification(message, sound);
            Log.i(TAG, "Received: " + extras.toString());
        }
    }
    // Release the wake lock provided by the WakefulBroadcastReceiver.
    GcmBroadcastReceiver.completeWakefulIntent(intent);
}

From source file:com.github.sryze.wirebug.DebugStatusService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent != null && intent.getAction() != null) {
        if (intent.getAction().equals(ACTION_UPDATE_STATUS)) {
            updateStatus();/*from w w w  .j  a  v  a 2 s  . co  m*/
            Intent updateStatusIntent = new Intent(DebugStatusService.this, DebugStatusService.class);
            updateStatusIntent.setAction(ACTION_UPDATE_STATUS);
            PendingIntent alarmPendingIntent = PendingIntent.getService(DebugStatusService.this, 0,
                    updateStatusIntent, PendingIntent.FLAG_CANCEL_CURRENT);
            alarmManager.cancel(alarmPendingIntent);
            alarmManager.set(AlarmManager.ELAPSED_REALTIME,
                    SystemClock.elapsedRealtime() + STATUS_UPDATE_INTERVAL, alarmPendingIntent);
        } else if (intent.getAction().equals(ACTION_STOP)) {
            DebugManager.setTcpDebuggingEnabled(false);
            updateStatus();
        }
    }
    return START_STICKY;
}

From source file:com.example.stacky.ScheduledMaintenanceService.java

/**
 * Reduce battery impact by waiting until the phone is no longer in standby mode before the alarm triggers
 *//*from  w  w  w .  j a v a2 s  .com*/
@Override
protected void onHandleIntent(Intent intent) {
    System.out.println("got Intent ");

    alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 25000,
            25000, startAlarmPendingIntent);

    //lastTime=System.currentTimeMillis();

    displayNotificationOne();

}

From source file:edu.mines.letschat.GcmIntentService.java

@Override
protected void onHandleIntent(Intent intent) {
    Bundle extras = intent.getExtras();/*from  ww  w.j  a  v 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 (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
            sendNotification("Send error: " + extras.toString(), "0");
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
            sendNotification("Deleted messages on server: " + extras.toString(), "0");
            // 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.

            String message = (String) extras.get("message");
            messages.add(message);

            String picture = (String) extras.get("picture");

            String senderID = (String) extras.get("sender");
            String recipientID = (String) extras.get("recipient");
            sendNotification(message, senderID);
            Log.v(TAG, "Received: " + message);

            Log.i(TAG, "Received: " + extras.toString());
            Intent resultBroadCastIntent = new Intent();
            /*set action here*/
            resultBroadCastIntent.setAction(
                    edu.mines.letschat.MessageActivity.TextCapitalizeResultReceiver.ACTION_TEXT_CAPITALIZED);
            /*set intent category as default*/
            resultBroadCastIntent.addCategory(Intent.CATEGORY_DEFAULT);

            /*add data to intent*/
            resultBroadCastIntent.putExtra(OUTPUT_TEXT, message);
            //              Log.v(TAG, "Sender id " + senderID + " recieve id " + recipientID);
            Log.v(TAG, picture);
            Conversation convo = new Conversation(getApplicationContext(), senderID, recipientID, message,
                    false, picture);
            convo.save();

            if (!picture.isEmpty()) {
                new DownloadImage(picture).execute();
            }

            /*send broadcast */
            sendBroadcast(resultBroadCastIntent);
        }
    }
    // Release the wake lock provided by the WakefulBroadcastReceiver.
    GcmBroadcastReviever.completeWakefulIntent(intent);
}

From source file:com.example.android.repeatingalarm.RepeatingAlarmFragment.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == R.id.sample_action) {

        // BEGIN_INCLUDE (intent_fired_by_alarm)
        // First create an intent for the alarm to activate.
        // This code simply starts an Activity, or brings it to the front if it has already
        // been created.
        Intent intent = new Intent(getActivity(), MainActivity.class);
        intent.setAction(Intent.ACTION_MAIN);
        intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        // END_INCLUDE (intent_fired_by_alarm)

        // BEGIN_INCLUDE (pending_intent_for_alarm)
        // Because the intent must be fired by a system service from outside the application,
        // it's necessary to wrap it in a PendingIntent.  Providing a different process with
        // a PendingIntent gives that other process permission to fire the intent that this
        // application has created.
        // Also, this code creates a PendingIntent to start an Activity.  To create a
        // BroadcastIntent instead, simply call getBroadcast instead of getIntent.
        PendingIntent pendingIntent = PendingIntent.getActivity(getActivity(), REQUEST_CODE, intent, 0);

        // END_INCLUDE (pending_intent_for_alarm)

        // BEGIN_INCLUDE (configure_alarm_manager)
        // There are two clock types for alarms, ELAPSED_REALTIME and RTC.
        // ELAPSED_REALTIME uses time since system boot as a reference, and RTC uses UTC (wall
        // clock) time.  This means ELAPSED_REALTIME is suited to setting an alarm according to
        // passage of time (every 15 seconds, 15 minutes, etc), since it isn't affected by
        // timezone/locale.  RTC is better suited for alarms that should be dependant on current
        // locale.

        // Both types have a WAKEUP version, which says to wake up the device if the screen is
        // off.  This is useful for situations such as alarm clocks.  Abuse of this flag is an
        // efficient way to skyrocket the uninstall rate of an application, so use with care.
        // For most situations, ELAPSED_REALTIME will suffice.
        int alarmType = AlarmManager.ELAPSED_REALTIME;
        final int FIFTEEN_SEC_MILLIS = 15000;

        // The AlarmManager, like most system services, isn't created by application code, but
        // requested from the system.
        AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(getActivity().ALARM_SERVICE);

        // setRepeating takes a start delay and period between alarms as arguments.
        // The below code fires after 15 seconds, and repeats every 15 seconds.  This is very
        // useful for demonstration purposes, but horrendous for production.  Don't be that dev.
        alarmManager.setRepeating(alarmType, SystemClock.elapsedRealtime() + FIFTEEN_SEC_MILLIS,
                FIFTEEN_SEC_MILLIS, pendingIntent);
        // END_INCLUDE (configure_alarm_manager);
        Log.i("RepeatingAlarmFragment", "Alarm set.");
    }/*from w ww  .  ja v  a  2  s . co m*/
    return true;
}

From source file:com.classiqo.nativeandroid_32bitz.playback.PlaybackManager.java

public void updatePlaybackState(String error) {
    LogHelper.d(TAG, "updatePlaybackState, playback state = " + mPlayback.getState());

    long position = PlaybackStateCompat.PLAYBACK_POSITION_UNKNOWN;
    if (mPlayback != null && mPlayback.isConnected()) {
        position = mPlayback.getCurrentStreamPosition();
    }//from ww w .  j a v  a 2 s . co  m

    //noinspection ResourceType
    PlaybackStateCompat.Builder stateBuilder = new PlaybackStateCompat.Builder()
            .setActions(getAvailableActions());

    setCustomAction(stateBuilder);
    int state = mPlayback.getState();

    if (error != null) {
        stateBuilder.setErrorMessage(error);
        state = PlaybackStateCompat.STATE_ERROR;
    }
    //noinspection ResourceType
    stateBuilder.setState(state, position, 1.0f, SystemClock.elapsedRealtime());

    MediaSessionCompat.QueueItem currentMusic = mQueueManager.getCurrentMusic();

    if (currentMusic != null) {
        stateBuilder.setActiveQueueItemId(currentMusic.getQueueId());
    }

    mServiceCallback.onPlaybackStateUpdated(stateBuilder.build());

    if (state == PlaybackStateCompat.STATE_PLAYING || state == PlaybackStateCompat.STATE_PAUSED) {
        mServiceCallback.onNotificationRequired();
    }
}