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.android.adcnx.adlib.plugin.AdConnectLibrary.java

private PluginResult createAdBlock(JSONObject params, final String callbackID) {
    final String action = "create";

    if (_lib != null) {
        return createResultWithJSONMessage(Status.ERROR,
                "There is already an instance of the library" + "currently running.");
    }/*from  w w w .  j a  va2s  . c  o  m*/

    if (params == null) {
        return createResultWithJSONMessage(Status.ERROR, "No params passed for action " + action);
    }

    //_createCallbackID = callbackID;
    log("Creating a new AdBlock");

    final String publisherID = params.optString("id");

    if (publisherID.equalsIgnoreCase("")) {
        return createResultWithJSONMessage(Status.ERROR, "Missing publisher id");
    }

    log("have publisher id.");

    JSONObject size = params.optJSONObject("size");

    if (size == null) {
        return createResultWithJSONMessage(Status.ERROR, "Missing AdSize");
    }

    final int width = size.optInt("width");
    final int height = size.optInt("height");

    if (width < 1 || height < 1) {
        return createResultWithJSONMessage(Status.ERROR, "AdSize is too small");
    }

    final JSONObject layout = params.optJSONObject("layout");

    log("have AdSize");

    Handler h = new Handler(ctx.getContext().getMainLooper());
    final AdConnectLibrary self = this;
    h.post(new Runnable() {

        public void run() {
            _lib = new AdBlock(ctx.getContext(), new AdSize(width, height), publisherID);

            _lib.setAdListener(self);
            LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

            if (layout != null) {
                log("setting the layout");

                String gravity = layout.optString("gravity");
                if (!gravity.equalsIgnoreCase("")) {
                    log("Have gravity: " + gravity);
                    layoutParams.gravity = getGravity(gravity);
                }
            }

            log("have a new lib");

            ((LinearLayout) webView.getParent()).addView(_lib, layoutParams);

            log("successfully added adblock to webview");

            updateAdBlockCreation(callbackID);
        }

    });

    PluginResult result = createResultWithJSONMessage(Status.NO_RESULT, "Awaiting AdBlockCreation");
    result.setKeepCallback(true);
    return result;
}

From source file:com.example.com.benasque2014.mercurio.PuntosInfoFragment.java

private void addPoint(LatLng point) {
    if (markers == null)
        markers = new ArrayList<Marker>();
    if (points == null)
        points = new ArrayList<LatLng>();
    MarkerOptions marker = new MarkerOptions().position(point).title("Parada " + markers.size() + 1);

    final Marker mMarker = mMap.addMarker(marker);

    //if (markers.size()==0)
    //   Toast.makeText(getActivity(), "Haga click en un punto para eliminarlo", Toast.LENGTH_SHORT).show();

    markers.add(mMarker);/*from   w  w w  .  ja  v a 2s .c o m*/

    //mPage.getData().putParcelableArrayList(PuntosInfoPage.PUNTOS_DATA_KEY, (ArrayList<? extends Parcelable>) points);
    //mPage.notifyDataChanged();

    // 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
        public void run() {
            long elapsed = SystemClock.uptimeMillis() - start;
            float t = Math.max(1 - interpolator.getInterpolation((float) elapsed / duration), 0);
            mMarker.setAnchor(0.5f, 1.0f + 2 * t);

            if (t > 0.0) {
                // Post again 16ms later.
                handler.postDelayed(this, 16);
            }
        }
    });
    //TODO: si queremos aadir lineas entre los puntos
    //addLines();
}

From source file:com.example.map.BasicMapActivity.java

public void animateMarker(final Marker marker, final LatLng toPosition, final boolean hideMarker) {
    final Handler handler = new Handler();
    final long start = SystemClock.uptimeMillis();
    Projection proj = mMap.getProjection();
    Point startPoint = proj.toScreenLocation(marker.getPosition());
    final LatLng startLatLng = proj.fromScreenLocation(startPoint);
    final long duration = 500;

    final Interpolator interpolator = new LinearInterpolator();

    handler.post(new Runnable() {
        @Override/*from  w w  w  .j a  va 2s .  c  om*/
        public void run() {
            long elapsed = SystemClock.uptimeMillis() - start;
            float t = interpolator.getInterpolation((float) elapsed / duration);
            double lng = t * toPosition.longitude + (1 - t) * startLatLng.longitude;
            double lat = t * toPosition.latitude + (1 - t) * startLatLng.latitude;
            marker.setPosition(new LatLng(lat, lng));

            if (t < 1.0) {
                // Post again 16ms later.
                handler.postDelayed(this, 16);
            } else {
                if (hideMarker) {
                    marker.setVisible(false);
                } else {
                    marker.setVisible(true);
                }
            }
        }
    });
}

From source file:de.stadtrallye.rallyesoft.model.map.MapManager.java

private void notifyMapUpdate(final List<Node> nodes, final List<Edge> edges) {
    Handler handler;
    synchronized (mapListeners) {
        for (final IMapListener l : mapListeners) {
            handler = l.getCallbackHandler();
            if (handler == null) {
                l.onMapChange(nodes, edges);
            } else {
                handler.post(new Runnable() {
                    @Override/*from  w ww .j  a  va  2 s .c o m*/
                    public void run() {
                        l.onMapChange(nodes, edges);
                    }
                });
            }
        }
    }
}

From source file:com.android.volley.Request.java

/**
 * Notifies the request queue that this request has finished (successfully or with error).
 *
 * <p>Also dumps all events from this request's event log; for debugging.</p>
 *///w w w  .j  a v a 2s  .  co  m
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());
    }
}

From source file:com.honeycomb.cocos2dx.Soccer.java

public synchronized void onWindowFocusChanged(final boolean pHasWindowFocus) {
    super.onWindowFocusChanged(pHasWindowFocus);
    if (!pHasWindowFocus) {
        return;//from w ww.ja v  a2  s  . c o  m
    }
    Handler h = new Handler();
    Runnable r = new Runnable() {
        @Override
        public void run() {
            AndroidNDKHelper.SendMessageWithParameters("resumeBackgroundMusic", getDict());
        }
    };
    h.post(r);
}

From source file:com.androidinspain.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./*from  www. ja  va 2s. com*/
 *
 * @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
    final int snoozeMinutes = DataModel.getDataModel().getSnoozeLength();
    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.androidinspain.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:com.example.mapdemo.VisibleRegionDemoActivity.java

public void animatePadding(final int toLeft, final int toTop, final int toRight, final int toBottom) {

    final Handler handler = new Handler();
    final long start = SystemClock.uptimeMillis();
    final long duration = 1000;

    final Interpolator interpolator = new OvershootInterpolator();

    final int startLeft = currentLeft;
    final int startTop = currentTop;
    final int startRight = currentRight;
    final int startBottom = currentBottom;

    currentLeft = toLeft;/*ww w. j a va2 s  . c o m*/
    currentTop = toTop;
    currentRight = toRight;
    currentBottom = toBottom;

    handler.post(new Runnable() {
        @Override
        public void run() {
            long elapsed = SystemClock.uptimeMillis() - start;
            float t = interpolator.getInterpolation((float) elapsed / duration);

            int left = (int) (startLeft + ((toLeft - startLeft) * t));
            int top = (int) (startTop + ((toTop - startTop) * t));
            int right = (int) (startRight + ((toRight - startRight) * t));
            int bottom = (int) (startBottom + ((toBottom - startBottom) * t));

            mMap.setPadding(left, top, right, bottom);

            if (elapsed < duration) {
                // Post again 16ms later.
                handler.postDelayed(this, 16);
            }
        }
    });
}

From source file:com.dan.wizardduel.MainActivity.java

public void startCustomGame(String playerId, String opponentId, String roomId) {
    mMainMenuFragment.stopLoading();/* w w w  . j  a  v a2  s . c  o  m*/

    gameFragment.npcGame = false;
    if (playerId != null) {
        gameFragment.playerId = playerId;
    }
    if (opponentId != null) {
        gameFragment.opponentId = opponentId;
    }
    if (roomId != null) {
        gameFragment.roomId = roomId;
    }
    replayRequested = false;
    Runnable r = new Runnable() {
        @Override
        public void run() {
            switchToFragment(gameFragment);
        }
    };
    Handler h = new Handler();
    h.post(r);
}

From source file:net.ben.subsonic.androidapp.util.Util.java

public static void showPlayingNotification(final Context context, Handler handler, MusicDirectory.Entry song) {

    // Use the same text for the ticker and the expanded notification
    String title = song.getTitle();

    // Set the icon, scrolling text and timestamp
    final Notification notification = new Notification(R.drawable.stat_notify_playing, title,
            System.currentTimeMillis());
    notification.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;

    // The PendingIntent to launch our activity if the user selects this notification
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(context, FragActivity.class),
            0);//from  ww w.jav  a2s  .  co m

    String text = song.getArtist();
    notification.setLatestEventInfo(context, title, text, contentIntent);

    // Send the notification.
    handler.post(new Runnable() {
        @Override
        public void run() {
            NotificationManager notificationManager = (NotificationManager) context
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(Constants.NOTIFICATION_ID_PLAYING, notification);
        }
    });

    // Update widget
    DownloadService service = DownloadServiceImpl.getInstance();
    if (service != null) {
        SubsonicAppWidgetProvider.getInstance().notifyChange(context, service, true);
    }
}