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:hcm.ssj.creator.MainActivity.java

/**
 *
 *///from  w w  w.  j a v  a2s.c o  m
private void setExceptionHandler() {
    ExceptionHandler exceptionHandler = new ExceptionHandler() {
        @Override
        public void handle(final String location, final String msg, final Throwable t) {
            Monitor.notifyMonitor();
            Handler handler = new Handler(Looper.getMainLooper());
            Runnable runnable = new Runnable() {
                public void run() {
                    new AlertDialog.Builder(MainActivity.this).setTitle(R.string.str_error)
                            .setMessage(location + ": " + msg).setPositiveButton(R.string.str_ok, null)
                            .setIcon(android.R.drawable.ic_dialog_alert).show();
                }
            };
            handler.post(runnable);
        }
    };
    TheFramework.getFramework().setExceptionHandler(exceptionHandler);
}

From source file:com.chinamobile.webrtc.SpeechAuth.java

/**
 * Posts request data, gets bytes of response, and calls client when done.
 * Performs blocking I/O, so it must be called from its own thread.
**//*from w  w  w . j  a v  a  2s.  co m*/
private void performFetch(Handler callingThread) {
    try {
        // Post the credentials.
        connection.setDoOutput(true);
        OutputStream out = connection.getOutputStream();
        out.write(postData);
        out.close();
        // Wait for the response.  
        // Note that getInputStream will throw exception for non-200 status.
        InputStream response = connection.getInputStream();
        byte[] data = readAllBytes(response);
        // Extract the token from JSON.
        String body = new String(data, "UTF8");
        JSONObject json = new JSONObject(body);
        final String token = json.getString("access_token");
        // Give it back to the client.
        callingThread.post(new Runnable() {
            public void run() {
                if (client != null)
                    client.handleResponse(token, null);
            }
        });
    } catch (final Exception ex) {
        callingThread.post(new Runnable() {
            public void run() {
                if (client != null)
                    client.handleResponse(null, ex);
            }
        });
    }
    // XXX: Should we close the connection?
    // finally { connection.close(); }
}

From source file:de.stadtrallye.rallyesoft.model.chat.Chatroom.java

private void notifyChatsChanged() {
    synchronized (listeners) {
        Handler handler;
        for (final IChatroomListener l : listeners) {
            handler = l.getCallbackHandler();
            if (handler == null) {
                l.onChatsChanged();/*from w w w .j a v  a  2s  .com*/
            } else {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        l.onChatsChanged();
                    }
                });
            }
        }
    }
}

From source file:com.ibm.pickmeup.activities.MapActivity.java

/**
 * Update map with the new coordinates for the driver
 * @param intent containing driver coordinates
 *//* w  w w.j  av  a2s  .c  o  m*/
private void updateMap(final Intent intent) {
    // not logging entry as it will flood the logs

    // getting driver LatLng values from the intent
    final LatLng driverLatLng = new LatLng(intent.getFloatExtra(Constants.LATITUDE, 0),
            intent.getFloatExtra(Constants.LONGITUDE, 0));

    // create driver marker if it doesn't exist and move the camera accordingly
    if (driverMarker == null) {
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(driverLatLng, 10));
        driverMarker = mMap.addMarker(new MarkerOptions().position(driverLatLng)
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_driver)));
        return;
    }

    // update driver location with LatLng
    driverLocation.setLatitude(driverLatLng.latitude);
    driverLocation.setLongitude(driverLatLng.longitude);

    // calculate current distance to the passenger
    float distance = passengerLocation.distanceTo(driverLocation) / 1000;

    // set the distance text
    distanceDetails.setText(String.format(getResources().getString(R.string.distance_with_value), distance));

    // calculating ETA - we are assuming here that the car travels at 20mph to simplify the calculations
    calendar = Calendar.getInstance();
    calendar.add(Calendar.MINUTE, Math.round(distance / 20 * 60));

    // set AM/PM to a relevant value
    AM_PM = getString(R.string.am);
    if (calendar.get(Calendar.AM_PM) == 1) {
        AM_PM = getString(R.string.pm);
    }

    // format ETA string to HH:MM
    String eta = String.format(getResources().getString(R.string.eta_with_value),
            calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), AM_PM);

    // set the ETA text
    etaDetails.setText(eta);

    // as we are throttling updates to the coordinates, we might need to smooth out the moving
    // of the driver's marker. To do so we are going to draw temporary markers between the
    // previous and the current coordinates. We are going to use interpolation for this and
    // use handler/looper to set the marker's position

    // get hold of the handler
    final Handler handler = new Handler();
    final long start = SystemClock.uptimeMillis();

    // get map projection and the driver's starting point
    Projection proj = mMap.getProjection();
    Point startPoint = proj.toScreenLocation(driverMarker.getPosition());
    final LatLng startLatLng = proj.fromScreenLocation(startPoint);
    final long duration = 150;

    // create new Interpolator
    final Interpolator interpolator = new LinearInterpolator();

    // post a Runnable to the handler
    handler.post(new Runnable() {
        @Override
        public void run() {
            // calculate how soon we need to redraw the marker
            long elapsed = SystemClock.uptimeMillis() - start;
            float t = interpolator.getInterpolation((float) elapsed / duration);
            double lng = t * intent.getFloatExtra(Constants.LONGITUDE, 0) + (1 - t) * startLatLng.longitude;
            double lat = t * intent.getFloatExtra(Constants.LATITUDE, 0) + (1 - t) * startLatLng.latitude;

            // set the driver's marker position
            driverMarker.setPosition(new LatLng(lat, lng));
            if (t < 1.0) {
                handler.postDelayed(this, 10);
            }
        }
    });
}

From source file:com.quarterfull.newsAndroid.NewsReaderListActivity.java

private void UpdateButtonLayoutWithHandler() {
    Handler refresh = new Handler(Looper.getMainLooper());
    refresh.post(new Runnable() {
        public void run() {
            UpdateButtonLayout();/* www  .  ja  va2  s . c  o m*/
        }
    });
}

From source file:com.quarterfull.newsAndroid.NewsReaderListActivity.java

@Subscribe
public void onEvent(SyncFinishedEvent event) {
    Handler refresh = new Handler(Looper.getMainLooper());
    refresh.post(new Runnable() {
        public void run() {
            UpdateButtonLayout();/*from  w  ww .j  a va  2s.  co m*/
            syncFinishedHandler();
        }
    });
}

From source file:com.sentaroh.android.Utilities.LogUtil.CommonLogFileListDialogFragment.java

private void reInitViewWidget() {
    if (DEBUG_ENABLE)
        Log.v(APPLICATION_TAG, "reInitViewWidget");
    if (!mTerminateRequired) {
        Handler hndl = new Handler();
        hndl.post(new Runnable() {
            @Override//from   w  ww .  j  a  v  a2s .  c o m
            public void run() {
                boolean scb = mLogFileManagementAdapter.isShowCheckBox();
                saveViewContents();
                initViewWidget();
                restoreViewContents();
                if (scb) {
                    mLogFileManagementAdapter.setShowCheckBox(true);
                    setContextButtonSelecteMode(mLogFileManagementAdapter);
                } else {
                    setContextButtonNormalMode(mLogFileManagementAdapter);
                }
            }
        });
    }
}

From source file:com.facebook.notifications.internal.activity.CardActivity.java

private void beginLoadingContent() {
    if (assetManager == null || contentManager == null) {
        Log.e(LOG_TAG, "Asset & content manager should be available!");
        return;// w ww .j  av a2s.c om
    }

    if (configurationPayload == null) {
        Log.e(LOG_TAG, "No card payload is available!");
        return;
    }

    ProgressBar loadingView = new ProgressBar(this);
    loadingView.setIndeterminate(true);

    int backgroundColor = ColorAssetHandler.fromRGBAHex(configurationPayload.optString("backdropColor"));

    FrameLayout loadingViewFrame = new FrameLayout(this);
    loadingViewFrame.setBackgroundColor(backgroundColor);

    LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    layoutParams.gravity = Gravity.CENTER;
    loadingViewFrame.addView(loadingView, layoutParams);

    setContentView(loadingViewFrame);

    final Handler handler = new Handler();
    if (configurationPayload == null) {
        return;
    }

    assetManager.cachePayload(configurationPayload, new AssetManager.CacheCompletionCallback() {
        @Override
        public void onCacheCompleted(@NonNull JSONObject payload) {
            final CardConfiguration configuration;
            try {
                configuration = new CardConfiguration(configurationPayload, assetManager, contentManager);
            } catch (JSONException ex) {
                Log.e(LOG_TAG, "Error while parsing JSON", ex);
                return;
            }

            handler.post(new Runnable() {
                @Override
                public void run() {
                    displayConfiguration(configuration);
                }
            });
        }
    });
}

From source file:com.shollmann.igcparser.ui.activity.FlightPreviewActivity.java

private void animateMarker() {
    final Handler handler = new Handler();
    final long start = SystemClock.uptimeMillis();
    duration = 300000;/*from   ww w.j a v a2 s . c  o m*/

    final Interpolator interpolator = new LinearInterpolator();

    handler.post(new Runnable() {
        int i = 0;

        @Override
        public void run() {
            long elapsed = SystemClock.uptimeMillis() - start;
            float t = interpolator.getInterpolation((float) elapsed / duration);
            if (i < listLatLngPoints.size()) {
                Double heading = SphericalUtil.computeHeading(markerGlider.getPosition(),
                        listLatLngPoints.get(i));
                markerGlider.setRotation(heading.floatValue());
                markerGlider.setPosition(listLatLngPoints.get(i));
            }
            i++;

            if (t < 1.0 && i < listLatLngPoints.size() && !isFinishReplay) {
                handler.postDelayed(this, replaySpeed);
            } else {
                finishReplay();
            }
        }
    });
}

From source file:de.stadtrallye.rallyesoft.model.chat.Chatroom.java

private void notifyPostChange(final PostChat post, final PostState state, final ChatEntry entry) {
    synchronized (listeners) {
        Handler handler;
        for (final IChatroomListener l : listeners) {
            handler = l.getCallbackHandler();
            if (handler == null) {
                l.onPostStateChange(post, state, entry);
            } else {
                handler.post(new Runnable() {
                    @Override/*  w w w  .j  ava 2  s  .  c  om*/
                    public void run() {
                        l.onPostStateChange(post, state, entry);
                    }
                });
            }
        }
    }
}