Example usage for android.os SystemClock sleep

List of usage examples for android.os SystemClock sleep

Introduction

In this page you can find the example usage for android.os SystemClock sleep.

Prototype

public static void sleep(long ms) 

Source Link

Document

Waits a given number of milliseconds (of uptimeMillis) before returning.

Usage

From source file:com.andrew.apollo.MusicPlaybackService.java

/**
 * Reloads the queue as the user left it the last time they stopped using
 * Apollo//from  w ww  .ja va 2  s  . c o m
 */
private void reloadQueue() {
    String q = null;
    int id = mCardId;
    if (mPreferences.contains("cardid")) {
        id = mPreferences.getInt("cardid", ~mCardId);
    }
    if (id == mCardId) {
        q = mPreferences.getString("queue", "");
    }
    int qlen = q != null ? q.length() : 0;
    if (qlen > 1) {
        int plen = 0;
        int n = 0;
        int shift = 0;
        for (int i = 0; i < qlen; i++) {
            final char c = q.charAt(i);
            if (c == ';') {
                ensurePlayListCapacity(plen + 1);
                mPlayList[plen] = n;
                plen++;
                n = 0;
                shift = 0;
            } else {
                if (c >= '0' && c <= '9') {
                    n += c - '0' << shift;
                } else if (c >= 'a' && c <= 'f') {
                    n += 10 + c - 'a' << shift;
                } else {
                    plen = 0;
                    break;
                }
                shift += 4;
            }
        }
        mPlayListLen = plen;
        final int pos = mPreferences.getInt("curpos", 0);
        if (pos < 0 || pos >= mPlayListLen) {
            mPlayListLen = 0;
            return;
        }
        mPlayPos = pos;
        updateCursor(mPlayList[mPlayPos]);
        if (mCursor == null) {
            SystemClock.sleep(3000);
            try {
                // TODO: well, this is garbage, since
                // there is a 3 seconds sleep, all sort
                // of things could happen to the mutable
                // variable mPlayPos, including set it to -1
                // this need to be recoded
                updateCursor(mPlayList[mPlayPos]);
            } catch (ArrayIndexOutOfBoundsException e) {
                // ignore and return
                return;
            }
        }
        synchronized (this) {
            closeCursor();
            mOpenFailedCounter = 20;
            openCurrentAndNext();
        }
        if (mPlayer == null || !mPlayer.isInitialized()) {
            mPlayListLen = 0;
            return;
        }

        final long seekpos = mPreferences.getLong("seekpos", 0);
        seek(seekpos >= 0 && seekpos < duration() ? seekpos : 0);

        if (D) {
            LOG.info("restored queue, currently at position " + position() + "/" + duration() + " (requested "
                    + seekpos + ")");
        }

        int repmode = mPreferences.getInt("repeatmode", REPEAT_NONE);
        if (repmode != REPEAT_ALL && repmode != REPEAT_CURRENT) {
            repmode = REPEAT_NONE;
        }
        mRepeatMode = repmode;
    }
}

From source file:com.av.remusic.service.MediaService.java

private void reloadQueue() {
    int id = mCardId;
    if (mPreferences.contains("cardid")) {
        id = mPreferences.getInt("cardid", ~mCardId);
    }//from   www  .  j  a  v  a2  s. com
    if (id == mCardId) {
        mPlaylist = mPlaybackStateStore.getQueue();
        try {
            FileInputStream in = new FileInputStream(new File(getCacheDir().getAbsolutePath() + "playlist"));
            String c = readTextFromSDcard(in);
            HashMap<Long, MusicInfo> play = MainApplication.gsonInstance().fromJson(c,
                    new TypeToken<HashMap<Long, MusicInfo>>() {
                    }.getType());
            if (play != null && play.size() > 0) {
                mPlaylistInfo = play;
                L.D(D, TAG, mPlaylistInfo.keySet().toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    if ((mPlaylist.size() == mPlaylistInfo.size()) && mPlaylist.size() > 0) {
        final int pos = mPreferences.getInt("curpos", 0);
        if (pos < 0 || pos >= mPlaylist.size()) {
            mPlaylist.clear();
            return;
        }
        mPlayPos = pos;
        updateCursor(mPlaylist.get(mPlayPos).mId);
        if (mCursor == null) {
            SystemClock.sleep(3000);
            updateCursor(mPlaylist.get(mPlayPos).mId);
        }
        synchronized (this) {
            closeCursor();
            mOpenFailedCounter = 20;
            openCurrentAndNext();
        }

        //            if (!mPlayer.isInitialized() && isTrackLocal()) {
        //                mPlaylist.clear();
        //                return;
        //            }
        final long seekpos = mPreferences.getLong("seekpos", 0);
        mLastSeekPos = seekpos;
        seek(seekpos >= 0 && seekpos < duration() ? seekpos : 0);

        if (D) {
            Log.d(TAG, "restored queue, currently at position " + position() + "/" + duration() + " (requested "
                    + seekpos + ")");
        }

        int repmode = mPreferences.getInt("repeatmode", REPEAT_ALL);
        if (repmode != REPEAT_ALL && repmode != REPEAT_CURRENT) {
            repmode = REPEAT_NONE;
        }
        mRepeatMode = repmode;

        int shufmode = mPreferences.getInt("shufflemode", SHUFFLE_NONE);
        if (shufmode != SHUFFLE_AUTO && shufmode != SHUFFLE_NORMAL) {
            shufmode = SHUFFLE_NONE;
        }
        if (shufmode != SHUFFLE_NONE) {
            mHistory = mPlaybackStateStore.getHistory(mPlaylist.size());
        }
        if (shufmode == SHUFFLE_AUTO) {
            if (!makeAutoShuffleList()) {
                shufmode = SHUFFLE_NONE;
            }
        }
        mShuffleMode = shufmode;
    } else {
        clearPlayInfos();
    }
    notifyChange(MUSIC_CHANGED);
}

From source file:org.broeuschmeul.android.gps.usb.provider.driver.USBGpsManager.java

private void enableNMEA(boolean enable) {
    //            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(callingService);
    //            String deviceSpeed = sharedPreferences.getString(USBGpsProviderService.PREF_GPS_DEVICE_SPEED, callingService.getString(R.string.defaultGpsDeviceSpeed));
    if (deviceSpeed.equals(callingService.getString(R.string.autoGpsDeviceSpeed))) {
        deviceSpeed = callingService.getString(R.string.defaultGpsDeviceSpeed);
    }/*  w  w  w .j a v  a 2s . c  o m*/
    SystemClock.sleep(400);
    if (enable) {
        //                int gll = (sharedPreferences.getBoolean(USBGpsProviderService.PREF_SIRF_ENABLE_GLL, false)) ? 1 : 0 ;
        //                int vtg = (sharedPreferences.getBoolean(USBGpsProviderService.PREF_SIRF_ENABLE_VTG, false)) ? 1 : 0 ;
        //                int gsa = (sharedPreferences.getBoolean(USBGpsProviderService.PREF_SIRF_ENABLE_GSA, false)) ? 5 : 0 ;
        //                int gsv = (sharedPreferences.getBoolean(USBGpsProviderService.PREF_SIRF_ENABLE_GSV, false)) ? 5 : 0 ;
        //                int zda = (sharedPreferences.getBoolean(USBGpsProviderService.PREF_SIRF_ENABLE_ZDA, false)) ? 1 : 0 ;
        //                int mss = 0;
        //                int epe = 0;
        //                int gga = 1;
        //                int rmc = 1;
        //                String command = getString(R.string.sirf_bin_to_nmea_38400_alt, gga, gll, gsa, gsv, rmc, vtg, mss, epe, zda);
        //                String command = getString(R.string.sirf_bin_to_nmea_alt, gga, gll, gsa, gsv, rmc, vtg, mss, epe, zda, Integer.parseInt(deviceSpeed));
        String command = callingService.getString(R.string.sirf_bin_to_nmea);
        this.sendSirfCommand(command);
    } else {
        //                this.sendNmeaCommand(callingService.getString(R.string.sirf_nmea_to_binary));
        this.sendNmeaCommand(
                callingService.getString(R.string.sirf_nmea_to_binary_alt, Integer.parseInt(deviceSpeed)));
    }
    SystemClock.sleep(400);
}

From source file:org.broeuschmeul.android.gps.usb.provider.driver.USBGpsManager.java

public void enableSirfConfig(final Bundle extra) {
    debugLog("spooling SiRF config: " + extra);
    if (isEnabled()) {
        notificationPool.execute(new Runnable() {
            @Override// w  w  w  .j a v a2s  .  c  om
            public void run() {
                while ((enabled) && ((!connected) || (connectedGps == null) || (!connectedGps.isReady()))) {
                    debugLog("writing thread is not ready");
                    SystemClock.sleep(500);
                }
                if (isEnabled() && (connected) && (connectedGps != null) && (connectedGps.isReady())) {
                    debugLog("init SiRF config: " + extra);
                    if (extra.containsKey(USBGpsProviderService.PREF_SIRF_ENABLE_GGA)) {
                        enableNmeaGGA(extra.getBoolean(USBGpsProviderService.PREF_SIRF_ENABLE_GGA, true));
                    }
                    if (extra.containsKey(USBGpsProviderService.PREF_SIRF_ENABLE_RMC)) {
                        enableNmeaRMC(extra.getBoolean(USBGpsProviderService.PREF_SIRF_ENABLE_RMC, true));
                    }
                    if (extra.containsKey(USBGpsProviderService.PREF_SIRF_ENABLE_GLL)) {
                        enableNmeaGLL(extra.getBoolean(USBGpsProviderService.PREF_SIRF_ENABLE_GLL, false));
                    }
                    if (extra.containsKey(USBGpsProviderService.PREF_SIRF_ENABLE_VTG)) {
                        enableNmeaVTG(extra.getBoolean(USBGpsProviderService.PREF_SIRF_ENABLE_VTG, false));
                    }
                    if (extra.containsKey(USBGpsProviderService.PREF_SIRF_ENABLE_GSA)) {
                        enableNmeaGSA(extra.getBoolean(USBGpsProviderService.PREF_SIRF_ENABLE_GSA, false));
                    }
                    if (extra.containsKey(USBGpsProviderService.PREF_SIRF_ENABLE_GSV)) {
                        enableNmeaGSV(extra.getBoolean(USBGpsProviderService.PREF_SIRF_ENABLE_GSV, false));
                    }
                    if (extra.containsKey(USBGpsProviderService.PREF_SIRF_ENABLE_ZDA)) {
                        enableNmeaZDA(extra.getBoolean(USBGpsProviderService.PREF_SIRF_ENABLE_ZDA, false));
                    }
                    if (extra.containsKey(USBGpsProviderService.PREF_SIRF_ENABLE_STATIC_NAVIGATION)) {
                        enableStaticNavigation(extra
                                .getBoolean(USBGpsProviderService.PREF_SIRF_ENABLE_STATIC_NAVIGATION, false));
                    } else if (extra.containsKey(USBGpsProviderService.PREF_SIRF_ENABLE_NMEA)) {
                        enableNMEA(extra.getBoolean(USBGpsProviderService.PREF_SIRF_ENABLE_NMEA, true));
                    }
                    if (extra.containsKey(USBGpsProviderService.PREF_SIRF_ENABLE_SBAS)) {
                        enableSBAS(extra.getBoolean(USBGpsProviderService.PREF_SIRF_ENABLE_SBAS, true));
                    }
                    debugLog("initialized SiRF config: " + extra);
                }
            }
        });
    }
}

From source file:io.realm.RealmTest.java

public void testFinalizerThread() throws NoSuchFieldException, IllegalAccessException {
    Field fieldReferences = FinalizerRunnable.class.getDeclaredField("references");
    fieldReferences.setAccessible(true);
    Map<Reference<?>, Boolean> references = (Map<Reference<?>, Boolean>) fieldReferences.get(null);
    assertNotNull(references);//from ww w.j  a  va  2 s  . c  o m

    Field fieldIsFinalizerStarted = Realm.class.getDeclaredField("isFinalizerStarted");
    fieldIsFinalizerStarted.setAccessible(true);
    boolean isFinalizerStarted = fieldIsFinalizerStarted.getBoolean(null);
    assertTrue(isFinalizerStarted);

    //insert some rows, then give the FinalizerRunnable some time to cleanup
    // we have 8 reference so far let's add more
    final int numberOfPopulateTest = 10000;
    final int totalNumberOfReferences = 8 + 20 * 2 * numberOfPopulateTest;

    for (int i = 0; i < numberOfPopulateTest; i++) {
        populateTestRealm(testRealm, 20);
    }

    final int MAX_GC_RETRIES = 5;
    int numberOfRetries = 0;
    while (references.size() > 0 && numberOfRetries < MAX_GC_RETRIES) {
        SystemClock.sleep(TimeUnit.SECONDS.toMillis(1)); //1s
        numberOfRetries++;
        System.gc();
    }

    // we can't guarantee that all references have been GC'd but we should detect a decrease
    boolean isDecreasing = references.size() < totalNumberOfReferences;
    if (!isDecreasing) {
        fail("FinalizerRunnable is not closing all native resources");

    } else {
        android.util.Log.d(RealmTest.class.getName(), "FinalizerRunnable freed : "
                + (totalNumberOfReferences - references.size()) + " out of " + totalNumberOfReferences);
    }
}

From source file:org.yammp.MusicPlaybackService.java

private void reloadQueue() {

    String q = null;/*from   w  ww.ja  v a2 s  .c om*/

    int id = mCardId;
    if (getSharedPreferences(SHAREDPREFS_STATES, Context.MODE_PRIVATE).contains(STATE_KEY_CARDID)) {
        id = mPrefs.getIntState(STATE_KEY_CARDID, mCardId);
    }
    if (id == mCardId) {
        // Only restore the saved playlist if the card is still
        // the same one as when the playlist was saved
        q = mPrefs.getStringState(STATE_KEY_QUEUE, "");
    }
    int qlen = q != null ? q.length() : 0;
    if (qlen > 1) {
        // Log.i("@@@@ service", "loaded queue: " + q);
        int plen = 0;
        int n = 0;
        int shift = 0;
        for (int i = 0; i < qlen; i++) {
            char c = q.charAt(i);
            if (c == ';') {
                ensurePlayListCapacity(plen + 1);
                mPlayList[plen] = n;
                plen++;
                n = 0;
                shift = 0;
            } else {
                if (c >= '0' && c <= '9') {
                    n += c - '0' << shift;
                } else if (c >= 'a' && c <= 'f') {
                    n += 10 + c - 'a' << shift;
                } else {
                    // bogus playlist data
                    plen = 0;
                    break;
                }
                shift += 4;
            }
        }
        //TODO shuffler.
        mShuffler = new Shuffler(mPlayList);
        mPlayListLen = plen;

        int pos = mPrefs.getIntState(STATE_KEY_CURRPOS, 0);
        if (pos < 0 || pos >= mPlayListLen) {
            // The saved playlist is bogus, discard it
            mPlayListLen = 0;
            return;
        }
        mPlayPos = pos;

        // When reloadQueue is called in response to a card-insertion,
        // we might not be able to query the media provider right away.
        // To deal with this, try querying for the current file, and if
        // that fails, wait a while and try again. If that too fails,
        // assume there is a problem and don't restore the state.
        Cursor cur = mUtils.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, new String[] { "_id" },
                "_id=" + mPlayList[mPlayPos], null, null);
        if (cur == null || cur.getCount() == 0) {
            // wait a bit and try again
            SystemClock.sleep(3000);
            cur = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, mCursorCols,
                    "_id=" + mPlayList[mPlayPos], null, null);
        }
        if (cur != null) {
            cur.close();
        }

        mOpenFailedCounter = 20;
        mQuietMode = true;
        openCurrent();
        mQuietMode = false;
        if (!mPlayer.isInitialized()) {
            // couldn't restore the saved state
            mPlayListLen = 0;
            return;
        }

        mLyricsHandler.sendEmptyMessage(NEW_LYRICS_LOADED);

        long seekpos = mPrefs.getLongState(STATE_KEY_SEEKPOS, 0);
        seek(seekpos >= 0 && seekpos < duration() ? seekpos : 0);
        Log.d(LOGTAG_SERVICE, "restored queue, currently at position " + position() + "/" + duration()
                + " (requested " + seekpos + ")");

        int repmode = mPrefs.getIntState(STATE_KEY_REPEATMODE, REPEAT_NONE);
        if (repmode != REPEAT_ALL && repmode != REPEAT_CURRENT) {
            repmode = REPEAT_NONE;
        }
        mRepeatMode = repmode;

        int shufmode = mPrefs.getIntState(STATE_KEY_SHUFFLEMODE, SHUFFLE_NONE);
        if (shufmode != SHUFFLE_NORMAL) {
            shufmode = SHUFFLE_NONE;
        }
        if (shufmode != SHUFFLE_NONE) {
            // in shuffle mode we need to restore the history too
            q = mPrefs.getStringState(STATE_KEY_HISTORY, "");
            qlen = q != null ? q.length() : 0;
            if (qlen > 1) {
                plen = 0;
                n = 0;
                shift = 0;
                mHistory.clear();
                for (int i = 0; i < qlen; i++) {
                    char c = q.charAt(i);
                    if (c == ';') {
                        if (n >= mPlayListLen) {
                            // bogus history data
                            mHistory.clear();
                            break;
                        }
                        if (!mHistory.contains(mPlayPos)) {
                            mHistory.add(mPlayPos);
                        }
                        n = 0;
                        shift = 0;
                    } else {
                        if (c >= '0' && c <= '9') {
                            n += c - '0' << shift;
                        } else if (c >= 'a' && c <= 'f') {
                            n += 10 + c - 'a' << shift;
                        } else {
                            // bogus history data
                            mHistory.clear();
                            break;
                        }
                        shift += 4;
                    }
                }
            }
        }
        mShuffleMode = shufmode;
    }
}

From source file:org.broeuschmeul.android.gps.usb.provider.driver.USBGpsManager.java

public void enableSirfConfig(final SharedPreferences extra) {
    debugLog("spooling SiRF config: " + extra);
    if (isEnabled()) {
        notificationPool.execute(new Runnable() {
            @Override// www. j  av  a  2 s .  c  o m
            public void run() {
                while ((enabled) && ((!connected) || (connectedGps == null) || (!connectedGps.isReady()))) {
                    debugLog("writing thread is not ready");
                    SystemClock.sleep(500);
                }
                if (isEnabled() && (connected) && (connectedGps != null) && (connectedGps.isReady())) {
                    debugLog("init SiRF config: " + extra);
                    if (extra.contains(USBGpsProviderService.PREF_SIRF_ENABLE_GLL)) {
                        enableNmeaGLL(extra.getBoolean(USBGpsProviderService.PREF_SIRF_ENABLE_GLL, false));
                    }
                    if (extra.contains(USBGpsProviderService.PREF_SIRF_ENABLE_VTG)) {
                        enableNmeaVTG(extra.getBoolean(USBGpsProviderService.PREF_SIRF_ENABLE_VTG, false));
                    }
                    if (extra.contains(USBGpsProviderService.PREF_SIRF_ENABLE_GSA)) {
                        enableNmeaGSA(extra.getBoolean(USBGpsProviderService.PREF_SIRF_ENABLE_GSA, false));
                    }
                    if (extra.contains(USBGpsProviderService.PREF_SIRF_ENABLE_GSV)) {
                        enableNmeaGSV(extra.getBoolean(USBGpsProviderService.PREF_SIRF_ENABLE_GSV, false));
                    }
                    if (extra.contains(USBGpsProviderService.PREF_SIRF_ENABLE_ZDA)) {
                        enableNmeaZDA(extra.getBoolean(USBGpsProviderService.PREF_SIRF_ENABLE_ZDA, false));
                    }
                    if (extra.contains(USBGpsProviderService.PREF_SIRF_ENABLE_STATIC_NAVIGATION)) {
                        enableStaticNavigation(extra
                                .getBoolean(USBGpsProviderService.PREF_SIRF_ENABLE_STATIC_NAVIGATION, false));
                    } else if (extra.contains(USBGpsProviderService.PREF_SIRF_ENABLE_NMEA)) {
                        enableNMEA(extra.getBoolean(USBGpsProviderService.PREF_SIRF_ENABLE_NMEA, true));
                    }
                    if (extra.contains(USBGpsProviderService.PREF_SIRF_ENABLE_SBAS)) {
                        enableSBAS(extra.getBoolean(USBGpsProviderService.PREF_SIRF_ENABLE_SBAS, true));
                    }
                    sendNmeaCommand(callingService.getString(R.string.sirf_nmea_gga_on));
                    sendNmeaCommand(callingService.getString(R.string.sirf_nmea_rmc_on));
                    if (extra.contains(USBGpsProviderService.PREF_SIRF_ENABLE_GGA)) {
                        enableNmeaGGA(extra.getBoolean(USBGpsProviderService.PREF_SIRF_ENABLE_GGA, true));
                    }
                    if (extra.contains(USBGpsProviderService.PREF_SIRF_ENABLE_RMC)) {
                        enableNmeaRMC(extra.getBoolean(USBGpsProviderService.PREF_SIRF_ENABLE_RMC, true));
                    }
                }
            }
        });
    }
}

From source file:nl.dobots.bluenet.ble.extended.BleExt.java

/**
 * Function to start a scan for devices, stop it again after scanDuration expired, then
 * return the list of devices/*  ww  w.  j a v  a  2 s.c o m*/
 *
 * Note: needs to be already connected or an error is created! Use overloaded function
 * with address otherwise
 * @param scanDuration the duration (in ms) for which the device should scan for other BLE
 *                     devices
 * @param callback the callback which will return the list of scanned devices
 */
public void scanForDevices(final int scanDuration, final IByteArrayCallback callback) {
    writeScanDevices(true, new IStatusCallback() {
        @Override
        public void onSuccess() {
            _handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    writeScanDevices(false, new IStatusCallback() {
                        @Override
                        public void onSuccess() {
                            // delay 500 ms, just wait, don't postdelay, since we are already
                            // inside the handler, and hopefully 500ms delay won't cause havoc
                            SystemClock.sleep(500);
                            listScannedDevices(callback);
                        }

                        @Override
                        public void onError(int error) {
                            callback.onError(error);
                        }
                    });
                }
            }, scanDuration);
        }

        @Override
        public void onError(int error) {
            callback.onError(error);
        }
    });
}

From source file:io.realm.RealmTests.java

@Test
public void closingRealmWhileOtherThreadIsOpeningRealm() throws Exception {
    final CountDownLatch startLatch = new CountDownLatch(1);
    final CountDownLatch endLatch = new CountDownLatch(1);

    final List<Exception> exception = new ArrayList<Exception>();

    new Thread() {
        @Override//w  w w  .  ja  va  2  s  .  c  om
        public void run() {
            try {
                startLatch.await();
            } catch (InterruptedException e) {
                exception.add(e);
                return;
            }

            final Realm realm = Realm.getInstance(realmConfig);
            try {
                realm.where(AllTypes.class).equalTo("columnLong", 0L).findFirst();
            } catch (Exception e) {
                exception.add(e);
            } finally {
                endLatch.countDown();
                realm.close();
            }
        }
    }.start();

    // prevent for another thread to enter Realm.createAndValidate().
    synchronized (BaseRealm.class) {
        startLatch.countDown();

        // wait for another thread's entering Realm.createAndValidate().
        SystemClock.sleep(100L);

        realm.close();
        realm = null;
    }

    endLatch.await();

    if (!exception.isEmpty()) {
        throw exception.get(0);
    }
}

From source file:nl.dobots.bluenet.ble.extended.BleExt.java

/**
 * Function to start a scan for devices, stop it again after scanDuration expired, then
 * return the list of devices/*  w w  w.  j ava2s . co  m*/
 *
 * Connects to the device if not already connected, and/or delays the disconnect if necessary.
 * @param scanDuration the duration (in ms) for which the device should scan for other BLE
 *                     devices
 * @param callback the callback which will return the list of scanned devices
 */
public void scanForDevices(final String address, final int scanDuration, final IByteArrayCallback callback) {
    BleLog.LOGd(TAG, "Scan for devices ...");
    if (checkConnection(address)) {
        scanForDevices(scanDuration, callback);
    } else {
        // connect and execute ...
        connectAndExecute(address, new IExecuteCallback() {
            @Override
            public void execute(final IStatusCallback startExecCallback) {
                // ... start scanning for devices
                writeScanDevices(true, new IStatusCallback() {
                    @Override
                    public void onSuccess() {
                        // if successfully started, post the stop scan with scanDuration delay
                        _handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                // once scanDuration delay expired, connect and execute ...
                                connectAndExecute(address, new IExecuteCallback() {
                                    @Override
                                    public void execute(final IStatusCallback stopExecCallback) {
                                        // ... stop scanning for devices
                                        writeScanDevices(false, new IStatusCallback() {
                                            @Override
                                            public void onSuccess() {
                                                // if successfully stopped, get the list of scanned devices ...

                                                // delay 500 ms to give time for list to be written to characteristic
                                                // just wait, don't postdelay, since we are already
                                                // inside the handler, and hopefully 500ms delay won't cause havoc
                                                SystemClock.sleep(500);
                                                // get the list ...
                                                listScannedDevices(new IByteArrayCallback() {
                                                    @Override
                                                    public void onSuccess(byte[] result) {
                                                        callback.onSuccess(result);
                                                        // ... and disconnect again once we have it
                                                        stopExecCallback.onSuccess();
                                                    }

                                                    @Override
                                                    public void onError(int error) {
                                                        //                                                   callback.onError(error);
                                                        // also disconnect if an error occurs
                                                        stopExecCallback.onError(error);
                                                    }
                                                });
                                            }

                                            @Override
                                            public void onError(int error) {
                                                //                                             callback.onError(error);
                                                // disconnect if an error occurs
                                                stopExecCallback.onError(error);
                                            }
                                        });
                                    }
                                }, new IStatusCallback() {
                                    @Override
                                    public void onSuccess() {
                                        /* don't care */ }

                                    @Override
                                    public void onError(int error) {
                                        callback.onError(error);
                                    }
                                });

                            }
                        }, scanDuration);
                        // after posting, disconnect again
                        startExecCallback.onSuccess();
                    }

                    @Override
                    public void onError(int error) {
                        //                        callback.onError(error);
                        // disconnect if an error occurs
                        startExecCallback.onError(error);
                    }
                });
            }
        }, new IStatusCallback() {
            @Override
            public void onSuccess() {
                /* don't care */ }

            @Override
            public void onError(int error) {
                callback.onError(error);
            }
        });
    }
}