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:ee.ioc.phon.android.speak.RecognizerIntentActivity.java

@Override
public void onStart() {
    super.onStart();

    mIsStartActivity = false;//from   w  ww .  j  av a2s  . c  o  m

    // Show the length of the current recording in bytes
    mRunnableBytes = new Runnable() {
        public void run() {
            if (mService != null) {
                mTvBytes.setText(Utils.getSizeAsString(mService.getLength()));
            }
            mHandlerBytes.postDelayed(this, TASK_BYTES_INTERVAL);
        }
    };

    // Show the number of audio chunks that have been sent to the server
    mRunnableChunks = new Runnable() {
        public void run() {
            if (mService != null) {
                mTvChunks.setText(makeBar(DOTS, mService.getChunkCount()));
            }
            mHandlerChunks.postDelayed(this, TASK_CHUNKS_INTERVAL);
        }
    };

    // Decide if we should stop recording
    // 1. Max recording time (in milliseconds) has passed
    // 2. Speaker stopped speaking
    final int maxRecordingTime = 1000 * Integer.parseInt(mPrefs
            .getString(getString(R.string.keyAutoStopAfterTime), getString(R.string.defaultAutoStopAfterTime)));

    mRunnableStop = new Runnable() {
        public void run() {
            if (mService != null) {
                if (maxRecordingTime < (SystemClock.elapsedRealtime() - mService.getStartTime())) {
                    Log.i(LOG_TAG, "Max recording time exceeded");
                    stopRecording();
                } else if (mPrefs.getBoolean("keyAutoStopAfterPause", true) && mService.isPausing()) {
                    Log.i(LOG_TAG, "Speaker finished speaking");
                    stopRecording();
                } else {
                    mHandlerStop.postDelayed(this, TASK_STOP_INTERVAL);
                }
            }
        }
    };

    mRunnableVolume = new Runnable() {
        public void run() {
            if (mService != null) {

                float db = mService.getRmsdb();
                final int maxLevel = mVolumeLevels.size() - 1;

                int index = (int) ((db - Constants.DB_MIN) / (Constants.DB_MAX - Constants.DB_MIN) * maxLevel);
                final int level = Math.min(Math.max(0, index), maxLevel);

                if (level != mLevel) {
                    mIvVolume.setImageDrawable(mVolumeLevels.get(level));
                    mLevel = level;
                }

                mHandlerVolume.postDelayed(this, TASK_VOLUME_INTERVAL);
            }
        }
    };

    mBStartStop.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if (mIsBound) {
                if (mService.getState() == State.RECORDING) {
                    stopRecording();
                } else {
                    startRecording();
                }
            } else {
                mStartRecording = true;
                doBindService();
            }
        }
    });

    // Settings button
    ((ImageButton) findViewById(R.id.bSettings)).setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            mIsStartActivity = true;
            startActivity(new Intent(getApplicationContext(), Preferences.class));
        }
    });

    doBindService();
}

From source file:com.inrista.loggliest.Loggly.java

private static synchronized void start() {
    if (mThread != null && mThread.isAlive())
        return;//from   www. j  a  v a 2s.  com

    mThread = new Thread(new Runnable() {
        @Override
        public void run() {
            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
            mThread.setName(THREAD_NAME);

            List<JSONObject> logBatch = new ArrayList<JSONObject>();
            while (true) {
                try {
                    JSONObject msg = mLogQueue.poll(10, TimeUnit.SECONDS);
                    if (msg != null) {
                        logBatch.add(msg);
                        while ((msg = mLogQueue.poll()) != null)
                            logBatch.add(msg);
                    }

                    long now = SystemClock.elapsedRealtime() / 1000;

                    if (!logBatch.isEmpty()) {
                        mLastLog = now;
                        mLogCounter += logBatch.size();
                        logToFile(logBatch);
                        logBatch.clear();
                    }

                    if ((now - mLastUpload) >= mUploadIntervalSecs || mLogCounter >= mUploadIntervalLogCount) {
                        postLogs();
                    }

                    if (((now - mLastLog) >= mIdleSecs) && mIdleSecs > 0 && mLastLog > 0) {
                        mThread.interrupt();
                    }

                } catch (InterruptedException e) {
                    mLogQueue.drainTo(logBatch);
                    logToFile(logBatch);
                    postLogs();
                    return;
                }
            }
        }
    });

    mThread.start();
}

From source file:com.frostwire.android.gui.fragments.MyFilesFragment.java

@Override
protected void initComponents(View v, Bundle savedInstanceState) {
    findView(v, R.id.fragment_my_files_select_all_container).setVisibility(View.GONE);
    findView(v, R.id.progressContainer).setVisibility(View.GONE);
    selectAllCheckboxListener = (buttonView, isChecked) -> onSelectAllChecked(isChecked);
    selectAllCheckbox = findView(v, R.id.fragment_my_files_select_all_checkbox);
    selectAllCheckboxContainer = findView(v, R.id.fragment_my_files_select_all_container);
    swipeRefresh = findView(v, R.id.fragment_my_files_swipe_refresh);
    swipeRefresh.setOnRefreshListener(() -> {
        long now = SystemClock.elapsedRealtime();
        if ((now - lastAdapterRefresh) > 5000) {
            refreshSelection();//w w w.  ja  v a2 s.c  o m
        } else {
            swipeRefresh.setRefreshing(false);
        }
    });
    list = findView(v, R.id.fragment_my_files_gridview);
    list.setOnScrollListener(new ScrollListeners.FastScrollDisabledWhenIdleOnScrollListener());

    SwipeLayout swipe = findView(v, R.id.fragment_my_files_swipe);
    swipe.setOnSwipeListener(new SwipeLayout.OnSwipeListener() {
        @Override
        public void onSwipeLeft() {
            switchToThe(true);
        }

        @Override
        public void onSwipeRight() {
            switchToThe(false);
        }
    });

    tabLayout = findView(v, R.id.fragment_my_files_tab_layout_file_type);
    tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            tabClicked(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {
            tabClicked(tab.getPosition());
        }
    });
}

From source file:com.farmerbb.taskbar.service.TaskbarService.java

@SuppressLint("RtlHardcoded")
private void drawTaskbar() {
    IconCache.getInstance(this).clearCache();

    // Initialize layout params
    windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
    U.setCachedRotation(windowManager.getDefaultDisplay().getRotation());

    final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.TYPE_PHONE,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
            PixelFormat.TRANSLUCENT);/*from w  ww .j  a va  2s.  co  m*/

    // Determine where to show the taskbar on screen
    switch (U.getTaskbarPosition(this)) {
    case "bottom_left":
        layoutId = R.layout.taskbar_left;
        params.gravity = Gravity.BOTTOM | Gravity.LEFT;
        positionIsVertical = false;
        break;
    case "bottom_vertical_left":
        layoutId = R.layout.taskbar_vertical;
        params.gravity = Gravity.BOTTOM | Gravity.LEFT;
        positionIsVertical = true;
        break;
    case "bottom_right":
        layoutId = R.layout.taskbar_right;
        params.gravity = Gravity.BOTTOM | Gravity.RIGHT;
        positionIsVertical = false;
        break;
    case "bottom_vertical_right":
        layoutId = R.layout.taskbar_vertical;
        params.gravity = Gravity.BOTTOM | Gravity.RIGHT;
        positionIsVertical = true;
        break;
    case "top_left":
        layoutId = R.layout.taskbar_left;
        params.gravity = Gravity.TOP | Gravity.LEFT;
        positionIsVertical = false;
        break;
    case "top_vertical_left":
        layoutId = R.layout.taskbar_top_vertical;
        params.gravity = Gravity.TOP | Gravity.LEFT;
        positionIsVertical = true;
        break;
    case "top_right":
        layoutId = R.layout.taskbar_right;
        params.gravity = Gravity.TOP | Gravity.RIGHT;
        positionIsVertical = false;
        break;
    case "top_vertical_right":
        layoutId = R.layout.taskbar_top_vertical;
        params.gravity = Gravity.TOP | Gravity.RIGHT;
        positionIsVertical = true;
        break;
    }

    // Initialize views
    int theme = 0;

    SharedPreferences pref = U.getSharedPreferences(this);
    switch (pref.getString("theme", "light")) {
    case "light":
        theme = R.style.AppTheme;
        break;
    case "dark":
        theme = R.style.AppTheme_Dark;
        break;
    }

    boolean altButtonConfig = pref.getBoolean("alt_button_config", false);

    ContextThemeWrapper wrapper = new ContextThemeWrapper(this, theme);
    layout = (LinearLayout) LayoutInflater.from(wrapper).inflate(layoutId, null);
    taskbar = (LinearLayout) layout.findViewById(R.id.taskbar);
    scrollView = (FrameLayout) layout.findViewById(R.id.taskbar_scrollview);

    if (altButtonConfig) {
        space = (Space) layout.findViewById(R.id.space_alt);
        layout.findViewById(R.id.space).setVisibility(View.GONE);
    } else {
        space = (Space) layout.findViewById(R.id.space);
        layout.findViewById(R.id.space_alt).setVisibility(View.GONE);
    }

    space.setOnClickListener(v -> toggleTaskbar());

    startButton = (ImageView) layout.findViewById(R.id.start_button);
    int padding;

    if (pref.getBoolean("app_drawer_icon", false)) {
        startButton.setImageDrawable(ContextCompat.getDrawable(this, R.mipmap.ic_launcher));
        padding = getResources().getDimensionPixelSize(R.dimen.app_drawer_icon_padding_alt);
    } else {
        startButton.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.all_apps_button_icon));
        padding = getResources().getDimensionPixelSize(R.dimen.app_drawer_icon_padding);
    }

    startButton.setPadding(padding, padding, padding, padding);
    startButton.setOnClickListener(ocl);
    startButton.setOnLongClickListener(view -> {
        openContextMenu();
        return true;
    });

    startButton.setOnGenericMotionListener((view, motionEvent) -> {
        if (motionEvent.getAction() == MotionEvent.ACTION_BUTTON_PRESS
                && motionEvent.getButtonState() == MotionEvent.BUTTON_SECONDARY)
            openContextMenu();

        return false;
    });

    refreshInterval = (int) (Float.parseFloat(pref.getString("refresh_frequency", "2")) * 1000);
    if (refreshInterval == 0)
        refreshInterval = 100;

    sortOrder = pref.getString("sort_order", "false");
    runningAppsOnly = pref.getString("recents_amount", "past_day").equals("running_apps_only");

    switch (pref.getString("recents_amount", "past_day")) {
    case "past_day":
        searchInterval = System.currentTimeMillis() - AlarmManager.INTERVAL_DAY;
        break;
    case "app_start":
        long oneDayAgo = System.currentTimeMillis() - AlarmManager.INTERVAL_DAY;
        long appStartTime = pref.getLong("time_of_service_start", System.currentTimeMillis());
        long deviceStartTime = System.currentTimeMillis() - SystemClock.elapsedRealtime();
        long startTime = deviceStartTime > appStartTime ? deviceStartTime : appStartTime;

        searchInterval = startTime > oneDayAgo ? startTime : oneDayAgo;
        break;
    }

    Intent intent = new Intent("com.farmerbb.taskbar.HIDE_START_MENU");
    LocalBroadcastManager.getInstance(TaskbarService.this).sendBroadcast(intent);

    if (altButtonConfig) {
        button = (Button) layout.findViewById(R.id.hide_taskbar_button_alt);
        layout.findViewById(R.id.hide_taskbar_button).setVisibility(View.GONE);
    } else {
        button = (Button) layout.findViewById(R.id.hide_taskbar_button);
        layout.findViewById(R.id.hide_taskbar_button_alt).setVisibility(View.GONE);
    }

    try {
        button.setTypeface(Typeface.createFromFile("/system/fonts/Roboto-Regular.ttf"));
    } catch (RuntimeException e) {
        /* Gracefully fail */ }

    updateButton(false);
    button.setOnClickListener(v -> toggleTaskbar());

    LinearLayout buttonLayout = (LinearLayout) layout.findViewById(
            altButtonConfig ? R.id.hide_taskbar_button_layout_alt : R.id.hide_taskbar_button_layout);
    if (buttonLayout != null)
        buttonLayout.setOnClickListener(v -> toggleTaskbar());

    LinearLayout buttonLayoutToHide = (LinearLayout) layout.findViewById(
            altButtonConfig ? R.id.hide_taskbar_button_layout : R.id.hide_taskbar_button_layout_alt);
    if (buttonLayoutToHide != null)
        buttonLayoutToHide.setVisibility(View.GONE);

    int backgroundTint = U.getBackgroundTint(this);
    int accentColor = U.getAccentColor(this);

    dashboardButton = (FrameLayout) layout.findViewById(R.id.dashboard_button);
    navbarButtons = (LinearLayout) layout.findViewById(R.id.navbar_buttons);

    dashboardEnabled = pref.getBoolean("dashboard", false);
    if (dashboardEnabled) {
        layout.findViewById(R.id.square1).setBackgroundColor(accentColor);
        layout.findViewById(R.id.square2).setBackgroundColor(accentColor);
        layout.findViewById(R.id.square3).setBackgroundColor(accentColor);
        layout.findViewById(R.id.square4).setBackgroundColor(accentColor);
        layout.findViewById(R.id.square5).setBackgroundColor(accentColor);
        layout.findViewById(R.id.square6).setBackgroundColor(accentColor);

        dashboardButton.setOnClickListener(v -> LocalBroadcastManager.getInstance(TaskbarService.this)
                .sendBroadcast(new Intent("com.farmerbb.taskbar.TOGGLE_DASHBOARD")));
    } else
        dashboardButton.setVisibility(View.GONE);

    if (pref.getBoolean("button_back", false)) {
        navbarButtonsEnabled = true;

        ImageView backButton = (ImageView) layout.findViewById(R.id.button_back);
        backButton.setVisibility(View.VISIBLE);
        backButton.setOnClickListener(v -> {
            U.sendAccessibilityAction(this, AccessibilityService.GLOBAL_ACTION_BACK);
            if (pref.getBoolean("hide_taskbar", true)
                    && !FreeformHackHelper.getInstance().isInFreeformWorkspace())
                hideTaskbar(true);
        });
    }

    if (pref.getBoolean("button_home", false)) {
        navbarButtonsEnabled = true;

        ImageView homeButton = (ImageView) layout.findViewById(R.id.button_home);
        homeButton.setVisibility(View.VISIBLE);
        homeButton.setOnClickListener(v -> {
            U.sendAccessibilityAction(this, AccessibilityService.GLOBAL_ACTION_HOME);
            if (pref.getBoolean("hide_taskbar", true)
                    && !FreeformHackHelper.getInstance().isInFreeformWorkspace())
                hideTaskbar(true);
        });

        homeButton.setOnLongClickListener(v -> {
            Intent voiceSearchIntent = new Intent(RecognizerIntent.ACTION_VOICE_SEARCH_HANDS_FREE);
            voiceSearchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            try {
                startActivity(voiceSearchIntent);
            } catch (ActivityNotFoundException e) {
                /* Gracefully fail */ }

            if (pref.getBoolean("hide_taskbar", true)
                    && !FreeformHackHelper.getInstance().isInFreeformWorkspace())
                hideTaskbar(true);

            return true;
        });

        homeButton.setOnGenericMotionListener((view13, motionEvent) -> {
            if (motionEvent.getAction() == MotionEvent.ACTION_BUTTON_PRESS
                    && motionEvent.getButtonState() == MotionEvent.BUTTON_SECONDARY) {
                Intent voiceSearchIntent = new Intent(RecognizerIntent.ACTION_VOICE_SEARCH_HANDS_FREE);
                voiceSearchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                try {
                    startActivity(voiceSearchIntent);
                } catch (ActivityNotFoundException e) {
                    /* Gracefully fail */ }

                if (pref.getBoolean("hide_taskbar", true)
                        && !FreeformHackHelper.getInstance().isInFreeformWorkspace())
                    hideTaskbar(true);
            }
            return true;
        });
    }

    if (pref.getBoolean("button_recents", false)) {
        navbarButtonsEnabled = true;

        ImageView recentsButton = (ImageView) layout.findViewById(R.id.button_recents);
        recentsButton.setVisibility(View.VISIBLE);
        recentsButton.setOnClickListener(v -> {
            U.sendAccessibilityAction(this, AccessibilityService.GLOBAL_ACTION_RECENTS);
            if (pref.getBoolean("hide_taskbar", true)
                    && !FreeformHackHelper.getInstance().isInFreeformWorkspace())
                hideTaskbar(true);
        });

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            recentsButton.setOnLongClickListener(v -> {
                U.sendAccessibilityAction(this, AccessibilityService.GLOBAL_ACTION_TOGGLE_SPLIT_SCREEN);
                if (pref.getBoolean("hide_taskbar", true)
                        && !FreeformHackHelper.getInstance().isInFreeformWorkspace())
                    hideTaskbar(true);

                return true;
            });

            recentsButton.setOnGenericMotionListener((view13, motionEvent) -> {
                if (motionEvent.getAction() == MotionEvent.ACTION_BUTTON_PRESS
                        && motionEvent.getButtonState() == MotionEvent.BUTTON_SECONDARY) {
                    U.sendAccessibilityAction(this, AccessibilityService.GLOBAL_ACTION_TOGGLE_SPLIT_SCREEN);
                    if (pref.getBoolean("hide_taskbar", true)
                            && !FreeformHackHelper.getInstance().isInFreeformWorkspace())
                        hideTaskbar(true);
                }
                return true;
            });
        }
    }

    if (!navbarButtonsEnabled)
        navbarButtons.setVisibility(View.GONE);

    layout.setBackgroundColor(backgroundTint);
    layout.findViewById(R.id.divider).setBackgroundColor(accentColor);
    button.setTextColor(accentColor);

    if (isFirstStart && FreeformHackHelper.getInstance().isInFreeformWorkspace())
        showTaskbar(false);
    else if (!pref.getBoolean("collapsed", false) && pref.getBoolean("taskbar_active", false))
        toggleTaskbar();

    LocalBroadcastManager.getInstance(this).unregisterReceiver(showReceiver);
    LocalBroadcastManager.getInstance(this).unregisterReceiver(hideReceiver);
    LocalBroadcastManager.getInstance(this).unregisterReceiver(tempShowReceiver);
    LocalBroadcastManager.getInstance(this).unregisterReceiver(tempHideReceiver);

    LocalBroadcastManager.getInstance(this).registerReceiver(showReceiver,
            new IntentFilter("com.farmerbb.taskbar.SHOW_TASKBAR"));
    LocalBroadcastManager.getInstance(this).registerReceiver(hideReceiver,
            new IntentFilter("com.farmerbb.taskbar.HIDE_TASKBAR"));
    LocalBroadcastManager.getInstance(this).registerReceiver(tempShowReceiver,
            new IntentFilter("com.farmerbb.taskbar.TEMP_SHOW_TASKBAR"));
    LocalBroadcastManager.getInstance(this).registerReceiver(tempHideReceiver,
            new IntentFilter("com.farmerbb.taskbar.TEMP_HIDE_TASKBAR"));

    startRefreshingRecents();

    windowManager.addView(layout, params);

    isFirstStart = false;
}

From source file:com.android.messaging.datamodel.action.SyncMessagesAction.java

/**
 * Compare messages based on timestamp and uri
 * @param db local database wrapper/*from  w w  w .  j a  v a  2  s  . co  m*/
 * @param cursors cursor pair holding references to local and remote messages
 * @param smsToAdd newly found sms messages to add
 * @param mmsToAdd newly found mms messages to add
 * @param messagesToDelete messages not found needing deletion
 * @param maxMessagesToScan max messages to scan for changes
 * @param maxMessagesToUpdate max messages to return for updates
 * @param cache cache for conversation id / thread id / recipient set mapping
 * @return timestamp of the oldest message seen during the sync scan
 */
private long syncCursorPair(final DatabaseWrapper db, final SyncCursorPair cursors,
        final ArrayList<SmsMessage> smsToAdd, final LongSparseArray<MmsMessage> mmsToAdd,
        final ArrayList<LocalDatabaseMessage> messagesToDelete, final int maxMessagesToScan,
        final int maxMessagesToUpdate, final ThreadInfoCache cache) {
    long lastTimestampMillis;
    final long startTimeMillis = SystemClock.elapsedRealtime();

    // Number of messages scanned local and remote
    int localPos = 0;
    int remotePos = 0;
    int localTotal = 0;
    int remoteTotal = 0;
    // Scan through the messages on both sides and prepare messages for local message table
    // changes (including adding and deleting)
    try {
        cursors.query(db);

        localTotal = cursors.getLocalCount();
        remoteTotal = cursors.getRemoteCount();

        if (LogUtil.isLoggable(TAG, LogUtil.DEBUG)) {
            LogUtil.d(TAG,
                    "SyncMessagesAction: Scanning cursors (local count = " + localTotal + ", remote count = "
                            + remoteTotal + ", message update limit = " + maxMessagesToUpdate
                            + ", message scan limit = " + maxMessagesToScan + ")");
        }

        lastTimestampMillis = cursors.scan(maxMessagesToScan, maxMessagesToUpdate, smsToAdd, mmsToAdd,
                messagesToDelete, cache);

        localPos = cursors.getLocalPosition();
        remotePos = cursors.getRemotePosition();

        if (LogUtil.isLoggable(TAG, LogUtil.DEBUG)) {
            LogUtil.d(TAG, "SyncMessagesAction: Scanned cursors (local position = " + localPos + " of "
                    + localTotal + ", remote position = " + remotePos + " of " + remoteTotal + ")");
        }

        // Batch loading the parts of the MMS messages in this batch
        loadMmsParts(mmsToAdd);
        // Lookup senders for incoming mms messages
        setMmsSenders(mmsToAdd, cache);
    } catch (final SQLiteException e) {
        LogUtil.e(TAG, "SyncMessagesAction: Database exception", e);
        // Let's abort
        lastTimestampMillis = SYNC_FAILED;
    } catch (final Exception e) {
        // We want to catch anything unexpected since this is running in a separate thread
        // and any unexpected exception will just fail this thread silently.
        // Let's crash for dogfooders!
        LogUtil.wtf(TAG, "SyncMessagesAction: unexpected failure in scan", e);
        lastTimestampMillis = SYNC_FAILED;
    } finally {
        if (cursors != null) {
            cursors.close();
        }
    }

    final long endTimeMillis = SystemClock.elapsedRealtime();

    if (LogUtil.isLoggable(TAG, LogUtil.DEBUG)) {
        LogUtil.d(TAG,
                "SyncMessagesAction: Scan complete (took " + (endTimeMillis - startTimeMillis) + " ms). "
                        + smsToAdd.size() + " remote SMS to add, " + mmsToAdd.size() + " MMS to add, "
                        + messagesToDelete.size() + " local messages to delete. " + "Oldest timestamp seen = "
                        + lastTimestampMillis);
    }

    return lastTimestampMillis;
}

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

private void onAlarmOrLocation(boolean force) {
    if (!isActive.get())
        return;/*from w w w. j a  v  a  2s .com*/

    updateNotification();
    final long now = SystemClock.elapsedRealtime();
    final long lastTestDelta = now - loopModeResults.getLastTestTime();

    Log.d(TAG, "onAlarmOrLocation; force:" + force);

    if (isRunning.get()) {
        if (lastTestDelta >= RMBTService.DEADMAN_TIME) {
            Log.e(TAG, "still running after " + lastTestDelta + " - assuming crash");
            isRunning.set(false); // assume crash and carry on
        } else {
            setAlarm(10000); // check again in 10s
            return;
        }
    }

    boolean run = false;

    if (force)
        run = true;

    if (!run) {
        Log.d(TAG, "lastTestDelta: " + lastTestDelta);

        long delay = loopModeResults.getMaxDelay();
        if (loopModeResults.getLastDistance() >= loopModeResults.getMaxMovement()
                && loopModeResults.getLastAccuracy() > 0.0f
                && loopModeResults.getLastAccuracy() <= AppConstants.LOOP_MODE_GPS_ACCURACY_CRITERIA) {
            Log.d(TAG, "lastDistance >= maxMovement; triggerTest");
            delay = loopModeResults.getMinDelay();
        }

        if (lastTestDelta + ACCEPT_INACCURACY >= delay) {
            Log.d(TAG, "accept delay (" + delay + "); triggerTest");
            run = true;
        }
    }

    if (run)
        triggerTest();

    if (loopModeResults.getMaxTests() == 0
            || loopModeResults.getNumberOfTests() <= loopModeResults.getMaxTests()) {
        setAlarm(10000);
    } else
        stopSelf();

    //setAlarm(delay - lastTestDelta);
}

From source file:com.lgallardo.youtorrentcontroller.RefreshListener.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Get preferences
    getSettings();/*from  w w w  .  j a  v  a2  s  .  c o m*/

    // Set alarm for checking completed torrents, if not set
    if (PendingIntent.getBroadcast(getApplication(), 0, new Intent(getApplication(), NotifierService.class),
            PendingIntent.FLAG_NO_CREATE) == null) {

        // Set Alarm for checking completed torrents
        alarmMgr = (AlarmManager) getApplication().getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(getApplication(), NotifierService.class);
        alarmIntent = PendingIntent.getBroadcast(getApplication(), 0, intent, 0);

        alarmMgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 5000,
                notification_period, alarmIntent);
    }

    // Set alarm for RSS checking, if not set
    if (PendingIntent.getBroadcast(getApplication(), 0, new Intent(getApplication(), RSSService.class),
            PendingIntent.FLAG_NO_CREATE) == null) {

        // Set Alarm for checking completed torrents
        alarmMgr = (AlarmManager) getApplication().getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(getApplication(), RSSService.class);
        alarmIntent = PendingIntent.getBroadcast(getApplication(), 0, intent, 0);

        alarmMgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 5000,
                AlarmManager.INTERVAL_DAY, alarmIntent);
    }

    // Set Theme (It must be fore inflating or setContentView)
    if (dark_ui) {
        this.setTheme(R.style.Theme_Dark);

        if (Build.VERSION.SDK_INT >= 21) {
            getWindow().setNavigationBarColor(getResources().getColor(R.color.Theme_Dark_toolbarBackground));
            getWindow().setStatusBarColor(getResources().getColor(R.color.Theme_Dark_toolbarBackground));
        }
    } else {
        this.setTheme(R.style.Theme_Light);

        if (Build.VERSION.SDK_INT >= 21) {
            getWindow().setNavigationBarColor(getResources().getColor(R.color.primary));
        }

    }

    setContentView(R.layout.activity_main);

    toolbar = (Toolbar) findViewById(R.id.app_bar);

    if (dark_ui) {
        toolbar.setBackgroundColor(getResources().getColor(R.color.Theme_Dark_primary));
    }

    setSupportActionBar(toolbar);

    // Set App title
    setTitle(R.string.app_shortname);

    // Drawer menu
    navigationDrawerServerItems = getResources().getStringArray(R.array.qBittorrentServers);
    navigationDrawerItemTitles = getResources().getStringArray(R.array.navigation_drawer_items_array);

    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

    //        drawerList = (ListView) findViewById(R.id.left_drawer);

    mRecyclerView = (RecyclerView) findViewById(R.id.RecyclerView); // Assigning the RecyclerView Object to the xml View
    mRecyclerView.setHasFixedSize(true); // Letting the system know that the list objects are

    ArrayList<ObjectDrawerItem> serverItems = new ArrayList<ObjectDrawerItem>();
    ArrayList<ObjectDrawerItem> actionItems = new ArrayList<ObjectDrawerItem>();
    ArrayList<ObjectDrawerItem> settingsItems = new ArrayList<ObjectDrawerItem>();

    // Add server category
    serverItems.add(new ObjectDrawerItem(R.drawable.ic_drawer_servers,
            getResources().getString(R.string.drawer_servers_category), DRAWER_CATEGORY, false, null));

    // Server items
    int currentServerValue = 1;

    try {
        currentServerValue = Integer.parseInt(MainActivity.currentServer);
    } catch (NumberFormatException e) {

    }

    for (int i = 0; i < navigationDrawerServerItems.length; i++) {
        //            Log.d("Debug", "MainActivity - currentServerValue - currentServerValue: " + currentServerValue);
        //            Log.d("Debug", "MainActivity - currentServerValue - (i + 1): " + (i + 1));
        //            Log.d("Debug", "MainActivity - currentServerValue - (i + 1) == currentServerValue: " + ((i + 1) == currentServerValue));

        serverItems.add(new ObjectDrawerItem(R.drawable.ic_drawer_subitem, navigationDrawerServerItems[i],
                DRAWER_ITEM_SERVERS, ((i + 1) == currentServerValue), "changeCurrentServer"));

    }

    //
    //        serverItems.add(new ObjectDrawerItem(R.drawable.ic_drawer_subitem, "Server 1", DRAWER_ITEM_SERVERS, true, "changeCurrentServer"));
    //        serverItems.add(new ObjectDrawerItem(R.drawable.ic_drawer_subitem, "Server 2", DRAWER_ITEM_SERVERS, false, "changeCurrentServer"));
    //        serverItems.add(new ObjectDrawerItem(R.drawable.ic_drawer_subitem, "Server 3", DRAWER_ITEM_SERVERS, false, "changeCurrentServer"));

    // Add actions
    actionItems.add(new ObjectDrawerItem(R.drawable.ic_drawer_all, navigationDrawerItemTitles[0],
            DRAWER_ITEM_ACTIONS, lastState.equals("all"), "refreshAll"));
    actionItems.add(new ObjectDrawerItem(R.drawable.ic_drawer_downloading, navigationDrawerItemTitles[1],
            DRAWER_ITEM_ACTIONS, lastState.equals("downloading"), "refreshDownloading"));
    actionItems.add(new ObjectDrawerItem(R.drawable.ic_drawer_completed, navigationDrawerItemTitles[2],
            DRAWER_ITEM_ACTIONS, lastState.equals("completed"), "refreshCompleted"));
    actionItems.add(new ObjectDrawerItem(R.drawable.ic_drawer_paused, navigationDrawerItemTitles[3],
            DRAWER_ITEM_ACTIONS, lastState.equals("pause"), "refreshPaused"));
    actionItems.add(new ObjectDrawerItem(R.drawable.ic_drawer_active, navigationDrawerItemTitles[4],
            DRAWER_ITEM_ACTIONS, lastState.equals("active"), "refreshActive"));
    actionItems.add(new ObjectDrawerItem(R.drawable.ic_drawer_inactive, navigationDrawerItemTitles[5],
            DRAWER_ITEM_ACTIONS, lastState.equals("inactive"), "refreshInactive"));

    // Add settings actions
    //        drawerItems.add(new ObjectDrawerItem(R.drawable.ic_action_options, navigationDrawerItemTitles[6], DRAWER_ITEM_ACTIONS, false, "openOptions"));
    settingsItems.add(new ObjectDrawerItem(R.drawable.ic_drawer_settings, navigationDrawerItemTitles[6],
            DRAWER_ITEM_ACTIONS, false, "openSettings"));
    if (packageName.equals("com.lgallardo.youtorrentcontroller")) {
        settingsItems.add(new ObjectDrawerItem(R.drawable.ic_drawer_pro, navigationDrawerItemTitles[7],
                DRAWER_ITEM_ACTIONS, false, "getPro"));
        settingsItems.add(new ObjectDrawerItem(R.drawable.ic_drawer_help, navigationDrawerItemTitles[8],
                DRAWER_ITEM_ACTIONS, false, "openHelp"));
    } else {
        settingsItems.add(new ObjectDrawerItem(R.drawable.ic_drawer_help, navigationDrawerItemTitles[7],
                DRAWER_ITEM_ACTIONS, false, "openHelp"));
    }

    // Set adapter

    rAdapter = new DrawerItemRecyclerViewAdapter(getApplicationContext(), this, serverItems, actionItems,
            settingsItems, null);
    rAdapter.notifyDataSetChanged();

    //        Log.d("Debug", "MainActivity - oldActionPosition: "+ (Arrays.asList(actionStates).indexOf(lastState)));

    //        drawerList.setAdapter(adapter);
    mRecyclerView.setAdapter(rAdapter);

    mLayoutManager = new LinearLayoutManager(this); // Creating a layout Manager
    mRecyclerView.setLayoutManager(mLayoutManager); // Setting the layout Manager

    // Set selection according to last state
    setSelectionAndTitle(lastState);

    // Set the item click listener
    //        drawerList.setOnItemClickListener(new DrawerItemClickListener());

    // Get drawer title
    title = drawerTitle = getTitle();

    // Add the application icon control code inside MainActivity onCreate

    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

    // New ActionBarDrawerToggle for Google Material Desing (v7)
    drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open,
            R.string.drawer_close) {

        /**
         * Called when a drawer has settled in a completely closed state.
         */
        public void onDrawerClosed(View view) {
            super.onDrawerClosed(view);
            // getSupportActionBar().setTitle(title);
        }

        /**
         * Called when a drawer has settled in a completely open state.
         */
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            // getSupportActionBar().setTitle(drawerTitle);
            // setTitle(R.string.app_shortname);
        }
    };

    drawerLayout.setDrawerListener(drawerToggle);
    //        drawerToggle.syncState();               // Finally we set the drawer toggle sync State

    getSupportActionBar().setDisplayHomeAsUpEnabled(false);
    getSupportActionBar().setHomeButtonEnabled(false);

    // Get options and save them as shared preferences
    //        qBittorrentOptions qso = new qBittorrentOptions();
    //        qso.execute(new String[]{qbQueryString + "/preferences", "getSettings"});

    // If it were awaked from an intent-filter,
    // Get token and cookie and then
    // get intent from the intent filter and Add URL torrent
    //        Log.d("Debug", "MainActivity - 1");
    new torrentTokenByIntent().execute(getIntent());

    // Fragments

    // Check whether the activity is using the layout version with
    // the fragment_container FrameLayout. If so, we must add the first
    // fragment
    if (findViewById(R.id.fragment_container) != null) {

        // However, if we're being restored from a previous state,
        // then we don't need to do anything and should return or else
        // we could end up with overlapping fragments.
        // if (savedInstanceState != null) {
        // return;
        // }

        // This fragment will hold the list of torrents
        if (firstFragment == null) {
            firstFragment = new com.lgallardo.youtorrentcontroller.ItemstFragment();
        }

        // This fragment will hold the list of torrents
        helpTabletFragment = new HelpFragment();

        // Set the second fragments container
        firstFragment.setSecondFragmentContainer(R.id.content_frame);

        // This i the second fragment, holding a default message at the
        // beginning
        secondFragment = new AboutFragment();

        // Add the fragment to the 'list_frame' FrameLayout
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        if (fragmentManager.findFragmentByTag("firstFragment") == null) {
            fragmentTransaction.add(R.id.list_frame, helpTabletFragment, "firstFragment");
        } else {
            fragmentTransaction.replace(R.id.list_frame, helpTabletFragment, "firstFragment");
        }

        if (fragmentManager.findFragmentByTag("secondFragment") == null) {
            fragmentTransaction.add(R.id.content_frame, secondFragment, "secondFragment");
        } else {
            fragmentTransaction.replace(R.id.content_frame, secondFragment, "secondFragment");
        }

        fragmentTransaction.commit();

        // Second fragment will be added in ItemsFRagment's onListItemClick
        // method

    } else {

        // Phones handle just one fragment

        // Create an instance of ItemsFragments
        if (firstFragment == null) {
            firstFragment = new com.lgallardo.youtorrentcontroller.ItemstFragment();
        }
        firstFragment.setSecondFragmentContainer(R.id.one_frame);

        // This is the about fragment, holding a default message at the
        // beginning
        secondFragment = new AboutFragment();

        // If we're being restored from a previous state,
        // then we don't need to do anything and should return or else
        // we could end up with overlapping fragments.
        //            if (savedInstanceState != null) {
        //
        //                // Handle Item list empty due to Fragment stack
        //                try {
        //                    FragmentManager fm = getFragmentManager();
        //
        //                    if (fm.getBackStackEntryCount() == 1 && fm.findFragmentById(R.id.one_frame) instanceof com.lgallardo.youtorrentcontroller.TorrentDetailsFragment) {
        //
        //                        refreshCurrent();
        //
        //                    }
        //                }
        //                catch (Exception e) {
        //                }
        //
        //                return;
        //            }

        // Add the fragment to the 'list_frame' FrameLayout
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        if (fragmentManager.findFragmentByTag("firstFragment") == null) {
            fragmentTransaction.add(R.id.one_frame, secondFragment, "firstFragment");
        } else {
            fragmentTransaction.replace(R.id.one_frame, secondFragment, "firstFragment");
        }

        // if torrent details was loaded reset back button stack
        for (int i = 0; i < fragmentManager.getBackStackEntryCount(); ++i) {
            fragmentManager.popBackStack();
        }

        fragmentTransaction.commit();
    }

    // Activity is visible
    activityIsVisible = true;

    // First refresh
    refreshCurrent();

    handler = new Handler();
    handler.postDelayed(m_Runnable, refresh_period);

    // Load banner
    loadBanner();

}

From source file:com.google.android.apps.location.gps.gnsslogger.FileLogger.java

private void writeGnssMeasurementToFile(GnssClock clock, GnssMeasurement measurement) throws IOException {
    String clockStream = String.format("Raw,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s", SystemClock.elapsedRealtime(),
            clock.getTimeNanos(), clock.hasLeapSecond() ? clock.getLeapSecond() : "",
            clock.hasTimeUncertaintyNanos() ? clock.getTimeUncertaintyNanos() : "", clock.getFullBiasNanos(),
            clock.hasBiasNanos() ? clock.getBiasNanos() : "",
            clock.hasBiasUncertaintyNanos() ? clock.getBiasUncertaintyNanos() : "",
            clock.hasDriftNanosPerSecond() ? clock.getDriftNanosPerSecond() : "",
            clock.hasDriftUncertaintyNanosPerSecond() ? clock.getDriftUncertaintyNanosPerSecond() : "",
            clock.getHardwareClockDiscontinuityCount() + ",");
    mFileWriter.write(clockStream);//from  www  . j ava  2 s  .c o m

    String measurementStream = String.format("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s",
            measurement.getSvid(), measurement.getTimeOffsetNanos(), measurement.getState(),
            measurement.getReceivedSvTimeNanos(), measurement.getReceivedSvTimeUncertaintyNanos(),
            measurement.getCn0DbHz(), measurement.getPseudorangeRateMetersPerSecond(),
            measurement.getPseudorangeRateUncertaintyMetersPerSecond(),
            measurement.getAccumulatedDeltaRangeState(), measurement.getAccumulatedDeltaRangeMeters(),
            measurement.getAccumulatedDeltaRangeUncertaintyMeters(),
            measurement.hasCarrierFrequencyHz() ? measurement.getCarrierFrequencyHz() : "",
            measurement.hasCarrierCycles() ? measurement.getCarrierCycles() : "",
            measurement.hasCarrierPhase() ? measurement.getCarrierPhase() : "",
            measurement.hasCarrierPhaseUncertainty() ? measurement.getCarrierPhaseUncertainty() : "",
            measurement.getMultipathIndicator(), measurement.hasSnrInDb() ? measurement.getSnrInDb() : "",
            measurement.getConstellationType(),
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && measurement.hasAutomaticGainControlLevelDb()
                    ? measurement.getAutomaticGainControlLevelDb()
                    : "",
            measurement.hasCarrierFrequencyHz() ? measurement.getCarrierFrequencyHz() : "");
    mFileWriter.write(measurementStream);
    mFileWriter.newLine();
}

From source file:com.example.Android.LoginActivity.java

@Override
public void processFinish(String output, ActionEnum action) {
    switch (action) {
    case RegisterDevice: {
        if (output.contains("True") || output.contains("true")) {
            mDisplay.append("Done" + "\n");
            mDisplay.append("Retrieving device tree...");

            asyncTask.setActionMethod(ActionEnum.Device);
            asyncTask.DownloadData(Constants.URL_RetrievePublishersTree);
        } else {/*from www  .ja  v a  2  s.c  o m*/
            mDisplay.append("Failed" + "\n");
            OnPXIInitializationFailed();
        }
        break;
    }
    case Device: {
        try {
            output.replace("GetLicensedDevices", "");
            is = new ByteArrayInputStream(output.getBytes("UTF-8"));
            DeviceXmlParser parser = new DeviceXmlParser();
            devices = parser.parse(is);
        } catch (Exception ex) {
            mDisplay.append("Failed" + "\n");
            OnPXIInitializationFailed();
            ex.printStackTrace();
        }

        String data = "<pay s='Atge' method='23'><req>"
                + "<EventsAlarmsCountAndData id='-4' rec='1' tyd='0' strt='10/20/2013 18:30:00' "
                + "end='10/30/2014 18:29:59' apfl='7,6' rcnt='0' max='342' grp='0' msc='-413' />"
                + "<EventsAlarmsCountAndData id='-4' rec='1' tyd='0' strt='10/20/2013 18:30:00' "
                + "end='10/30/2014 18:29:59' apfl='7,6' rcnt='0' max='19' grp='0' msc='-415' />"
                + "</req></pay>";

        byte[] bytes = null;
        try {
            bytes = data.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            mDisplay.append("Failed" + "\n");
            OnPXIInitializationFailed();
            e.printStackTrace();
        }

        asyncTask.setHTTPMethod("POST");
        asyncTask.setActionMethod(ActionEnum.Alarm);
        asyncTask.setPostData(bytes);
        asyncTask.DownloadData(
                "http://pxiinsight.cloudapp.net/PXInsight/PxsDownloadData.pxsdownloaddata?kind=pxsdownloaddata&requesttype=Alarm");

        //SendAlarmHttpRequest();
        break;
    }
    case Alarm: {
        is = null;
        try {
            is = new ByteArrayInputStream(output.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            mDisplay.append("Failed" + "\n");
            OnPXIInitializationFailed();
            e.printStackTrace();
        }

        AlarmXmlParser alarmParser = new AlarmXmlParser();
        try {
            List<AlarmEventSummary> alarms = alarmParser.parse(is);

            for (AlarmEventSummary ae : alarms) {
                for (Device d : devices) {
                    if (ae.nodeId == Integer.parseInt(d.deviceId)) {
                        d.alarmEventSummary.add(ae);
                        break;
                    }
                }
            }

            for (Device d : devices) {
                ArrayList<Device> dev = new ArrayList<Device>();
                if (mapOfDevices.containsKey(d.publisherName)) {
                    mapOfDevices.get(d.publisherName).add(d);
                } else {
                    dev.add(d);
                    mapOfDevices.put(d.publisherName, dev);
                }
            }

            String results = new Gson().toJson(mapOfDevices);

            mDisplay.append("Done" + "\n");

            // Add some delay
            for (int i = 0; i < 3; i++) {
                Log.i(TAG, "Working... " + (i + 1) + "/5 @ " + SystemClock.elapsedRealtime());
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                }
            }

            Intent myIntent = new Intent(LoginActivity.this, DevicesActivity.class);
            myIntent.putExtra(Constants.DEVICES_EXTRA_MESSAGE, results);
            startActivity(myIntent);
            finish();

        } catch (XmlPullParserException e) {
            // TODO Auto-generated catch block
            mDisplay.append("Failed" + "\n");
            OnPXIInitializationFailed();
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            mDisplay.append("Failed" + "\n");
            OnPXIInitializationFailed();
            e.printStackTrace();
        }
        // PopulateAlarmsToDevices(output);
        break;
    }
    }
}

From source file:cm.android.download.providers.downloads.DownloadNotifier.java

public void dumpSpeeds() {
    synchronized (mDownloadSpeed) {
        for (int i = 0; i < mDownloadSpeed.size(); i++) {
            final long id = mDownloadSpeed.keySet().toArray(new Long[0])[i]; // FIXME
            // TransferManager
            // very
            // inefficient
            final long delta = SystemClock.elapsedRealtime() - mDownloadTouch.get(id);
            Log.d(TAG, "Download " + id + " speed " + mDownloadSpeed.get(i) + "bps, " + delta + "ms ago");
        }/*from w ww  .j av a2s . co m*/
    }
}