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:au.com.smarttrace.beacons.BluetoothService.java

private void connect() {
    btScanner = btAdapter.getBluetoothLeScanner();
    if (btScanner != null && btAdapter.isEnabled()) {

        Log.d(TAG, "START SCANNING!");
        btScanner.startScan(btFilters, btSettings, scanCallback);
        scanning = true;/*from   ww w.j a  va  2  s .c  o m*/
        sendChange(true);

        //XXX: workaround to avoid bluetooth scan halt
        AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
        Intent intent = new Intent(BluetoothService.ACTION_RESCAN, null, this, BluetoothService.class);
        alarm.setExact(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 15000l,
                PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));

        //         future = executor.schedule(this, DELAY_REPEAT_SCAN, TimeUnit.SECONDS);
    }
}

From source file:cz.tomas.StockAnalyze.activity.NewsActivity.java

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    this.adapter.swapCursor(data);

    //      this.getActionBar().setRefreshActionItemState(false);
    this.listView.onRefreshComplete();
    final long current = SystemClock.elapsedRealtime();
    if (current - lastUpdateTime > UPDATE_INTERVAL) {
        this.refresh();
        lastUpdateTime = current;/*from  w w w.  j a  va 2s.  c o m*/
    }
}

From source file:com.appdevper.mediaplayer.app.PlaybackManager.java

/**
 * Update the current media player state, optionally showing an error message.
 *
 * @param error if not null, error message to present to the user.
 *///w  w w .  j  av a 2 s .c om
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();
    }

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

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

    // If there is an error message, send it to the playback state:
    if (error != null) {
        // Error states are really only supposed to be used for errors that cause playback to
        // stop unexpectedly and persist until the user takes action to fix it.
        stateBuilder.setErrorMessage(error);
        state = PlaybackStateCompat.STATE_ERROR;
    }
    //noinspection ResourceType
    stateBuilder.setState(state, position, 1.0f, SystemClock.elapsedRealtime());

    // Set the activeQueueItemId if the current index is valid.
    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();
    }
}

From source file:org.kegbot.app.service.CheckinService.java

private void registerAlarm() {
    unregisterAlarm();//w  ww. j  a  v  a  2  s. c  om
    Log.d(TAG, "Registering alarm.");
    final Intent intent = getCheckinIntent(this);
    mPendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
    final AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    final long nextCheckin = SystemClock.elapsedRealtime() + CHECKIN_INTERVAL_MILLIS;
    alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, nextCheckin, CHECKIN_INTERVAL_MILLIS,
            mPendingIntent);
}

From source file:ca.rmen.android.scrumchatter.meeting.detail.MeetingCursorAdapter.java

/**
 * Set the view elements (TextView text, etc) for the given member of a
 * meeting./* ww  w  . ja va  2 s . c  o m*/
 */
@Override
public void onBindViewHolder(MeetingViewHolder holder, int position) {
    // Extract the fields we need from this cursor
    @SuppressWarnings("resource")
    MeetingMemberCursorWrapper cursorWrapper = new MeetingMemberCursorWrapper(getCursor());
    MeetingMemberItemData meetingMemberItemData = new MeetingMemberItemData();
    meetingMemberItemData.memberId = cursorWrapper.getMemberId();
    meetingMemberItemData.memberName = cursorWrapper.getMemberName();
    long duration = cursorWrapper.getDuration();
    State meetingState = cursorWrapper.getMeetingState();
    Long talkStartTime = cursorWrapper.getTalkStartTime();

    // Find the Views we need to set up
    MeetingMemberListItemBinding binding = holder.binding;

    // if the talkStartTime is non-zero, this means the
    // member is talking (and started talking that long ago).
    meetingMemberItemData.isTalking = talkStartTime > 0;

    // Set up the start/stop button for this member.
    // If the meeting is finished, we hide the start/stop button.
    if (meetingState == State.FINISHED) {
        meetingMemberItemData.startStopButtonVisibility = View.INVISIBLE;
    }
    meetingMemberItemData.clickable = meetingState != State.FINISHED;

    // If the member is currently talking, show the chronometer.
    // Otherwise, show the duration that they talked (if any).
    if (meetingMemberItemData.isTalking) {
        long hasBeenTalkingFor = duration * 1000 + (System.currentTimeMillis() - talkStartTime);
        binding.tvDuration.setBase(SystemClock.elapsedRealtime() - hasBeenTalkingFor);
        binding.tvDuration.start();
        meetingMemberItemData.durationColor = mColorChronoActive;
        startAnimation(binding.ivChatterFace);
    } else {
        binding.tvDuration.stop();
        binding.tvDuration.setText(DateUtils.formatElapsedTime(duration));
        meetingMemberItemData.durationColor = duration > 0 ? mColorChronoInactive : mColorChronoNotStarted;
        stopAnimation(binding.ivChatterFace);
    }

    @ColorRes
    int backgroundColorRes = (position % 2 == 0) ? R.color.row_background_color_even
            : R.color.row_background_color_odd;
    meetingMemberItemData.backgroundColor = ContextCompat.getColor(binding.getRoot().getContext(),
            backgroundColorRes);
    // Set the member id as a tag, so when the listener receives the
    // click action, it knows for which member the user clicked.
    binding.setItemData(meetingMemberItemData);
    binding.executePendingBindings();
}

From source file:com.google.android.apps.muzei.sync.TaskQueueService.java

private void scheduleRetryArtworkDownload() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
        jobScheduler.schedule(new JobInfo.Builder(LOAD_ARTWORK_JOB_ID,
                new ComponentName(this, DownloadArtworkJobService.class))
                        .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY).build());
    } else {/*  www  .ja  v  a 2  s.  c o  m*/
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        int reloadAttempt = sp.getInt(PREF_ARTWORK_DOWNLOAD_ATTEMPT, 0);
        sp.edit().putInt(PREF_ARTWORK_DOWNLOAD_ATTEMPT, reloadAttempt + 1).commit();
        AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        long retryTimeMillis = SystemClock.elapsedRealtime() + (1 << reloadAttempt) * 2000;
        am.set(AlarmManager.ELAPSED_REALTIME, retryTimeMillis,
                TaskQueueService.getArtworkDownloadRetryPendingIntent(this));
    }
}

From source file:com.tws.soul.soulbrown.gcm.GcmIntentService.java

@Override
protected void onHandleIntent(Intent intent) {
    Bundle extras = intent.getExtras();//from   ww w  .jav  a  2s  . c  om
    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) {
            }
            }
            */

            String msg = extras.getString("msg");
            String pushFlag = extras.getString("pushflag");
            int status = extras.getInt("status");

            LOG.d("GcmIntentService msg : " + msg + " pushFlag : " + pushFlag + " status : " + status);

            String decMsg = "";
            try {
                decMsg = URLDecoder.decode(msg, "utf-8");

            } catch (Exception e) {
                decMsg = "";
            }

            Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
            // Post notification of received message.

            if (!TextUtils.isEmpty(decMsg)) {

                sendNotification(decMsg);

                Intent intentGcm = new Intent(GCM_BROADCAST);

                intentGcm.putExtra("msg", decMsg);

                LocalBroadcastManager.getInstance(this).sendBroadcast(intentGcm);

                // alarm , geofence off
                if (pushFlag.equals(GcmDefine.PUSH_CHG_ORDER)) {

                    //if( status == 1 ) {
                    LOG.d("GcmIntentService alarm , geofence off");

                    PrefOrderInfo prefOrderInfo = new PrefOrderInfo(this);
                    prefOrderInfo.setArriveTime(0);
                    prefOrderInfo.setOrderStore("");

                    AlarmManagerBroadcastReceiver alarmManagerBroadcastReceiver = new AlarmManagerBroadcastReceiver();
                    alarmManagerBroadcastReceiver.cancelAlarm(this);

                    geofenceClient = new GeofenceClient(this, GeofenceResultHandler);
                    //}
                } else if (pushFlag.equals(GcmDefine.PUSH_CANCEL_ORDER)
                        || pushFlag.equals(GcmDefine.PUSH_APPROACH_USER)
                        || pushFlag.equals(GcmDefine.PUSH_NEW_ORDER)) {
                    // alarm service call

                    Intent intentSvc = new Intent(this, AlarmNotiService.class);

                    this.startService(intentSvc);

                } else if (pushFlag.equals(GcmDefine.PUSH_CHG_PUSHKEY)) {
                    setPushStatus(0);
                }

            }
            Log.i(TAG, "Received: " + decMsg);

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

From source file:com.murati.oszk.audiobook.playback.PlaybackManager.java

/**
 * Update the current media player state, optionally showing an error message.
 *
 * @param error if not null, error message to present to the user.
 *//*from   w  w  w  .j  ava 2s  .co m*/
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();
    }

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

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

    // If there is an error message, send it to the playback state:
    if (error != null) {
        // Error states are really only supposed to be used for errors that cause playback to
        // stop unexpectedly and persist until the user takes action to fix it.
        stateBuilder.setErrorMessage(error);
        state = PlaybackStateCompat.STATE_ERROR;
    }
    //noinspection ResourceType
    stateBuilder.setState(state, position, 1.0f, SystemClock.elapsedRealtime());

    // Set the activeQueueItemId if the current index is valid.
    MediaSessionCompat.QueueItem currentMusic = mQueueManager.getCurrentTrack();
    if (currentMusic != null) {
        stateBuilder.setActiveQueueItemId(currentMusic.getQueueId());
    }

    mServiceCallback.onPlaybackStateUpdated(stateBuilder.build());

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

From source file:com.lastsoft.plog.adapter.GroupAdapter.java

@Override
public void onBindViewHolder(ViewHolder viewHolder, final int position) {
    //long totalPlays = ((long) PlayersPerPlay.totalPlays_GameGroup(GameGroup.findById(GameGroup.class, groups.get(position).getId())).size() / (long) GameGroup.getGroupPlayers(GameGroup.findById(GameGroup.class, groups.get(position).getId())).size());
    viewHolder.getNameView().setText(groups.get(position).groupName);
    viewHolder.getPlaysView()/*w w  w  .  j a  v  a 2  s .  c  om*/
            .setText(mActivity.getString(R.string.total_plays) + groups.get(position).totalPlays);
    viewHolder.getGamesView()
            .setText(mActivity.getString(R.string.unique_games) + groups.get(position).uniqueGames);
    viewHolder.getView().setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (SystemClock.elapsedRealtime() - mLastClickTime < 1000) {
                return;
            }
            mLastClickTime = SystemClock.elapsedRealtime();
            ((MainActivity) mActivity).openAddGroup(mFragment, groups.get(position).getId());
        }
    });
    viewHolder.getOverflowLayout().setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            groupPopup(view, position);
        }
    });
}

From source file:com.directsiding.android.WebActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    setContentView(R.layout.activity_web);

    // Le ponemos la font Signika al titulo del Action Bar
    SpannableString s = new SpannableString(getString(R.string.app_name));
    s.setSpan(new TypefaceSpan(this, LoginActivity.PATH_SIGNIKA_FONT), 0, s.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    // Agregamos lo necesario al Action Bar
    ActionBar actionBar = getSupportActionBar();
    actionBar.setTitle(s);//  ww  w . j a va  2  s  . c om
    actionBar.setDisplayShowHomeEnabled(true);
    actionBar.setHomeButtonEnabled(true);

    // Obtenemos la url a la que el usuario va a ingresar
    String url = getIntent().getExtras().getString(LoginActivity.EXTRA_URL);

    // Obtenemos la cookie y la agregamos al webview
    Cookie sessionCookie = LoginOpActivity.cookie;
    CookieSyncManager.createInstance(this);
    CookieManager cookieManager = CookieManager.getInstance();
    if (sessionCookie != null) {
        //cookieManager.removeSessionCookie();
        String cookieString = sessionCookie.getName() + "=" + sessionCookie.getValue() + "; domain="
                + sessionCookie.getDomain();
        cookieManager.setCookie(LoginActivity.POST_URL, cookieString);
        CookieSyncManager.getInstance().sync();
    }

    mProgressBar = (ProgressBar) findViewById(R.id.progressBar_webView);
    webView = (WebView) findViewById(R.id.webView_ing);

    webViewConfig();
    webView.loadUrl(url);
    //webView.loadUrl("http://www.google.com");

    // guardamos el tiempo en el que se creo la actividad
    lastTimeStamp = SystemClock.elapsedRealtime();

}