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.syncedsynapse.kore2.jsonrpc.HostConnection.java

private <T> void handleTcpResponse(ObjectNode jsonResponse) {

    if (!jsonResponse.has(ApiMethod.ID_NODE)) {
        // It's a notification, notify observers
        String notificationName = jsonResponse.get(ApiNotification.METHOD_NODE).asText();
        ObjectNode params = (ObjectNode) jsonResponse.get(ApiNotification.PARAMS_NODE);

        if (notificationName.equals(Player.OnPause.NOTIFICATION_NAME)) {
            final Player.OnPause apiNotification = new Player.OnPause(params);
            for (final PlayerNotificationsObserver observer : playerNotificationsObservers.keySet()) {
                Handler handler = playerNotificationsObservers.get(observer);
                handler.post(new Runnable() {
                    @Override/*from   w w  w .jav  a  2s  .  c  o  m*/
                    public void run() {
                        observer.onPause(apiNotification);
                    }
                });
            }
        } else if (notificationName.equals(Player.OnPlay.NOTIFICATION_NAME)) {
            final Player.OnPlay apiNotification = new Player.OnPlay(params);
            for (final PlayerNotificationsObserver observer : playerNotificationsObservers.keySet()) {
                Handler handler = playerNotificationsObservers.get(observer);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        observer.onPlay(apiNotification);
                    }
                });
            }
        } else if (notificationName.equals(Player.OnSeek.NOTIFICATION_NAME)) {
            final Player.OnSeek apiNotification = new Player.OnSeek(params);
            for (final PlayerNotificationsObserver observer : playerNotificationsObservers.keySet()) {
                Handler handler = playerNotificationsObservers.get(observer);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        observer.onSeek(apiNotification);
                    }
                });
            }
        } else if (notificationName.equals(Player.OnSpeedChanged.NOTIFICATION_NAME)) {
            final Player.OnSpeedChanged apiNotification = new Player.OnSpeedChanged(params);
            for (final PlayerNotificationsObserver observer : playerNotificationsObservers.keySet()) {
                Handler handler = playerNotificationsObservers.get(observer);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        observer.onSpeedChanged(apiNotification);
                    }
                });
            }
        } else if (notificationName.equals(Player.OnStop.NOTIFICATION_NAME)) {
            final Player.OnStop apiNotification = new Player.OnStop(params);
            for (final PlayerNotificationsObserver observer : playerNotificationsObservers.keySet()) {
                Handler handler = playerNotificationsObservers.get(observer);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        observer.onStop(apiNotification);
                    }
                });
            }
        } else if (notificationName.equals(System.OnQuit.NOTIFICATION_NAME)) {
            final System.OnQuit apiNotification = new System.OnQuit(params);
            for (final SystemNotificationsObserver observer : systemNotificationsObservers.keySet()) {
                Handler handler = systemNotificationsObservers.get(observer);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        observer.onQuit(apiNotification);
                    }
                });
            }
        } else if (notificationName.equals(System.OnRestart.NOTIFICATION_NAME)) {
            final System.OnRestart apiNotification = new System.OnRestart(params);
            for (final SystemNotificationsObserver observer : systemNotificationsObservers.keySet()) {
                Handler handler = systemNotificationsObservers.get(observer);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        observer.onRestart(apiNotification);
                    }
                });
            }
        } else if (notificationName.equals(System.OnSleep.NOTIFICATION_NAME)) {
            final System.OnSleep apiNotification = new System.OnSleep(params);
            for (final SystemNotificationsObserver observer : systemNotificationsObservers.keySet()) {
                Handler handler = systemNotificationsObservers.get(observer);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        observer.onSleep(apiNotification);
                    }
                });
            }
        } else if (notificationName.equals(Input.OnInputRequested.NOTIFICATION_NAME)) {
            final Input.OnInputRequested apiNotification = new Input.OnInputRequested(params);
            for (final InputNotificationsObserver observer : inputNotificationsObservers.keySet()) {
                Handler handler = inputNotificationsObservers.get(observer);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        observer.onInputRequested(apiNotification);
                    }
                });
            }
        }

        LogUtils.LOGD(TAG, "Got a notification: " + jsonResponse.get("method").textValue());
    } else {
        String methodId = jsonResponse.get(ApiMethod.ID_NODE).asText();

        if (jsonResponse.has(ApiMethod.ERROR_NODE)) {
            // Error response
            callErrorCallback(methodId, new ApiException(ApiException.API_ERROR, jsonResponse));
        } else {
            // Sucess response
            final MethodCallInfo<?> methodCallInfo = clientCallbacks.get(methodId);
            //            LogUtils.LOGD(TAG, "Sending response to method: " + methodCallInfo.method.getMethodName());

            if (methodCallInfo != null) {
                try {
                    final T result = (T) methodCallInfo.method.resultFromJson(jsonResponse);
                    final ApiCallback<T> callback = (ApiCallback<T>) methodCallInfo.callback;

                    if ((methodCallInfo.handler != null) && (callback != null)) {
                        methodCallInfo.handler.post(new Runnable() {
                            @Override
                            public void run() {
                                callback.onSucess(result);
                            }
                        });
                    }

                    // We've replied, remove the client from the list
                    synchronized (clientCallbacks) {
                        clientCallbacks.remove(methodId);
                    }
                } catch (ApiException e) {
                    callErrorCallback(methodId, e);
                }
            }
        }
    }
}

From source file:com.sentaroh.android.TaskAutomation.Config.ProfileMaintenanceTimeProfile.java

public 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 a2 s. co  m*/
            public void run() {
                SavedViewContents sv = null;
                if (!mOpType.equals("BROWSE"))
                    sv = saveViewContents();
                initViewWidget();
                if (!mOpType.equals("BROWSE"))
                    restoreViewContents(sv);
                CommonDialog.setDlgBoxSizeLimit(mDialog, true);
            }
        });
    }
}

From source file:de.j4velin.mapsmeasure.Map.java

/**
 * Get the formatted string for the valueTextView.
 * <p/>//w w  w .  j a v  a2 s .  c o m
 * Depending on whether 'showArea' is set, the returned string shows the
 * distance of the trace or the area between them. If 'showArea' is set,
 * this call might be expensive as the area is computed here and not cached.
 *
 * @return the formatted text for the valueTextView
 */
private String getFormattedString() {
    if (type == MeasureType.DISTANCE) {
        if (metric) {
            if (distance > 1000)
                return formatter_two_dec.format(distance / 1000) + " km";
            else
                return formatter_two_dec.format(Math.max(0, distance)) + " m";
        } else {
            if (distance > 1609)
                return formatter_two_dec.format(distance / 1609.344f) + " mi";
            else
                return formatter_two_dec.format(Math.max(0, distance / 0.3048f)) + " ft";
        }
    } else if (type == MeasureType.AREA) {
        double area;
        if (areaOverlay != null)
            areaOverlay.remove();
        if (trace.size() >= 3) {
            area = SphericalUtil.computeArea(trace);
            areaOverlay = mMap
                    .addPolygon(new PolygonOptions().addAll(trace).strokeWidth(0).fillColor(COLOR_POINT));
        } else {
            area = 0;
        }
        if (metric) {
            if (area > 1000000)
                return formatter_two_dec.format(Math.max(0, area / 1000000d)) + " km";
            else
                return formatter_no_dec.format(Math.max(0, area)) + " m";
        } else {
            if (area >= 2589989)
                return formatter_two_dec.format(Math.max(0, area / 2589988.110336d)) + " mi";
            else
                return formatter_no_dec.format(Math.max(0, area / 0.09290304d)) + " ft";
        }
    } else if (type == MeasureType.ELEVATION) {
        if (altitude == null) {
            final Handler h = new Handler();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    altitude = Util.getElevation(trace);
                    h.post(new Runnable() {
                        @Override
                        public void run() {
                            if (isFinishing())
                                return;
                            if (altitude == null) {
                                Dialogs.getElevationErrorDialog(Map.this).show();
                                changeType(MeasureType.DISTANCE);
                            } else {
                                updateValueText();
                            }
                        }
                    });
                }
            }).start();
            return "Loading...";
        } else {
            String re = metric
                    ? formatter_two_dec.format(altitude.first) + " m\u2B06, "
                            + formatter_two_dec.format(-1 * altitude.second) + " m\u2B07"
                    : formatter_two_dec.format(altitude.first / 0.3048f) + " ft\u2B06"
                            + formatter_two_dec.format(-1 * altitude.second / 0.3048f) + " ft\u2B07";
            if (!trace.isEmpty()) {
                try {
                    float lastPoint = Util.getAltitude(trace.peek(), null, null);
                    if (lastPoint > -Float.MAX_VALUE) {
                        re += "\n" + (metric ? formatter_two_dec.format(lastPoint) + " m"
                                : formatter_two_dec.format(lastPoint / 0.3048f) + " ft");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            altitude = null;
            return re;
        }
    } else {
        return "not yet supported";
    }
}

From source file:com.nuvolect.securesuite.data.SqlSyncTest.java

public JSONObject pong_test(final Context ctx) {

    managePayloadSize();/*from   www  . ja  va  2  s  .  co  m*/

    /**
     * Build the payload and generate MD5
     */
    Map<String, String> parameters = makeParameters();
    parameters.put(CConst.CMD, SyncRest.CMD.pong_test.toString());
    parameters.put(CConst.COUNTER, String.valueOf(++pong_counter));

    String url = WebUtil.getCompanionServerUrl(CConst.SYNC);
    startTime = System.currentTimeMillis();

    Comm.sendPost(ctx, url, parameters, new Comm.CommPostCallbacks() {
        @Override
        public void success(String response) {

            LogUtil.log(LogUtil.LogType.SQL_SYNC_TEST, SyncRest.CMD.pong_test + " response: " + response);

            if (WebUtil.responseMatch(response, CConst.RESPONSE_CODE_SUCCESS_100)) {

                if (m_pingPongCallbacks != null) {

                    Handler handler = new Handler(Looper.getMainLooper());
                    Runnable r = new Runnable() {
                        @Override
                        public void run() {

                            m_pingPongCallbacks.progressUpdate(m_pingPongCallbacksAct, ping_counter,
                                    pong_counter, payloadSize);

                            if (!m_continueTest)
                                m_pingPongCallbacks.cancelDialog(m_pingPongCallbacksAct);
                        }
                    };
                    handler.post(r);
                }
                if (m_continueTest)
                    WorkerCommand.quePingTest(ctx);
            }
        }

        @Override
        public void fail(String error) {
            LogUtil.log(LogUtil.LogType.SQL_SYNC_TEST, SyncRest.CMD.pong_test + " error: " + error);
        }
    });
    if (m_continueTest)
        return WebUtil.response(CConst.RESPONSE_CODE_SUCCESS_100);
    else
        return WebUtil.response(CConst.RESPONSE_CODE_USER_CANCEL_102);
}

From source file:github.madmarty.madsonic.util.Util.java

private static void updateCustomNotification(Context context, final DownloadServiceImpl downloadService,
        Handler handler, MusicDirectory.Entry song, boolean playing) {

    if (song == null) {
        hidePlayingNotification(context, downloadService, handler);

        //        } else if (!isNotificationHiddenByUser(context)) {
        final Notification notification = createCustomNotification(context, song, playing);

        // Send the notification and put the service in the foreground.
        handler.post(new Runnable() {
            @Override/*from  w w  w  . j  a  v a  2  s.  c o m*/
            public void run() {
                downloadService.startForeground(Constants.NOTIFICATION_ID_PLAYING, notification);
            }
        });
    }
}

From source file:com.nuvolect.securesuite.data.SqlSyncTest.java

/**
 * Test the network performance between this device and a companion device.
 * CONCEPT:// w w  w. j  a  v a 2 s  .  co m
 * A package is constructed of minimal size and sent to the companion device.
 * The companion tests the package for integrity and if successful, creates a larger package and sends it back.
 * The process is continued until communications fail.
 *
 * TODO complete ping pong test.  Show running data rate, success and failure.
 *
 * @param ctx
 * @return
 */
public JSONObject ping_test(final Context ctx) {

    managePayloadSize();

    /**
     * Build the payload and generate MD5
     */
    Map<String, String> params = makeParameters();
    params.put(CConst.CMD, SyncRest.CMD.ping_test.toString());
    params.put(CConst.COUNTER, String.valueOf(++ping_counter));

    String url = WebUtil.getCompanionServerUrl(CConst.SYNC);
    startTime = System.currentTimeMillis();

    Comm.sendPost(ctx, url, params, new Comm.CommPostCallbacks() {
        @Override
        public void success(String response) {

            LogUtil.log(LogUtil.LogType.SQL_SYNC_TEST, SyncRest.CMD.ping_test + " response: " + response);

            if (WebUtil.responseMatch(response, CConst.RESPONSE_CODE_SUCCESS_100)) {

                if (m_pingPongCallbacks != null) {

                    Handler handler = new Handler(Looper.getMainLooper());
                    Runnable r = new Runnable() {
                        @Override
                        public void run() {

                            m_pingPongCallbacks.progressUpdate(m_pingPongCallbacksAct, ping_counter,
                                    pong_counter, payloadSize);

                            if (!m_continueTest)
                                m_pingPongCallbacks.cancelDialog(m_pingPongCallbacksAct);
                        }
                    };
                    handler.post(r);
                }
                /**
                 * To alternate volleys, pong is kicked off by the response sender
                 * versus the machine receiving the response
                 *
                 * if( m_continueTest) WorkerCommand.quePongTest(ctx);
                 */
            }
        }

        @Override
        public void fail(String error) {

            LogUtil.log(LogUtil.LogType.SQL_SYNC_TEST, SyncRest.CMD.ping_test + " error: " + error);
        }
    });
    if (m_continueTest)
        return WebUtil.response(CConst.RESPONSE_CODE_SUCCESS_100);
    else
        return WebUtil.response(CConst.RESPONSE_CODE_USER_CANCEL_102);
}

From source file:com.geniatech.client_phone.wifi.WifiStatusTest.java

private final void updatePingState() {
    final Handler handler = new Handler();
    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);
        }/* w  w  w.j a  va2  s . co  m*/
    };
    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:com.sveder.cardboardpassthrough.MainActivity.java

private void callMessageTask() {
    final Handler handler = new Handler();
    Timer timer = new Timer();
    TimerTask doAsynchronousTask = new TimerTask() {
        @Override/*from   w w  w .  ja  va2  s .co  m*/
        public void run() {
            handler.post(new Runnable() {
                public void run() {
                    try {
                        MessageTask getMessageTask = new MessageTask(MainActivity.this);
                        getMessageTask.setMessageLoading(null);
                        getMessageTask.execute(TASKS_URL);
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                    }
                }
            });
        }
    };
    timer.schedule(doAsynchronousTask, 0, 5000); //execute in every 50000 ms

}

From source file:com.twitter4rk.TwitterAuthFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    mTwitterWebView = new WebView(getActivity());
    final Bundle args = getArguments();
    if (args == null) {
        // This wont be case because startTwitterAuth() handles args for
        // fragment
        throw new IllegalArgumentException(
                "No arguments passed to fragment, Please use startTwitterAuth(...) method for showing this fragment");
    }/*from  ww w. j a v  a  2  s .  c  o  m*/
    // Get builder from args
    mBuilder = args.getParcelable(BUILDER_KEY);
    // Hide action bar
    if (mBuilder.hideActionBar)
        mBuilder.activity.getActionBar().hide();
    // Init progress dialog
    mProgressDialog = new ProgressDialog(mBuilder.activity);
    mProgressDialog.setMessage(mBuilder.progressText == null ? "Loading ..." : mBuilder.progressText);
    if (mBuilder.isProgressEnabled)
        mProgressDialog.show();

    // Init ConfigurationBuilder twitter4j
    final ConfigurationBuilder cb = new ConfigurationBuilder();
    if (mBuilder.isDebugEnabled)
        cb.setDebugEnabled(true);
    cb.setOAuthConsumerKey(mBuilder.consumerKey);
    cb.setOAuthConsumerSecret(mBuilder.consumerSecret);

    // Web view client to handler url loading
    mTwitterWebView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // Get url first
            final Uri uri = Uri.parse(url);
            // Check if we need to see for callback URL
            if (mBuilder.callbackUrl != null && url.contains(mBuilder.callbackUrl)) {
                // Get req info
                String oauthToken = uri.getQueryParameter("oauth_token");
                String oauthVerifier = uri.getQueryParameter("oauth_verifier");
                if (mListener != null)
                    mListener.onSuccess(oauthToken, oauthVerifier);
                if (mBuilder.isActionBarVisible && mBuilder.hideActionBar && getActivity() != null)
                    getActivity().getActionBar().show();
                mIsAuthenticated = true;
                removeMe();
                return true;
                // If no callback URL then check for info directly
            } else if (uri.getQueryParameter("oauth_token") != null
                    && uri.getQueryParameter("oauth_verifier") != null) {
                // Get req info
                String oauthToken = uri.getQueryParameter("oauth_token");
                String oauthVerifier = uri.getQueryParameter("oauth_verifier");
                if (mListener != null)
                    mListener.onSuccess(oauthToken, oauthVerifier);
                if (mBuilder.isActionBarVisible && mBuilder.hideActionBar && getActivity() != null)
                    getActivity().getActionBar().show();
                mIsAuthenticated = true;
                removeMe();
                return true;
                // If nothing then its failure
            } else {
                // Notify user
                if (mListener != null)
                    mListener.onFailure(
                            new Exception("Couldn't find the callback URL or oath parameters in response"));
                if (mBuilder.isActionBarVisible && mBuilder.hideActionBar && getActivity() != null)
                    getActivity().getActionBar().show();
                removeMe();
                return false;
            }
        }
    });
    // Web Crome client to handler progress dialog visibility
    mTwitterWebView.setWebChromeClient(new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
                if (mProgressDialog.isShowing())
                    mProgressDialog.dismiss();
            }
        }
    });
    final Handler handler = new Handler();
    new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                final TwitterFactory twitterFactory = new TwitterFactory(cb.build());
                final Twitter twitter = twitterFactory.getInstance();
                RequestToken requestToken = null;
                if (mBuilder.callbackUrl == null)
                    requestToken = twitter.getOAuthRequestToken();
                else
                    requestToken = twitter.getOAuthRequestToken(mBuilder.callbackUrl);
                final RequestToken finalRequestToken = requestToken;
                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        final String url = finalRequestToken.getAuthorizationURL();
                        mTwitterWebView.loadUrl(url);
                    }
                });
            } catch (TwitterException e) {
                e.printStackTrace();
            }
        }
    }).start();

    return mTwitterWebView;
}

From source file:com.androzic.location.LocationService.java

private void updateLocation() {
    final Location location = lastKnownLocation;
    final boolean continous = isContinous;
    final boolean geoid = !Float.isNaN(nmeaGeoidHeight);
    final float smoothspeed = smoothSpeed;
    final float avgspeed = avgSpeed;

    final Handler handler = new Handler();

    if (trackingEnabled) {
        handler.post(new Runnable() {
            @Override/*from w w  w  .j av  a  2s  .c o  m*/
            public void run() {
                writeTrack(location, continous, geoid, smoothspeed, avgspeed);
            }
        });
    }
    for (final ILocationListener callback : locationCallbacks) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                callback.onLocationChanged(location, continous, geoid, smoothspeed, avgspeed);
            }
        });
    }
    final int n = locationRemoteCallbacks.beginBroadcast();
    for (int i = 0; i < n; i++) {
        final ILocationCallback callback = locationRemoteCallbacks.getBroadcastItem(i);
        try {
            callback.onLocationChanged(location, continous, geoid, smoothspeed, avgspeed);
        } catch (RemoteException e) {
            Log.e(TAG, "Location broadcast error", e);
        }
    }
    locationRemoteCallbacks.finishBroadcast();
    Log.d(TAG, "Location dispatched: " + (locationCallbacks.size() + n));
}