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.spoiledmilk.ibikecph.navigation.routing_engine.SMRoute.java

@Override
public void onResponseReceived(int requestType, Object response) {
    switch (requestType) {
    case SMHttpRequest.REQUEST_GET_ROUTE:
        JsonNode jsonRoot = ((RouteInfo) response).jsonRoot;
        if (jsonRoot == null || jsonRoot.path("status").asInt(-1) != 0) {
            if (listener != null)
                listener.routeNotFound();
        } else {//from w w  w.j  a v  a  2s.c om
            setupRoute(jsonRoot);
            if (listener != null)
                listener.startRoute();
        }
        break;
    case SMHttpRequest.REQUEST_GET_RECALCULATED_ROUTE:
        final JsonNode jRoot = ((RouteInfo) response).jsonRoot;

        if (jRoot == null || jRoot.path("status").asInt() != 0) {
            if (listener != null) {
                listener.serverError();
            }
            recalculationInProgress = false;
            return;
        }

        final Handler h = new Handler();
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {

                boolean ok = parseFromJson(jRoot, null, isRouteBroken);

                //                        logWaypoints();

                if (ok) {
                    approachingTurn = false;
                    h.post(new Runnable() {
                        @Override
                        public void run() {
                            if (lastLocation != null) {
                                visitLocation(lastLocation);
                            }
                            if (visitedLocations != null && visitedLocations.size() > 0) {
                                // visitLocation(visitedLocations.get(visitedLocations.size() - 1));
                            }
                            if (SMLocationManager.getInstance().hasValidLocation()) {
                                updateDistances(SMLocationManager.getInstance().getLastValidLocation());
                            }
                            if (listener != null) {
                                listener.routeRecalculationDone();
                                listener.updateRoute();
                            }
                            recalculationInProgress = false;
                        }
                    });
                } else {
                    h.post(new Runnable() {
                        @Override
                        public void run() {
                            if (listener != null)
                                listener.serverError();
                            recalculationInProgress = false;
                        }
                    });
                }

            }
        });
        t.setPriority(Thread.MIN_PRIORITY);
        t.start();
    }
}

From source file:ch.bfh.evoting.alljoyn.BusHandler.java

/**
 * Initialize AllJoyn//from   ww w  .  j  a v a  2 s  . c  o m
 */
private void doInit() {
    PeerGroupListener pgListener = new PeerGroupListener() {

        @Override
        public void foundAdvertisedName(String groupName, short transport) {
            Intent i = new Intent("advertisedGroupChange");
            LocalBroadcastManager.getInstance(context).sendBroadcast(i);
        }

        @Override
        public void lostAdvertisedName(String groupName, short transport) {
            Intent i = new Intent("advertisedGroupChange");
            LocalBroadcastManager.getInstance(context).sendBroadcast(i);
        }

        @Override
        public void groupLost(String groupName) {
            if (mGroupManager.listHostedGroups().contains(groupName)
                    && mGroupManager.getNumPeers(groupName) == 1) {
                //signal was send because admin stays alone in the group
                //not necessary to manage this case for us
                Log.d(TAG, "Group destroyed event ignored");
                return;
            }
            Log.d(TAG, "Group " + groupName + " was destroyed.");
            Intent i = new Intent("groupDestroyed");
            i.putExtra("groupName", groupName);
            LocalBroadcastManager.getInstance(context).sendBroadcast(i);
        }

        @Override
        public void peerAdded(String busId, String groupName, int numParticipants) {
            Log.d(TAG, "peer added");

            if (amIAdmin) {
                Log.d(TAG, "Sending salt " + Base64.encodeToString(messageEncrypter.getSalt(), Base64.DEFAULT));
                Message msg = obtainMessage(BusHandler.PING);
                Bundle data = new Bundle();
                data.putString("groupName", lastJoinedNetwork);
                data.putString("pingString", Base64.encodeToString(messageEncrypter.getSalt(), Base64.DEFAULT));
                data.putBoolean("encrypted", false);
                data.putSerializable("type", Type.SALT);
                msg.setData(data);
                sendMessage(msg);
            }

            //update UI
            LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent("participantStateUpdate"));

        }

        @Override
        public void peerRemoved(String peerId, String groupName, int numPeers) {
            //update UI
            Log.d(TAG, "peer left");
            Intent intent = new Intent("participantStateUpdate");
            intent.putExtra("action", "left");
            intent.putExtra("id", peerId);
            LocalBroadcastManager.getInstance(context).sendBroadcast(intent);

            super.peerRemoved(peerId, groupName, numPeers);
        }

    };

    ArrayList<BusObjectData> busObjects = new ArrayList<BusObjectData>();
    Handler mainHandler = new Handler(context.getMainLooper());

    Runnable myRunnable = new Runnable() {

        @Override
        public void run() {
            org.alljoyn.bus.alljoyn.DaemonInit.PrepareDaemon(context);
        }

    };
    mainHandler.post(myRunnable);

    busObjects.add(new BusObjectData(mSimpleService, "/SimpleService"));
    mGroupManager = new PeerGroupManager(SERVICE_NAME, pgListener, busObjects);
    mGroupManager.registerSignalHandlers(this);
}

From source file:com.facebook.Session.java

private static void runWithHandlerOrExecutor(Handler handler, Runnable runnable) {
    if (handler != null) {
        handler.post(runnable);
    } else {/*from ww w  .  j  a v  a  2 s . c  om*/
        Settings.getExecutor().execute(runnable);
    }
}

From source file:com.corporatetaxi.TaxiOntheWay_Activity.java

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

    final Interpolator interpolator = new LinearInterpolator();
    handler.post(new Runnable() {
        @Override//from w w  w  .j a  va  2s  . c o m
        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);
                }
            }
            map.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(lat, lng)));
        }
    });

}

From source file:org.appspot.apprtc.util.ThumbnailsCacheManager.java

public static void LoadImage(final String url, LoadImageCallback callback, final Resources resources,
        final String displayname, final boolean rounded, boolean fromCache) {
    final LoadImageCallback mCallback = callback;
    final Handler uiHandler = new Handler();
    final int FG_COLOR = 0xFFFAFAFA;
    final String name = displayname;

    if (fromCache) {
        Bitmap bitmap = ThumbnailsCacheManager.getBitmapFromDiskCache(url);

        if (bitmap != null) {
            if (rounded) {
                RoundedBitmapDrawable roundedBitmap = RoundedBitmapDrawableFactory.create(resources, bitmap);
                roundedBitmap.setCircular(true);
                mCallback.onImageLoaded(roundedBitmap.getBitmap());
            } else {
                mCallback.onImageLoaded(bitmap);
            }/*from   w  w  w  .java  2s  . c om*/
            return;
        }
    }

    AsyncHttpURLConnection httpConnection = new AsyncHttpURLConnection("GET", url, "",
            new AsyncHttpURLConnection.AsyncHttpEvents() {
                @Override
                public void onHttpError(String errorMessage) {
                    Log.d("LoadImage", errorMessage);
                }

                @Override
                public void onHttpComplete(String response) {
                    int size = 256;
                    Bitmap bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
                    Canvas canvas = new Canvas(bitmap);
                    final String trimmedName = name == null ? "" : name.trim();
                    drawTile(canvas, trimmedName, 0, 0, size, size);
                    ThumbnailsCacheManager.addBitmapToCache(url, bitmap);
                    onHttpComplete(bitmap);
                }

                @Override
                public void onHttpComplete(final Bitmap response) {
                    if (mCallback != null) {
                        uiHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                if (rounded) {
                                    RoundedBitmapDrawable roundedBitmap = RoundedBitmapDrawableFactory
                                            .create(resources, response);
                                    roundedBitmap.setCircular(true);
                                    mCallback.onImageLoaded(roundedBitmap.getBitmap());
                                } else {
                                    mCallback.onImageLoaded(response);
                                }

                            }

                        });

                    }
                }

                private boolean drawTile(Canvas canvas, String letter, int tileColor, int left, int top,
                        int right, int bottom) {
                    letter = letter.toUpperCase(Locale.getDefault());
                    Paint tilePaint = new Paint(), textPaint = new Paint();
                    tilePaint.setColor(tileColor);
                    textPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
                    textPaint.setColor(FG_COLOR);
                    textPaint.setTypeface(Typeface.create("sans-serif-light", Typeface.NORMAL));
                    textPaint.setTextSize((float) ((right - left) * 0.8));
                    Rect rect = new Rect();

                    canvas.drawRect(new Rect(left, top, right, bottom), tilePaint);
                    textPaint.getTextBounds(letter, 0, 1, rect);
                    float width = textPaint.measureText(letter);
                    canvas.drawText(letter, (right + left) / 2 - width / 2,
                            (top + bottom) / 2 + rect.height() / 2, textPaint);
                    return true;
                }

                private boolean drawTile(Canvas canvas, String name, int left, int top, int right, int bottom) {
                    if (name != null) {
                        final String letter = getFirstLetter(name);
                        final int color = ThumbnailsCacheManager.getColorForName(name);
                        drawTile(canvas, letter, color, left, top, right, bottom);
                        return true;
                    }
                    return false;
                }

            });
    httpConnection.setBitmap();
    httpConnection.send();
}

From source file:jp.app_mart.billing.AppmartHelper.java

/**
 * thread??/*from   ww w .j  a v a2  s .  com*/
 * @param querySkuDetails
 * @param moreSkus
 * @param listener
 */
public void queryInventoryAsync(final List<String> moreSkus,
        final QueryAppmartInventoryFinishedListener listener) {

    final Handler handler = new Handler();

    checkSetupDone("queryInventory");
    flagStartAsync("refresh inventory");

    (new Thread(new Runnable() {

        public void run() {

            AppmartResult result = new AppmartResult(BILLING_RESPONSE_RESULT_OK,
                    mContext.getString(R.string.inventory_refreshed));
            AppmartInventory inv = null;

            try {
                inv = queryInventory(true, moreSkus);
            } catch (AppmartException ex) {
                result = ex.getResult();
            }

            flagEndAsync();

            final AppmartResult result_f = result;
            final AppmartInventory inv_f = inv;
            handler.post(new Runnable() {
                public void run() {
                    listener.onQueryInventoryFinished(result_f, inv_f);
                }
            });
        }
    })).start();

}

From source file:im.neon.services.EventStreamService.java

/**
 * internal start.//from w ww  .  java 2 s  . com
 */
private void start() {
    StreamAction state = getServiceState();

    if (state == StreamAction.START) {
        Log.e(LOG_TAG, "start : Already started.");
        return;
    } else if ((state == StreamAction.PAUSE) || (state == StreamAction.CATCHUP)) {
        Log.e(LOG_TAG, "start : Resuming active stream.");
        resume();
        return;
    }

    if (mSessions == null) {
        Log.e(LOG_TAG, "start : No valid MXSession.");
        return;
    }

    Log.d(LOG_TAG, "## start : start the service");

    mActiveEventStreamService = this;

    for (MXSession session : mSessions) {
        if (null == session.getDataHandler()) {
            Log.e(LOG_TAG, "start : the session is not anymore valid.");
            return;
        }

        session.getDataHandler().addListener(mEventsListener);
        session.getDataHandler().getCallsManager().addListener(mCallsManagerListener);
        final IMXStore store = session.getDataHandler().getStore();

        // the store is ready (no data loading in progress...)
        if (store.isReady()) {
            startEventStream(session, store);
        } else {
            final MXSession fSession = session;
            // wait that the store is ready  before starting the events listener
            store.addMXStoreListener(new MXStoreListener() {
                @Override
                public void onStoreReady(String accountId) {
                    startEventStream(fSession, store);
                }

                @Override
                public void onStoreCorrupted(String accountId, String description) {
                    // start a new initial sync
                    if (null == store.getEventStreamToken()) {
                        startEventStream(fSession, store);
                    } else {
                        // the data are out of sync
                        Matrix.getInstance(getApplicationContext()).reloadSessions(getApplicationContext());
                    }
                }

                @Override
                public void onStoreOOM(final String accountId, final String description) {
                    Handler uiHandler = new Handler(getMainLooper());

                    uiHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(), accountId + " : " + description,
                                    Toast.LENGTH_LONG).show();

                            Matrix.getInstance(getApplicationContext()).reloadSessions(getApplicationContext());
                        }
                    });
                }
            });
        }
    }

    mGcmRegistrationManager = Matrix.getInstance(getApplicationContext()).getSharedGCMRegistrationManager();

    if (!mGcmRegistrationManager.useGCM()) {
        updateServiceForegroundState();
    }

    setServiceState(StreamAction.START);
}

From source file:com.corporatetaxi.TaxiArrived_Acitivity.java

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

    final Interpolator interpolator = new LinearInterpolator();
    handler.post(new Runnable() {
        @Override/*from  w  ww. j a  v  a  2 s  .  c o m*/
        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);
                }
            }
            map.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(lat, lng)));
        }
    });
}

From source file:com.hzl.administrator.wifi.WifiStatusTest.java

private final void updatePingState() {
    final Handler handler = new Handler();
    // Set all to unknown since the threads will take a few secs to update.
    mPingIpAddrResult = getResources().getString(R.string.radioInfo_unknown);
    mPingHostnameResult = getResources().getString(R.string.radioInfo_unknown);
    mHttpClientTestResult = getResources().getString(R.string.radioInfo_unknown);

    mPingIpAddr.setText(mPingIpAddrResult);
    mPingHostname.setText(mPingHostnameResult);
    mHttpClientTest.setText(mHttpClientTestResult);

    final Runnable updatePingResults = new Runnable() {
        public void run() {
            mPingIpAddr.setText(mPingIpAddrResult);
            mPingHostname.setText(mPingHostnameResult);
            mHttpClientTest.setText(mHttpClientTestResult);
        }/*from   ww w  .j  a  v  a  2  s  . c om*/
    };
    Thread ipAddrThread = new Thread() {
        @Override
        public void run() {
            pingIpAddr();
            handler.post(updatePingResults);
        }
    };
    ipAddrThread.start();

    Thread hostnameThread = new Thread() {
        @Override
        public void run() {
            pingHostname();
            handler.post(updatePingResults);
        }
    };
    hostnameThread.start();

    Thread httpClientThread = new Thread() {
        @Override
        public void run() {
            httpClientTest();
            handler.post(updatePingResults);
        }
    };
    httpClientThread.start();
}

From source file:org.appspot.apprtc.util.ThumbnailsCacheManager.java

public static void LoadMenuImage(final String url, MenuItem menuItem, String displayname, final boolean rounded,
        Resources resources, boolean fromCache) {
    final Resources mResources = resources;
    final WeakReference<MenuItem> menuItemImage = new WeakReference<MenuItem>(menuItem);
    final Handler uiHandler = new Handler();
    final int FG_COLOR = 0xFFFAFAFA;
    final String name = displayname;

    if (fromCache) {
        Bitmap bitmap = ThumbnailsCacheManager.getBitmapFromDiskCache(url);

        if (bitmap != null) {
            if (rounded) {
                RoundedBitmapDrawable roundedBitmap = RoundedBitmapDrawableFactory.create(mResources, bitmap);
                roundedBitmap.setCircular(true);
                menuItemImage.get().setIcon(roundedBitmap);
            } else {
                menuItemImage.get().setIcon(new BitmapDrawable(bitmap));
            }/*from  www. j  a v  a 2  s.  c om*/
            return;
        }
    }

    AsyncHttpURLConnection httpConnection = new AsyncHttpURLConnection("GET", url, "",
            new AsyncHttpURLConnection.AsyncHttpEvents() {
                @Override
                public void onHttpError(String errorMessage) {
                    Log.d("LoadImage", errorMessage);
                }

                @Override
                public void onHttpComplete(String response) {
                    int size = 96;
                    Bitmap bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
                    Canvas canvas = new Canvas(bitmap);
                    final String trimmedName = name == null ? "" : name.trim();
                    drawTile(canvas, trimmedName, 0, 0, size, size);
                    ThumbnailsCacheManager.addBitmapToCache(url, bitmap);
                    onHttpComplete(bitmap);
                }

                @Override
                public void onHttpComplete(final Bitmap response) {
                    if (menuItemImage != null && menuItemImage.get() != null) {
                        uiHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                if (rounded) {
                                    RoundedBitmapDrawable roundedBitmap = RoundedBitmapDrawableFactory
                                            .create(mResources, response);
                                    roundedBitmap.setCircular(true);
                                    menuItemImage.get().setIcon(roundedBitmap);
                                } else {
                                    menuItemImage.get().setIcon(new BitmapDrawable(response));
                                }
                            }

                        });

                    }
                }

                private boolean drawTile(Canvas canvas, String letter, int tileColor, int left, int top,
                        int right, int bottom) {
                    letter = letter.toUpperCase(Locale.getDefault());
                    Paint tilePaint = new Paint(), textPaint = new Paint();
                    tilePaint.setColor(tileColor);
                    textPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
                    textPaint.setColor(FG_COLOR);
                    textPaint.setTypeface(Typeface.create("sans-serif-light", Typeface.NORMAL));
                    textPaint.setTextSize((float) ((right - left) * 0.8));
                    Rect rect = new Rect();

                    canvas.drawRect(new Rect(left, top, right, bottom), tilePaint);
                    textPaint.getTextBounds(letter, 0, 1, rect);
                    float width = textPaint.measureText(letter);
                    canvas.drawText(letter, (right + left) / 2 - width / 2,
                            (top + bottom) / 2 + rect.height() / 2, textPaint);
                    return true;
                }

                private boolean drawTile(Canvas canvas, String name, int left, int top, int right, int bottom) {
                    if (name != null) {
                        final String letter = getFirstLetter(name);
                        final int color = ThumbnailsCacheManager.getColorForName(name);
                        drawTile(canvas, letter, color, left, top, right, bottom);
                        return true;
                    }
                    return false;
                }

            });
    httpConnection.setBitmap();
    httpConnection.send();
}