Example usage for android.os Handler post

List of usage examples for android.os Handler post

Introduction

In this page you can find the example usage for android.os Handler post.

Prototype

public final boolean post(Runnable r) 

Source Link

Document

Causes the Runnable r to be added to the message queue.

Usage

From source file:com.mobshep.mobileshepherd.BrokenCrypto.java

private void startTimerFive() {
    final Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        public void run() {

            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();//  w  ww .j a  v a  2 s .  co m
            }
            handler.post(new Runnable() {
                public void run() {
                    messageFive.setVisibility(View.VISIBLE);
                }
            });

        }
    };
    new Thread(runnable).start();
}

From source file:com.eutectoid.dosomething.picker.PlacePickerFragment.java

private void onSearchTextTimerTriggered() {
    if (hasSearchTextChangedSinceLastQuery) {
        Handler handler = new Handler(Looper.getMainLooper());
        handler.post(new Runnable() {
            @Override//ww  w. ja va2 s .c  o m
            public void run() {
                FacebookException error = null;
                try {
                    loadData(true);
                } catch (FacebookException fe) {
                    error = fe;
                } catch (Exception e) {
                    error = new FacebookException(e);
                } finally {
                    if (error != null) {
                        OnErrorListener onErrorListener = getOnErrorListener();
                        if (onErrorListener != null) {
                            onErrorListener.onError(PlacePickerFragment.this, error);
                        } else {
                            Logger.log(LoggingBehavior.REQUESTS, TAG, "Error loading data : %s", error);
                        }
                    }
                }
            }
        });
    } else {
        // Nothing has changed in 2 seconds. Invalidate and forget about this timer.
        // Next time the user types, we will fire a query immediately again.
        searchTextTimer.cancel();
        searchTextTimer = null;
    }
}

From source file:com.dspot.declex.actions.NotificationActionHolder.java

void execute() {

    final Runnable execute = new Runnable() {

        @Override//  w  w  w.j  a  v a 2 s  .co  m
        public void run() {
            manager.notify(notificationId, builder.build());
            if (Shown != null)
                Shown.run();
        }
    };

    if (pendingLargeIconLoad != null) {
        BackgroundExecutor.execute(new Runnable() {

            @Override
            public void run() {
                try {
                    Bitmap bitmap = Picasso.with(context).load(pendingLargeIconLoad).get();
                    pendingLargeIconLoad = null;
                    builder.setLargeIcon(bitmap);
                } catch (IOException ignored) {
                }

                Handler mainHandler = new Handler(context.getMainLooper());
                mainHandler.post(execute);
            }
        });
    } else {
        execute.run();
    }

}

From source file:com.fatelon.partyphotobooth.setup.fragments.EventInfoSetupFragment.java

/**
 * Creates and stores a new event logo from an image {@link Uri}. Update ui when the operation completes.
 *
 * @param srcUri the {@link Uri} to the source image.
 *///from  ww w.jav a  2  s  . c  o  m
private void newLogo(final Uri srcUri) {
    if (TextHelper.isValid(srcUri.toString())) {
        final ContentResolver resolver = getActivity().getContentResolver();
        final Handler workerHandler = new Handler(MyApplication.getWorkerLooper());
        workerHandler.post(new Runnable() {

            @Override
            public void run() {
                // Load and create new logo.
                final Bitmap newLogo = ImageHelper.getScaledBitmap(resolver, srcUri,
                        BaseTitleHeader.EVENT_LOGO_MAX_WIDTH, BaseTitleHeader.EVENT_LOGO_MAX_HEIGHT);
                if (newLogo != null) {
                    // Store new logo in cache.
                    mBitmapCache.asyncPut(BaseTitleHeader.EVENT_LOGO_CACHE_KEY, newLogo,
                            new PersistedBitmapCache.IAsyncPutCallbacks() {

                                @Override
                                public void onSuccess(String key) {
                                    if (isActivityAlive()) {
                                        mLogoUri.setText(srcUri.toString());

                                        // tryGet() should always succeed since the cache has just been populated.
                                        final Bitmap logo = mBitmapCache.tryGet(key);
                                        if (logo != null) {
                                            // Set thumb as compound drawable, fitted to the text height.
                                            final BitmapDrawable thumb = new BitmapDrawable(getResources(),
                                                    logo);
                                            int thumbSize = (int) getResources()
                                                    .getDimension(R.dimen.text_size_normal);
                                            Point drawableSize = ImageHelper.getAspectFitSize(thumbSize,
                                                    thumbSize, logo.getWidth(), logo.getHeight());
                                            thumb.setBounds(0, 0, drawableSize.x, drawableSize.y);
                                            mLogoUri.setCompoundDrawables(null, null, thumb, null);
                                        }

                                        mLogoClear.setVisibility(View.VISIBLE);
                                    }
                                }

                                @Override
                                public void onFailure(String key) {
                                    postLogoError();
                                }
                            });
                } else {
                    postLogoError();
                }
            }
        });
    } else {
        postLogoError();
    }
}

From source file:com.SmartDial.ForegroundService.java

/**
 * Put the service in a foreground state to prevent app from being killed
 * by the OS./*  w  ww  .  j  av a  2 s .  c o m*/
 */
public void keepAwake() {
    final Handler handler = new Handler();

    if (!this.inSilentMode()) {
        startForeground(NOTIFICATION_ID, makeNotification());
    } else {
        Log.w("BackgroundMode", "In silent mode app may be paused by OS!");
    }

    BackgroundMode.deleteUpdateSettings();

    keepAliveTask = new TimerTask() {
        @Override
        public void run() {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    // Nothing to do here
                    // Log.d("BackgroundMode", "" + new Date().getTime());
                }
            });
        }
    };

    scheduler.schedule(keepAliveTask, 0, 1000);
}

From source file:com.masseyhacks.sjam.cheqout.ScannerActivity.java

public void addToCart(String itemID) {
    final ArrayList<String> info = getCartInfoFromFirebase("Products", itemID);
    //Log.e(TAG, info.size() + "");
    Handler h = new Handler(Looper.getMainLooper());
    h.post(new Runnable() {

        @Override/*from   w w  w . j a v  a  2 s  .com*/
        public void run() {
            Context context = getApplicationContext();
            String text = "";
            boolean toast = false;
            if (!info.isEmpty()) {
                //Item not in database
                //Log.e(TAG, info.get(0));
                if (info.get(0).equals("1")) {
                    text = "Item not recognized. Please try again.";
                    toast = true;
                } else {
                    if (!items.containsKey(info.get(0))) {
                        toast = true;
                        text = info.get(0) + ": $" + info.get(1);
                        items.put(info.get(0), Double.parseDouble(info.get(1)));
                        //                            quantities.put(Double.parseDouble(info.get(1)), 1);
                    }
                }
            }
            if (toast) {
                Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
            }
        }
    });
}

From source file:com.licubeclub.zionhs.PostViewActivity.java

private void networkTask() {

    final Handler mHandler = new Handler();

    new Thread() {
        public void run() {

            try {
                Document doc = Jsoup.connect(URL).get();
                Element element = doc.select("td").get(4);
                data = element.getAllElements().toString();

            } catch (IOException e) {
                e.printStackTrace();//from   w w  w .jav a 2 s  . c o m
            }

            mHandler.post(new Runnable() {
                public void run() {
                    WV.getSettings().setJavaScriptEnabled(true);
                    WV.setWebViewClient(new WebViewClient() {
                        public void onReceivedError(WebView view, int errorCode, String description,
                                String failingUrl) {
                            Toast.makeText(PostViewActivity.this, description, Toast.LENGTH_SHORT).show();
                        }
                    });
                    //                        WV.loadData(data,"text/html","utf-8");
                    if (data == null) {
                        data = getResources().getString(R.string.nodata);
                    } else if (data.equals("<td class=\"writeBody writeContent\"></td>")) {
                        data = getResources().getString(R.string.nodata);
                    } else {
                    }
                    Log.d("DATA", data);
                    WV.loadDataWithBaseURL(null, data, "text/html", "utf-8", null);
                    handler.sendEmptyMessage(0);
                }
            });

        }
    }.start();

}

From source file:com.wizardsofm.deskclock.alarms.AlarmStateManager.java

/**
 * This will set the alarm instance to the SNOOZE_STATE and update
 * the application notifications and schedule any state changes that need
 * to occur in the future./* ww  w  .j  a  v  a2 s  . c o  m*/
 *
 * @param context  application context
 * @param instance to set state to
 */
public static void setSnoozeState(final Context context, AlarmInstance instance, boolean showToast) {
    // Stop alarm if this instance is firing it
    AlarmService.stopAlarm(context, instance);

    // Calculate the new snooze alarm time
    String snoozeMinutesStr = Utils.getDefaultSharedPreferences(context)
            .getString(SettingsActivity.KEY_ALARM_SNOOZE, DEFAULT_SNOOZE_MINUTES);
    final int snoozeMinutes = Integer.parseInt(snoozeMinutesStr);
    Calendar newAlarmTime = Calendar.getInstance();
    newAlarmTime.add(Calendar.MINUTE, snoozeMinutes);

    // Update alarm state and new alarm time in db.
    LogUtils.i("Setting snoozed state to instance " + instance.mId + " for "
            + AlarmUtils.getFormattedTime(context, newAlarmTime));
    instance.setAlarmTime(newAlarmTime);
    instance.mAlarmState = AlarmInstance.SNOOZE_STATE;
    AlarmInstance.updateInstance(context.getContentResolver(), instance);

    // Setup instance notification and scheduling timers
    AlarmNotifications.showSnoozeNotification(context, instance);
    scheduleInstanceStateChange(context, instance.getAlarmTime(), instance, AlarmInstance.FIRED_STATE);

    // Display the snooze minutes in a toast.
    if (showToast) {
        final Handler mainHandler = new Handler(context.getMainLooper());
        final Runnable myRunnable = new Runnable() {
            @Override
            public void run() {
                String displayTime = String.format(context.getResources().getQuantityText(
                        com.wizardsofm.deskclock.R.plurals.alarm_alert_snooze_set, snoozeMinutes).toString(),
                        snoozeMinutes);
                Toast.makeText(context, displayTime, Toast.LENGTH_LONG).show();
            }
        };
        mainHandler.post(myRunnable);
    }

    // Instance time changed, so find next alarm that will fire and notify system
    updateNextAlarm(context);
}

From source file:de.quist.app.maps.example.MarkerDemoActivity.java

@Override
public boolean onMarkerClick(final Marker marker) {
    if (marker.equals(mPerth)) {
        // This causes the marker at Perth to bounce into position when it is clicked.
        final Handler handler = new Handler();
        final long start = SystemClock.uptimeMillis();
        final long duration = 1500;

        final Interpolator interpolator = new BounceInterpolator();

        handler.post(new Runnable() {
            @Override/*from  ww  w  .  ja  v  a 2 s  . c  o m*/
            public void run() {
                long elapsed = SystemClock.uptimeMillis() - start;
                float t = Math.max(1 - interpolator.getInterpolation((float) elapsed / duration), 0);
                marker.setAnchor(0.5f, 1.0f + 2 * t);

                if (t > 0.0) {
                    // Post again 16ms later.
                    handler.postDelayed(this, 16);
                }
            }
        });
    } else if (marker.equals(mAdelaide)) {
        // This causes the marker at Adelaide to change color and alpha.
        marker.setIcon(
                BuildConfig.MAP_BINDING.bitmapDescriptorFactory().defaultMarker(mRandom.nextFloat() * 360));
        marker.setAlpha(mRandom.nextFloat());
    }

    mLastSelectedMarker = marker;
    // We return false to indicate that we have not consumed the event and that we wish
    // for the default behavior to occur (which is for the camera to move such that the
    // marker is centered and for the marker's info window to open, if it has one).
    return false;
}

From source file:com.autonavi.gxdtaojin.toolbox.volley.Request.java

/**
 * Notifies the request queue that this request has finished (successfully or with error).
 * <p>//from   ww  w.j  av  a2  s .  c  o m
 * Also dumps all events from this request's event log; for debugging.
 * </p>
 */
void finish(final String tag) {
    if (mRequestQueue != null) {
        mRequestQueue.finish(this);
    }
    if (MarkerLog.ENABLED) {
        final long threadId = Thread.currentThread().getId();
        if (Looper.myLooper() != Looper.getMainLooper()) {
            // If we finish marking off of the main thread, we need to
            // actually do it on the main thread to ensure correct ordering.
            Handler mainThread = new Handler(Looper.getMainLooper());
            mainThread.post(new Runnable() {
                @Override
                public void run() {
                    mEventLog.add(tag, threadId);
                    mEventLog.finish(this.toString());
                }
            });
            return;
        }

        mEventLog.add(tag, threadId);
        mEventLog.finish(this.toString());
    } else {
        long requestTime = SystemClock.elapsedRealtime() - mRequestBirthTime;
        if (requestTime >= SLOW_REQUEST_THRESHOLD_MS) {
            VolleyLog.d("%d ms: %s", requestTime, this.toString());
        }
    }
}