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.ubergeek42.WeechatAndroid.service.RelayService.java

private void reconnect() {
    // stop if we are already trying to reconnect
    if (reconnector != null && reconnector.isAlive()) {
        return;//from   w  ww  .ja v a  2 s.c  o  m
    }
    reconnector = new Thread(new Runnable() {
        long delays[] = new long[] { 0, 5, 15, 30, 60, 120, 300, 600, 900 };
        int numReconnects = 0;// how many times we've tried this...

        @Override
        public void run() {
            for (;;) {
                long currentDelay = 0;
                if (numReconnects >= delays.length) {
                    currentDelay = delays[delays.length - 1];
                } else {
                    currentDelay = delays[numReconnects];
                }
                if (currentDelay > 0) {
                    showNotification(getString(R.string.notification_reconnecting),
                            String.format(getString(R.string.notification_reconnecting_details), currentDelay));
                }
                // Sleep for a bit
                SystemClock.sleep(currentDelay * 1000);

                // See if we are connected, if so we can stop trying to reconnect
                if (relayConnection != null && relayConnection.isConnected()) {
                    return;
                }

                // Try connecting again
                connect();
                numReconnects++;
            }
        }
    });
    reconnector.start();
}

From source file:com.scvngr.levelup.core.test.TestThreadingUtils.java

/**
 * Helper method to wait for an action to occur.
 *
 * @param instrumentation the test {@link Instrumentation}.
 * @param activity the activity for the test being run.
 * @param latchRunnable the runnable that will check the condition and signal success via its
 * {@link java.util.concurrent.CountDownLatch}.
 * @param timeoutMillis the timeout duration in milliseconds.
 * @param isMainThreadRunnable Determine whether or not the runnable must be invoked on the main
 * thread./*  www  . j a va 2 s.c  o m*/
 * @return true if the action happened before the timeout, false otherwise.
 */
public static boolean waitForAction(@NonNull final Instrumentation instrumentation,
        @NonNull final Activity activity, @NonNull final LatchRunnable latchRunnable, final long timeoutMillis,
        final boolean isMainThreadRunnable) {
    final long endTime = SystemClock.elapsedRealtime() + timeoutMillis;
    boolean result = true;

    while (true) {
        if (isMainThreadRunnable) {
            runOnMainSync(instrumentation, activity, latchRunnable);
        } else {
            latchRunnable.run();
            instrumentation.waitForIdleSync();
        }

        if (latchRunnable.getCount() == 0) {
            break;
        }

        if (SystemClock.elapsedRealtime() >= endTime) {
            result = false;
            break;
        }

        SystemClock.sleep(WAIT_SLEEP_MILLIS);
    }

    return result;
}

From source file:org.zeroxlab.benchmark.Benchmark.java

@SuppressWarnings("unused")
private void initAuto() {
    Intent intent = getIntent();/*from  w w w. j a v  a  2s  .  co m*/
    String TAG = intent.getStringExtra("TAG");
    String CAT = intent.getStringExtra("CAT");

    _checkAllCase(false);
    if (TAG != null)
        _checkTagCase(TAG.split(","));
    if (CAT != null)
        _checkCatCase(CAT.split(","));
    if (TAG == null && CAT == null)
        _checkAllCase(true);
    final Handler h = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 0x1234)
                onClick(mRun);
        }
    };

    final ProgressDialog dialog = ProgressDialog.show(this, "Starting Benchmark", "Please wait...", true,
            false);

    new Thread() {
        public void run() {
            SystemClock.sleep(1000);
            dialog.dismiss();
            Message m = new Message();
            m.what = 0x1234;
            h.sendMessage(m);
        }
    }.start();
    mTouchable = true;
}

From source file:com.carreygroup.JARVIS.Demon.java

public boolean P2PConnect(String UUID, String PWD) {
    int portstatus = 0;
    int intWaitTime = 0;
    // ID//w  ww. j  a  v a  2  s  .  c om
    if (UUID.length() == 0) {
        Log.e("_DEBUG", "ID");
        return false;
    }

    // 
    if (PWD.length() == 0) {
        Log.e("_DEBUG", "");
        return false;
    }

    Log.v("_DEBUG", "UUID:" + UUID + " Password:" + PWD);
    /*
    //SharedPreferences
      SharedPreferences sharedPre=getSharedPreferences("config", Context.MODE_PRIVATE);
      //Editor
      Editor editor=sharedPre.edit();
      //
      editor.putString("username", strUUID);
      editor.putString("password", strPwd);
      //
      editor.commit();
     */
    // -------------SDK------------------------
    try {
        T2u.Init("nat.vveye.net", (char) 8000, "");
    } catch (Exception e) {
        //Toast.makeText(mHomeActivity, "SDK", Toast.LENGTH_SHORT).show();
        Log.e("_DEBUG", "SDK");
        return false;
    }

    // ----------------------------------
    byte[] result = new byte[1500];
    int num = T2u.Search(result);
    String tmp;
    Log.v("_DEBUG", "T2u.Search:" + num);
    if (num > 0) {
        tmp = new String(result);
        Log.v("_DEBUG", "Device:" + tmp);

    } else {
        //Toast.makeText(mHomeActivity, "", Toast.LENGTH_SHORT).show();            
    }
    // -------------------------------------

    while (T2u.Status() == 0) {
        SystemClock.sleep(1000);
        intWaitTime += 1;

        Log.v("_DEBUG", "T2u.Status=" + T2u.Status());
        if (intWaitTime > 10) {
            break;
        }
    }

    Log.v("_DEBUG", "T2u.status -> " + T2u.Status());

    // ------------------- --------------------
    if (T2u.Status() == 1) {
        int ret;
        // --------------------------------
        ret = T2u.Query(UUID);
        Log.v("_DEBUG", "T2u.Query:" + UUID + " -> " + ret);
        if (ret > 0) {
            // ******************IP*********************
            // String strIP = Utils.getIPAddress(true);
            // setTitle("IP:" + strIP);
            // -------------------------------
            p2p_Port = T2u.AddPortV3(UUID, PWD, "127.0.0.1", (char) 8080, (char) 0);
            Log.v("_DEBUG", "T2u.add_port -> port:" + p2p_Port);

            while (portstatus == 0) {
                SystemClock.sleep(1000);

                portstatus = T2u.PortStatus((char) p2p_Port);
                Log.v("_DEBUG", "portstatus=" + portstatus);
                if (portstatus == 1) {
                    Log.v("_DEBUG", "");
                    //return true;
                } else if (portstatus == 0) {
                    Log.v("_DEBUG", "......");
                } else if (portstatus == -1) {
                    //Toast.makeText(mHomeActivity, "", Toast.LENGTH_SHORT).show();
                    Log.e("_DEBUG", "");
                    T2u.Exit();
                    return false;
                } else if (portstatus == -5) {
                    //Toast.makeText(mHomeActivity, "", Toast.LENGTH_SHORT).show();
                    Log.e("_DEBUG", "");
                    T2u.Exit();
                    return false;
                }
            }
        } else {
            //Toast.makeText(mHomeActivity, "", Toast.LENGTH_SHORT).show();
            return false;
        }
    } else {
        //Toast.makeText(mHomeActivity, "", Toast.LENGTH_SHORT).show();
        return false;
    }
    // 
    if (!isNumeric(String.valueOf(p2p_Port))) {
        return false;
    }
    // -------------------,--------------------
    String mHost = getLoaclIPAddress(true);
    Log.i("_DEBUG", "IP:" + mHost + "," + "Port:" + p2p_Port);

    try {
        mSocket = new Socket();
        mAddress = new InetSocketAddress(mHost, p2p_Port);
        mSocket.connect(mAddress, 5000);
        mPrintWriterClient = new PrintWriter(mSocket.getOutputStream(), true);
        if (mSocket.isConnected())
            Log.v("_DEBUG", "Connected!");
        else
            Log.v("_DEBUG", "No Connected!");
        return true;
    } catch (IOException e) {
        // TODO Auto-generated catch block             
        e.printStackTrace();
        return false;
    }
}

From source file:edu.utexas.quietplaces.services.PlacesUpdateService.java

/**
 * Polls the underlying service to return a list of places within the specified
 * radius of the specified Location./* w ww .j  a v a  2s  . co  m*/
 *
 * @param location Location
 * @param radius   Radius
 */
protected void refreshPlaces(Location location, int radius, String page_token) {
    if (location == null) {
        Log.e(TAG, "Null location in refreshPlaces");
        return;
    }
    // Log to see if we'll be prefetching the details page of each new place.
    if (mobileData) {
        Log.d(TAG, "Not prefetching due to being on mobile");
    } else if (lowBattery) {
        Log.d(TAG, "Not prefetching due to low battery");
    }

    long currentTime = System.currentTimeMillis();
    URL url;

    String placeTypes = prefs.getString(PlacesConstants.SP_KEY_API_PLACE_TYPES,
            PlacesConstants.SP_KEY_API_PLACE_TYPES_DEFAULT);
    Log.v(TAG, "Doing places search with types: " + placeTypes);

    try {
        // Should be at most 6 decimal places for max cache usage, but 5 is fine too
        // https://developers.google.com/maps/documentation/business/articles/usage_limits

        String locationStr = String.format("%.5f,%.5f", location.getLatitude(), location.getLongitude());

        String baseURI = PlacesConstants.PLACES_LIST_BASE_URI;

        String placesFeed;
        if (page_token != null && page_token.length() > 0) {
            // Other params are actually ignored here.
            placesFeed = baseURI + PlacesConstants.getPlacesAPIKey(this, true) + "&pagetoken=" + page_token;
        } else {
            placesFeed = baseURI + "&types=" + placeTypes + "&location=" + locationStr + "&radius=" + radius
                    + PlacesConstants.getPlacesAPIKey(this, true);
        }
        url = new URL(placesFeed);

        Log.w(TAG, "HTTP request: " + url);

        // Open the connection
        URLConnection connection = url.openConnection();
        HttpsURLConnection httpConnection = (HttpsURLConnection) connection;
        int responseCode = httpConnection.getResponseCode();

        /*
                    if (connection.getUseCaches()) {
        Log.v(TAG, "Using HTTPS cache");
                    }
                    else {
        Log.v(TAG, "HTTPS cache is disabled");
                    }
        */

        if (responseCode == HttpURLConnection.HTTP_OK) {
            // Use the XML Pull Parser to extract each nearby location.
            // TODO Replace the XML parsing to extract your own place list.
            InputStream in = httpConnection.getInputStream();

            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            factory.setNamespaceAware(true);
            XmlPullParser xpp = factory.newPullParser();

            int placesAddedThisRequest = 0;

            String next_page_token = "";

            xpp.setInput(in, null);
            int eventType = xpp.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                if (eventType == XmlPullParser.START_TAG && xpp.getName().equals("next_page_token")) {
                    next_page_token = xpp.nextText();
                } else if (eventType == XmlPullParser.START_TAG && xpp.getName().equals("result")) {
                    eventType = xpp.next();
                    String id = "";
                    String name = "";
                    String vicinity = "";
                    String types = "";
                    String locationLat = "";
                    String locationLng = "";
                    String viewport = "";
                    String icon = "";
                    String reference = "";
                    while (!(eventType == XmlPullParser.END_TAG && xpp.getName().equals("result"))) {
                        if (eventType == XmlPullParser.START_TAG && xpp.getName().equals("name"))
                            name = xpp.nextText();
                        else if (eventType == XmlPullParser.START_TAG && xpp.getName().equals("vicinity"))
                            vicinity = xpp.nextText();
                        else if (eventType == XmlPullParser.START_TAG && xpp.getName().equals("type"))
                            types = types.equals("") ? xpp.nextText() : types + " " + xpp.nextText();
                        else if (eventType == XmlPullParser.START_TAG && xpp.getName().equals("lat"))
                            locationLat = xpp.nextText();
                        else if (eventType == XmlPullParser.START_TAG && xpp.getName().equals("lng"))
                            locationLng = xpp.nextText();
                        else if (eventType == XmlPullParser.START_TAG && xpp.getName().equals("icon"))
                            icon = xpp.nextText();
                        else if (eventType == XmlPullParser.START_TAG && xpp.getName().equals("reference"))
                            reference = xpp.nextText();
                        else if (eventType == XmlPullParser.START_TAG && xpp.getName().equals("id"))
                            id = xpp.nextText();
                        else if (eventType == XmlPullParser.START_TAG
                                && xpp.getName().equals("next_page_token"))
                            next_page_token = xpp.nextText();
                        eventType = xpp.next();
                    }

                    Location placeLocation = new Location(PlacesConstants.CONSTRUCTED_LOCATION_PROVIDER);
                    placeLocation.setLatitude(Double.valueOf(locationLat));
                    placeLocation.setLongitude(Double.valueOf(locationLng));

                    Log.v(TAG, "Found place: " + " location: " + location + " id: " + id + " name: " + name
                            + " vicinity: " + vicinity + " types: " + types + " ref: " + reference);

                    if (!next_page_token.equals("")) {
                        Log.e(TAG, "WARNING: unhandled next_page_token from Places search " + next_page_token);
                    }

                    // Add each new place to the Places Content Provider
                    addPlace(location, id, name, vicinity, types, placeLocation, viewport, icon, reference,
                            currentTime);
                    placesAddedThisRequest++;
                }
                eventType = xpp.next();
            }

            if (placesAddedThisRequest > 0) {
                Log.i(TAG, "Found " + placesAddedThisRequest + " places this request.");

                if (!next_page_token.equals("")) {
                    // TODO: we should check for INVALID_RESULT and retry after a shorter wait
                    // Currently, if this wait is too long, we waste time, but if it's too short, we don't get the next page.
                    Log.d(TAG, "Sleeping before fetching next page. Sleep interval (ms): "
                            + PlacesConstants.PLACES_NEXT_PAGE_INTERVAL_MS);
                    SystemClock.sleep(PlacesConstants.PLACES_NEXT_PAGE_INTERVAL_MS);
                    Log.i(TAG, "Fetching next page of places results.");
                    refreshPlaces(location, radius, next_page_token);
                }
            } else {
                Log.w(TAG, "Found 0 places this request.");
            }

            // Remove places from the PlacesDetailsContentProvider that aren't from this update.
            String where = PlaceDetailsContentProvider.KEY_LAST_UPDATE_TIME + " < " + currentTime;
            contentResolver.delete(PlacesContentProvider.CONTENT_URI, where, null);

            // Save the last update time and place to the Shared Preferences.
            prefsEditor.putFloat(PlacesConstants.SP_KEY_LAST_LIST_UPDATE_LAT, (float) location.getLatitude());
            prefsEditor.putFloat(PlacesConstants.SP_KEY_LAST_LIST_UPDATE_LNG, (float) location.getLongitude());
            prefsEditor.putLong(PlacesConstants.SP_KEY_LAST_LIST_UPDATE_TIME, System.currentTimeMillis());
            sharedPreferenceSaver.savePreferences(prefsEditor, false);
            //prefsEditor.apply();
            //prefsEditor.commit();
        } else
            Log.e(TAG, responseCode + ": " + httpConnection.getResponseMessage());

    } catch (MalformedURLException e) {
        Log.e(TAG, e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, e.getMessage());
    } catch (XmlPullParserException e) {
        Log.e(TAG, e.getMessage());
    } finally {
    }
}

From source file:eu.nubomedia.nubomedia_kurento_health_communicator_android.kc_and_client.ui.activity.ItemListActivity.java

private void showPopup() {
    dialog.setVisibility(View.VISIBLE);
    dialogBackground.setVisibility(View.VISIBLE);

    dialog.startAnimation(myAnimationShowPopup);

    Button create_group = (Button) dialog.findViewById(R.id.create_button);
    create_group.setOnClickListener(new OnClickListener() {

        @Override//  w w w  .ja  v  a  2 s .  c  om
        public void onClick(View v) {
            if (((EditText) ItemListActivity.this.findViewById(R.id.group_name_text)).getText().toString()
                    .length() == 0) {
                Toast.makeText(ItemListActivity.this, getString(R.string.creating_group_mandatory_name),
                        Toast.LENGTH_SHORT).show();
                return;
            }
            dialog.setVisibility(View.GONE);
            dialogBackground.setVisibility(View.GONE);

            imm.hideSoftInputFromWindow(
                    ((EditText) ItemListActivity.this.findViewById(R.id.group_name_text)).getWindowToken(), 0);
            imm.hideSoftInputFromWindow(
                    ((EditText) ItemListActivity.this.findViewById(R.id.group_phone_text)).getWindowToken(), 0);

            createGroup();
        }
    });

    Button cancel_group = (Button) dialog.findViewById(R.id.cancel_button);
    cancel_group.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            imm.hideSoftInputFromWindow(
                    ((EditText) ItemListActivity.this.findViewById(R.id.group_name_text)).getWindowToken(), 0);
            imm.hideSoftInputFromWindow(
                    ((EditText) ItemListActivity.this.findViewById(R.id.group_phone_text)).getWindowToken(), 0);

            dialog.setVisibility(View.GONE);
            dialogBackground.setVisibility(View.GONE);
            clearPopup();
        }
    });

    ImageView image = (ImageView) dialog.findViewById(R.id.group_image);
    image.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            imm.hideSoftInputFromWindow(((EditText) dialog.findViewById(R.id.group_name_text)).getWindowToken(),
                    0);
            new AsyncTask<Void, Void, Void>() {
                @Override
                protected Void doInBackground(Void... params) {
                    SystemClock.sleep(200);
                    return null;
                }

                @Override
                protected void onPostExecute(Void result) {
                    mQuickAction.show(((ImageView) dialog.findViewById(R.id.group_image)));
                }
            }.execute();
        }
    });

    dialogBackground.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.setVisibility(View.GONE);
            dialogBackground.setVisibility(View.GONE);
        }
    });
}

From source file:com.bangz.shotrecorder.RecordActivity.java

private void doStartRecord() {

    doDelayStart();/*from w w  w.j a va2s.c  o m*/

    ToneGenerator tg = new ToneGenerator(AudioManager.STREAM_MUSIC, 100);
    tg.startTone(ToneGenerator.TONE_CDMA_ABBR_ALERT, BEEP_DURATIONMS);
    SystemClock.sleep(BEEP_DURATIONMS - 20);
    tg.stopTone();
    tg.release();

    mState = STATE_RECORDING;
    Intent intent = new Intent(this, RecordService.class);

    intent.putExtra(RecordService.EXTRA_SAMPLERATE, mSampleRate);
    intent.putExtra(RecordService.EXTRA_CHANNLES, mChannels);
    intent.putExtra(RecordService.EXTRA_ENCODDING, mEncoding);

    intent.putExtra(RecordService.EXTRA_MODE, mMode.ordinal());
    intent.putExtra(RecordService.EXTRA_MAXSHOT, this.mMaxShots);
    intent.putExtra(RecordService.EXTRA_MAXPARTIME, (int) (mMaxParTime * 1000));
    intent.putExtra(RecordService.EXTRA_CAPTURESIZE, 128);
    intent.putExtra(RecordService.EXTRA_MAXRECORDTIME, 5 * 60);
    startService(intent);

    doBindService();

    textTIME.setText(R.string.READY);
}

From source file:com.bangz.shotrecorder.RecordActivity.java

private void doDelayStart() {
    int maxDelay = Prefs.getDelayStart(this) * 1000;
    int minDelay = maxDelay * Prefs.getMinDelayStart(this) / 100;

    Random rand = new Random();
    int delay = minDelay + ((maxDelay == minDelay) ? 0 : rand.nextInt(maxDelay - minDelay)) - BEEP_DURATIONMS;
    delay = delay - delay % 1000;//from w  w  w .  j a  va2s  .  co  m

    if (delay > 0) {
        SystemClock.sleep(delay);
    }
}

From source file:eu.nubomedia.nubomedia_kurento_health_communicator_android.kc_and_client.ui.activity.MessagesActivity.java

private void configurePopup() {
    ActionItem addItem = new ActionItem(ID_CAMERA, getString(R.string.popup_camera),
            getResources().getDrawable(android.R.drawable.ic_menu_camera));
    ActionItem acceptItem = new ActionItem(ID_VIDIO, getString(R.string.popup_vidio),
            getResources().getDrawable(android.R.drawable.ic_menu_slideshow));
    ActionItem uploadItem = new ActionItem(ID_GALLERY, getString(R.string.popup_gallery),
            getResources().getDrawable(android.R.drawable.ic_menu_gallery));

    mQuickAction = new QuickAction(messagesActivity);

    mQuickAction.addActionItem(addItem);
    mQuickAction.addActionItem(acceptItem);
    mQuickAction.addActionItem(uploadItem);

    // setup the action item click listener
    mQuickAction.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
        @Override/*from   w  ww  . j  a  v a2s  .co  m*/
        public void onItemClick(QuickAction quickAction, int pos, int actionId) {
            AppUtils.setDefaults(ConstantKeys.FROMLOGIN, ConstantKeys.FALSE, messagesActivity);

            if (actionId == ID_CAMERA) {
                takePicture();
            } else if (actionId == ID_VIDIO) {
                recordVideo();
            } else if (actionId == ID_GALLERY) {
                takeGallery();
            }
        }
    });

    ImageButton mediaButton = ((ImageButton) messagesActivity.findViewById(R.id.media_button));

    mediaButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(
                    ((EditText) messagesActivity.messagesActivity.findViewById(R.id.upload_description_content))
                            .getWindowToken(),
                    0);

            new AsyncTask<Void, Void, Void>() {
                @Override
                protected Void doInBackground(Void... params) {
                    SystemClock.sleep(200);
                    return null;
                }

                @Override
                protected void onPostExecute(Void result) {
                    mQuickAction.show(
                            ((ImageButton) messagesActivity.messagesActivity.findViewById(R.id.media_button)));
                }
            }.execute();
        }
    });
}

From source file:com.ubergeek42.WeechatAndroid.service.RelayService.java

@Override
public void onUpgrade() {
    // Don't do this twice
    if (upgrading != null && upgrading.isAlive()) {
        return;/*from  w ww.  j  av  a2  s . c o m*/
    }

    // Basically just reconnect on upgrade
    upgrading = new Thread(new Runnable() {
        @Override
        public void run() {
            showNotification(getString(R.string.notification_upgrading),
                    getString(R.string.notification_upgrading_details));
            shutdown();
            SystemClock.sleep(5000);
            connect();
        }
    });
    upgrading.start();
}