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.tonikorin.cordova.plugin.LocationProvider.LocationService.java

private void handleLocationQuery(JSONObject messageIn, String time) throws JSONException, IOException {
    Log.d(TAG, "Handle location query...");
    String ownName = config.optString("member", "");
    JSONObject teams = config.optJSONObject("teams");
    String teamName;//from w w w . ja  v  a  2 s .c o  m
    String teamPassword;
    String teamHost;
    JSONObject team = null;
    if (teams != null)
        team = teams.optJSONObject(messageIn.optString("teamId"));
    if (team != null) {
        teamName = team.optString("name", "");
        teamPassword = team.optString("password", "");
        ownName = team.optString("member", ownName);
        teamHost = team.optString("host", "");
    } else
        return; // => URI hanging in PostServer
    String msgType = messageIn.optString("messageType", LOCATE);
    // Create Messaging Server interface
    String messageUrl = config.optString("messageUrl", "").replace("{host}", teamHost);
    MessageServer msgServer = new MessageServer(ownName, teamName, teamPassword, messageUrl);
    if (messageIn.optString("memberName").equals(ownName)) {
        updateLocateHistory(messageIn, true, msgType, time);
        msgServer.post(RESERVED);
        SystemClock.sleep(5000);// 5 sec delay
        String pushUrl = config.optString("pushUrl", "").replace("{host}", teamHost);
        msgServer.updatePushToken(ownName, teamName, config.optString("token", ""), pushUrl);
        return;
    }
    // Read extra team configuration (e.g. icon and schedule)
    TeamConfig cTeam = new TeamConfig(config, teamName);
    // Store details about location query
    updateLocateHistory(messageIn, cTeam.isBlocked(), msgType, time);
    if (cTeam.isBlocked())
        msgServer.addBlockedField();
    msgServer.post(ALIVE);
    if (cTeam.isBlocked() || CHAT.equals(msgType))
        return; // skip giving your location
    try {
        //Log.d(TAG, "myContext: " + myContext.getPackageName());
        new MyLocation(myContext, myLocationResult, messageIn.optInt("accuracy", 50),
                config.optInt("timeout", 60)).start();
        JSONObject location = myLocationResult.getJsonLocation();
        //Log.d(TAG, "Background position accuracy: " + location.optInt("accuracy"));
        if (cTeam.getIcon() != null)
            msgServer.addIconField(cTeam.getIcon());
        msgServer.post(POSITION, location.toString());
    } catch (Exception e) {
        Log.e(TAG, "LocationProvider exception ", e);
        msgServer.post(FAILURE, e.getMessage());
    }
    Log.d(TAG, "Handle location query...completed!");
}

From source file:com.bt.download.android.gui.transfers.PeerHttpDownload.java

/**
 * /*from  w  ww .  jav a2  s  .  c  o  m*/
 * @param delay in seconds.
 * @param retry
 */
private void start(final int delay, final int retry) {
    if (status == STATUS_SAVE_DIR_ERROR) {
        return;
    }

    Engine.instance().getThreadPool().execute(new Thread(getDisplayName()) {
        public void run() {
            try {
                status = STATUS_WAITING;
                SystemClock.sleep(delay * 1000);

                status = STATUS_DOWNLOADING;
                String uri = peer.getDownloadUri(fd);
                new HttpFetcher(uri).save(savePath, new DownloadListener(retry));
                Librarian.instance().scan(savePath);
            } catch (Throwable e) {
                error(e);
            }
        }
    });
}

From source file:com.owncloud.android.services.observer.AdvancedFileAlterationObserver.java

/**
 * Final processing.//from   ww w  .j av a 2 s.com
 *
 * @throws Exception if an error occurs
 */
public void destroy() throws Exception {
    Iterator iterator = getMagicListeners().iterator();
    while (iterator.hasNext()) {
        AdvancedFileAlterationListener AdvancedFileAlterationListener = (AdvancedFileAlterationListener) iterator
                .next();
        while (AdvancedFileAlterationListener.getActiveTasksCount() > 0) {
            SystemClock.sleep(250);
        }
    }
}

From source file:com.baidao.realm_threadexample.ThreadFragment.java

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

    // Enable UI refresh while the fragment is active.
    realm.addChangeListener(realmListener);

    // Create background thread that add a new dot every 0.5 second.
    backgroundThread = new Thread() {

        @Override//from www. ja v  a 2s  .  c  o  m
        public void run() {
            // Realm instances cannot be shared between threads, so we need to create a new
            // instance on the background thread.
            final int redColor = getResources().getColor(R.color.realm_red);
            final Realm backgroundThreadRealm = Realm.getDefaultInstance();
            while (!backgroundThread.isInterrupted()) {
                backgroundThreadRealm.executeTransaction(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                        // Add red dot from the background thread
                        Dot dot = backgroundThreadRealm.createObject(Dot.class);
                        dot.setX(random.nextInt(100));
                        dot.setY(random.nextInt(100));
                        dot.setColor(redColor);
                    }
                });

                // Wait 0.5 sec. before adding the next dot.
                SystemClock.sleep(500);
            }

            // Also close Realm instances used in background threads.
            backgroundThreadRealm.close();
        }
    };
    backgroundThread.start();
}

From source file:com.nextgis.woody.fragment.LoginFragment.java

private void signup() {
    if (!UiUtil.isEmailValid(mLogin.getText().toString())) {
        Toast.makeText(getActivity(), R.string.email_not_valid, Toast.LENGTH_SHORT).show();
        return;//from w  w  w .  j a va  2s.  co m
    }
    mSignInButton.setEnabled(false);
    Runnable signUp = new Runnable() {
        @Override
        public void run() {
            final boolean[] result = new boolean[1];

            Thread t = new Thread(new Runnable() {
                @Override
                public void run() {
                    result[0] = NGWUtil.signUp(mUrlText, mLogin.getText().toString(),
                            mPassword.getText().toString(), null, null);
                }
            });
            t.start();

            while (t.isAlive()) {
                SystemClock.sleep(300);
            }

            if (result[0]) {
                getLoaderManager().restartLoader(R.id.auth_token_loader, null, LoginFragment.this);
            } else {
                Toast.makeText(getActivity(), R.string.error_sign_up, Toast.LENGTH_LONG).show();
            }

            if (mProgressDialog.isShowing()) {
                mProgressDialog.dismiss();
            }
        }
    };

    new Handler().post(signUp);
}

From source file:com.bt.download.android.gui.transfers.HttpDownload.java

/**
 * /*  w  w w  .java 2  s .com*/
 * @param delay in seconds.
 * @param retry
 */
private void start(final int delay, final int retry) {
    if (status == STATUS_SAVE_DIR_ERROR) {
        return;
    }

    Engine.instance().getThreadPool().execute(new Thread(getDisplayName()) {
        public void run() {
            try {
                status = STATUS_WAITING;
                SystemClock.sleep(delay * 1000);

                status = STATUS_DOWNLOADING;
                String uri = link.getUrl();
                new HttpFetcher(uri, 10000).save(savePath, new DownloadListener(retry));
                Librarian.instance().scan(savePath);
            } catch (Throwable e) {
                error(e);
            }
        }
    });
}

From source file:com.frostwire.android.gui.transfers.HttpDownload.java

/**
 * /*from   w w  w  .  java  2 s .  c o m*/
 * @param delay in seconds.
 * @param retry
 */
private void start(final int delay, final int retry) {
    if (status == STATUS_SAVE_DIR_ERROR || status == STATUS_ERROR_DISK_FULL || status == STATUS_ERROR) {
        return;
    }

    Engine.instance().getThreadPool().execute(new Thread(getDisplayName()) {
        public void run() {
            try {
                status = STATUS_WAITING;
                SystemClock.sleep(delay * 1000);

                status = STATUS_DOWNLOADING;
                String uri = link.getUrl();
                new HttpFetcher(uri, 10000).save(savePath, new DownloadListener(retry));
                Librarian.instance().scan(savePath);
            } catch (Throwable e) {
                error(e);
            }
        }
    });
}

From source file:cn.edu.szjm.support.images.remote.RemoteImageLoader.java

/**
 * Creates a new ImageLoader that is backed by an {@link ImageCache}. The cache will by default
 * cache to the device's external storage, and expire images after 1 day. You can set useCache
 * to false and then supply your own image cache instance via {@link #setImageCache(ImageCache)}
 * , or fine-tune the default one through {@link #getImageCache()}.
 * /*from  w  w w  .  j  a  va2  s.com*/
 * @param context
 *            the current context
 * @param createCache
 *            whether to create a default {@link ImageCache} used for caching
 */
public RemoteImageLoader(final Context context, boolean usingCache) {
    //        executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(DEFAULT_POOL_SIZE);
    this.usingCache = usingCache;
    if (usingCache) {
        imageCache = SharedImageCache.getSharedImageCache();
    } else {
        imageCache = null;
    }
    errorDrawable = context.getResources().getDrawable(android.R.drawable.ic_dialog_alert);
    task = new IgnitedAsyncTask<Context, Void, Void, Bitmap>() {
        @Override
        public boolean onTaskCompleted(Bitmap bitmap) {
            if (!cancel) {
                handler.handleImageLoaded(bitmap, null);
            }
            return true;
        }

        @Override
        public boolean onTaskFailed(Exception error) {
            if (task != null) {
                Log.d("test", "failed " + task.getStatus() + task);
            }
            return true;
        }

        //            @Override
        //            protected void onCancelled() {
        //               if(task != null) {
        //                  Log.d("test", "cancel "+task.getStatus() + task + isCancelled());
        //               }
        //            }
    };
    IgnitedAsyncTaskCallable<Context, Void, Void, Bitmap> callable = new IgnitedAsyncTaskCallable<Context, Void, Void, Bitmap>() {
        @Override
        public Bitmap call(IgnitedAsyncTask<Context, Void, Void, Bitmap> task) throws Exception {
            // TODO Auto-generated method stub
            if (cancel) {
                return null;
            }
            Bitmap bitmap = null;
            if (imageCache != null) {
                // at this point we know the image is not in memory, but it could be cached to SD card
                bitmap = imageCache.getBitmap(imageUrl);
            }
            if (bitmap == null) {
                bitmap = downloadImage(context);
            }
            return bitmap;
        }

        protected Bitmap downloadImage(Context context) {
            int timesTried = 1;
            while (timesTried <= numRetries && !cancel) {
                try {
                    if (cancel) {
                        return null;
                    }
                    byte[] imageData = retrieveImageData(context);
                    if (imageData == null) {
                        break;
                    }
                    if (imageCache != null) {
                        imageCache.put(imageUrl, imageData);
                    }
                    return BitmapFactory.decodeByteArray(imageData, 0, imageData.length);
                } catch (Throwable e) {
                    Log.w(LOG_TAG, "download for " + imageUrl + " failed (attempt " + timesTried + ")");
                    e.printStackTrace();
                    SystemClock.sleep(DEFAULT_RETRY_HANDLER_SLEEP_TIME);
                    timesTried++;
                }
            }
            return null;
        }

        protected byte[] retrieveImageData(Context context) throws IOException {
            IgnitedHttp http = new IgnitedHttp(context);
            http.disableResponseCache(true);
            IgnitedHttpRequest request = http.get(imageUrl, true).retries(3).expecting(200);
            request.setWrapResponse(false);
            if (cancel) {
                return null;
            }
            HttpResponse response = (HttpResponse) request.send();
            HttpEntity entity = response.getEntity();
            //                URL url = new URL(imageUrl);
            //                HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // determine the image size and allocate a buffer
            int fileSize = (int) entity.getContentLength();
            Log.d(LOG_TAG, "fetching image " + imageUrl + " ("
                    + (fileSize <= 0 ? "size unknown" : Integer.toString(fileSize)) + ")");
            BufferedInputStream istream = new BufferedInputStream(entity.getContent());
            try {
                if (fileSize <= 0) {
                    Log.w(LOG_TAG, "Server did not set a Content-Length header, will default to buffer size of "
                            + defaultBufferSize + " bytes");
                    ByteArrayOutputStream buf = new ByteArrayOutputStream(defaultBufferSize);
                    byte[] buffer = new byte[defaultBufferSize];
                    int bytesRead = 0;
                    while (bytesRead != -1) {
                        if (cancel) {
                            return null;
                        }
                        bytesRead = istream.read(buffer, 0, defaultBufferSize);
                        if (bytesRead > 0)
                            buf.write(buffer, 0, bytesRead);
                    }
                    return buf.toByteArray();
                } else {
                    byte[] imageData = new byte[fileSize];

                    int bytesRead = 0;
                    int offset = 0;
                    while (bytesRead != -1 && offset < fileSize) {
                        if (cancel) {
                            return null;
                        }
                        bytesRead = istream.read(imageData, offset, fileSize - offset);
                        offset += bytesRead;
                    }
                    return imageData;
                }
            } finally {
                // clean up
                try {
                    istream.close();
                    //connection.disconnect();
                } catch (Exception ignore) {
                }
            }
        }
    };
    task.setCallable(callable);
}

From source file:com.renjunzheng.vendingmachine.MyGcmListenerService.java

private void updatePurchaseInfo(String purchaseInfo) {
    try {/*from w  w  w  . j a  va 2  s. c  om*/
        DataDbHelper dbHelper = new DataDbHelper(this);
        SQLiteDatabase database = dbHelper.getWritableDatabase();

        database.delete(DataContract.PurchasedEntry.TABLE_NAME, null, null);
        database.execSQL(
                "DELETE FROM SQLITE_SEQUENCE WHERE NAME = '" + DataContract.PurchasedEntry.TABLE_NAME + "'");

        JSONArray valueArray = new JSONArray(purchaseInfo);
        Log.i(TAG, "the valueArray length: " + Integer.toString(valueArray.length()));
        for (int lc = 0; lc < valueArray.length(); ++lc) {
            JSONObject infoJson = valueArray.getJSONObject(lc);
            String item_name = infoJson.getString("item_name");
            database.execSQL("DELETE FROM SQLITE_SEQUENCE WHERE NAME = '"
                    + DataContract.PurchasedEntry.TABLE_NAME + "'");

            //query based on this item_name and get item id
            //currently if queried has no such item in current database then don't insert to purchase table
            //find user id using the stored email
            Cursor itemIDCursor;
            int waitTime = 0;
            boolean breaked = false;
            do {
                String[] itemProj = new String[] { DataContract.ItemEntry._ID };
                String[] itemSelArgs = new String[] { item_name };
                itemIDCursor = database.query(DataContract.ItemEntry.TABLE_NAME, itemProj,
                        DataContract.ItemEntry.COLUMN_ITEM_NAME + " = ?", itemSelArgs, null, null, null);
                if (waitTime != 0) {
                    // if the item is not yet exists in the item table, probably means update purchase get called before update storage. So wait until find
                    SystemClock.sleep(1000);
                    if (++waitTime > 30) {
                        breaked = true;
                        break;
                    }
                } else if (waitTime == 0) {
                    waitTime = 1;
                }
            } while (itemIDCursor == null || itemIDCursor.getCount() == 0);

            if (!breaked) {
                itemIDCursor.moveToNext();
                int itemID = itemIDCursor.getInt(0);
                itemIDCursor.close();

                String[] userProj = new String[] { DataContract.UserEntry._ID };
                String user_email = infoJson.getString("email");
                String[] userSelArgs = new String[] { user_email };
                Cursor userIDCursor = database.query(DataContract.UserEntry.TABLE_NAME, userProj,
                        DataContract.UserEntry.COLUMN_EMAIL + " = ?", userSelArgs, null, null, null);
                userIDCursor.moveToNext();
                Log.i(TAG, "userID: " + user_email);
                int userID = userIDCursor.getInt(0);
                Log.i(TAG, "itemID: " + itemID);
                Log.i(TAG, "userID: " + userID);
                userIDCursor.close();
                ContentValues newValues = new ContentValues();
                newValues.put(DataContract.PurchasedEntry.COLUMN_ITEM_KEY, itemID);
                newValues.put(DataContract.PurchasedEntry.COLUMN_USER_KEY, userID);
                newValues.put(DataContract.PurchasedEntry.COLUMN_ORDER_TIME, infoJson.getString("order_time"));
                newValues.put(DataContract.PurchasedEntry.COLUMN_PICK_UP_TIME,
                        infoJson.getString("pickup_time"));
                newValues.put(DataContract.PurchasedEntry.COLUMN_QUANTITY, infoJson.getString("quantity"));
                newValues.put(DataContract.PurchasedEntry.COLUMN_RECEIPT_NUM, infoJson.getString("receipt"));
                Uri returnedUri = getContentResolver().insert(DataContract.PurchasedEntry.CONTENT_URI,
                        newValues);
                Log.i(TAG, "inserted row num " + ContentUris.parseId(returnedUri));
            }
        }

        database.close();
        dbHelper.close();
    } catch (JSONException e) {
        Log.e(TAG, "error when parsing Json");
    }
}

From source file:android.support.v7.testutils.TestUtils.java

public static void waitForActivityDestroyed(BaseTestActivity activity) {
    while (!activity.isDestroyed()) {
        SystemClock.sleep(30);
    }
}