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.cyrilmottier.android.polaris2demo.MarkerDemoActivity.java

@Override
public boolean onMarkerClick(final Marker marker) {
    // This causes the marker at Perth to bounce into position when it is clicked.
    if (marker.equals(mPerth)) {
        final Handler handler = new Handler();
        final long start = SystemClock.uptimeMillis();
        Projection proj = mMap.getProjection();
        Point startPoint = proj.toScreenLocation(PERTH);
        startPoint.offset(0, -100);//from   w  ww.j  a va  2  s  .  c  o  m
        final LatLng startLatLng = proj.fromScreenLocation(startPoint);
        final long duration = 1500;

        final Interpolator interpolator = new BounceInterpolator();

        handler.post(new Runnable() {
            @Override
            public void run() {
                long elapsed = SystemClock.uptimeMillis() - start;
                float t = interpolator.getInterpolation((float) elapsed / duration);
                double lng = t * PERTH.longitude + (1 - t) * startLatLng.longitude;
                double lat = t * PERTH.latitude + (1 - t) * startLatLng.latitude;
                marker.setPosition(new LatLng(lat, lng));

                if (t < 1.0) {
                    // Post again 16ms later.
                    handler.postDelayed(this, 16);
                }
            }
        });
    }
    // 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:org.hfoss.posit.android.sync.Communicator.java

/**
 * Sends the authentication response from server back to the caller main UI
 * thread through its handler.//from   w  w  w.java2s.  c  om
 * 
 * @param authKey
 *            the auth key obtained from the server
 * @param result
 *            The boolean holding authentication result
 * @param authToken
 *            The auth token returned from the server for this account.
 * @param handler
 *            The main UI thread's handler instance.
 * @param context
 *            The caller Activity's context.
 */
private static void sendAuthenticationResult(final String authKey, final Boolean result, final Handler handler,
        final Context context) {
    if (handler == null || context == null) {
        return;
    }
    handler.post(new Runnable() {
        public void run() {
            ((AuthenticatorActivity) context).onAuthenticationResult(result, authKey);
        }
    });
}

From source file:crackerjack.education.Indijisites.StartUp.java

@Override
public boolean onMarkerClick(final Marker marker) {
    // This method makes the marker bounce when you click on it. It's not really needed, but it's a neat feature.
    // Will expand this if offered more time.
    if (marker.equals(mBrisbane)) {
        final Handler handler = new Handler();
        final long start = SystemClock.uptimeMillis();
        Projection proj = mMap.getProjection();
        Point startPoint = proj.toScreenLocation(BRISBANE);
        startPoint.offset(0, -100);// ww  w . j  a v  a  2 s. co  m
        final LatLng startLatLng = proj.fromScreenLocation(startPoint);
        final long duration = 1500;

        final Interpolator interpolator = new BounceInterpolator();

        handler.post(new Runnable() {
            @Override
            public void run() {
                long elapsed = SystemClock.uptimeMillis() - start;
                float t = interpolator.getInterpolation((float) elapsed / duration);
                double lng = t * BRISBANE.longitude + (1 - t) * startLatLng.longitude; // This allows the marker to pinpoint if offscreen (I think =/)
                double lat = t * BRISBANE.latitude + (1 - t) * startLatLng.latitude;
                marker.setPosition(new LatLng(lat, lng));

                if (t < 1.0) {
                    // Post again 16ms later
                    handler.postDelayed(this, 16);
                }
            }
        });
    }
    //False is returned to indicate we have not consumed the event and that we wish
    //for the default behaviour to occur (move to marker location).
    return false;
}

From source file:com.pranavpandey.smallapp.view.PagerSlidingTabStrip.java

@Override
public void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);
    Handler handler = new Handler();
    handler.post(new Runnable() {

        @Override/*  w w w  .  jav a2  s .  c  o  m*/
        public void run() {
            notifyDataSetChanged();
            requestLayout();
        }
    });
}

From source file:de.stadtrallye.rallyesoft.model.Server.java

private void notifyAvailableGroups() {
    android.os.Handler handler;
    synchronized (listeners) {
        for (final IServer.IServerListener listener : listeners) {
            handler = listener.getCallbackHandler();
            if (handler != null) {
                handler.post(new Runnable() {
                    @Override// www.j av  a  2  s.co  m
                    public void run() {
                        listener.onAvailableGroupsChanged(groups);
                    }
                });
            } else {
                listener.onAvailableGroupsChanged(groups);
            }
        }
    }
}

From source file:de.stadtrallye.rallyesoft.model.Server.java

private void notifyConnectionFailed(final Exception e, final int status) {
    android.os.Handler handler;
    synchronized (listeners) {
        for (final IServer.IServerListener listener : listeners) {
            handler = listener.getCallbackHandler();
            if (handler != null) {
                handler.post(new Runnable() {
                    @Override// w  w  w  . j av  a2  s .  c om
                    public void run() {
                        listener.onConnectionFailed(e, status);
                    }
                });
            } else {
                listener.onConnectionFailed(e, status);
            }
        }
    }
}

From source file:de.stadtrallye.rallyesoft.model.Server.java

private void notifyLoginSuccessful() {
    android.os.Handler handler;
    synchronized (listeners) {
        for (final IServer.IServerListener listener : listeners) {
            handler = listener.getCallbackHandler();
            if (handler != null) {
                handler.post(new Runnable() {
                    @Override//w  ww .  ja va 2 s  . c o m
                    public void run() {
                        listener.onLoginSuccessful();
                    }
                });
            } else {
                listener.onLoginSuccessful();
            }
        }
    }
}

From source file:com.echopf.members.ECHOMemberQuery.java

/**
 * Does Login//from w  w  w  .j a va 2  s  . com
 * @param sync if set TRUE, then the main (UI) thread is waited for complete the logging-in in a background thread. 
 *              (a synchronous communication)
 * @param callback invoked after the logging-in is completed
 * @param instanceId the reference ID of the instance to which the logged-in member belong
 * @param login_id
 * @param password
 * @throws ECHOException
 */
protected static ECHOMemberObject doLogin(final boolean sync, final LoginCallback callback,
        final String instanceId, final String login_id, final String password) throws ECHOException {
    final Handler handler = new Handler();

    // Get ready a background thread
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Callable<ECHOMemberObject> communicator = new Callable<ECHOMemberObject>() {

        @Override
        public ECHOMemberObject call() throws ECHOException {

            ECHOException exception = null;
            ECHOMemberObject memberObj = null;

            try {
                JSONObject params = new JSONObject();
                params.put("login_id", login_id);
                params.put("password", password);
                JSONObject response = ECHOQuery.postRequest(instanceId + "/login", params);
                memberObj = new ECHOMemberObject(instanceId, response.optString("refid"), response);

                //
                ECHO.accessToken = response.optString("access_token");

            } catch (ECHOException e) {
                exception = e;
            } catch (Exception e) {
                exception = new ECHOException(e);
            }

            if (sync == false) {

                // Execute a callback method in the main (UI) thread.
                if (callback != null) {
                    final ECHOException fException = exception;
                    final ECHOMemberObject fMemberObj = memberObj;

                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            callback.done(fMemberObj, fException);
                        }
                    });
                }

                return null;

            } else {

                if (exception == null)
                    return memberObj;
                throw exception;
            }
        }
    };

    Future<ECHOMemberObject> future = executor.submit(communicator);

    if (sync) {
        try {
            return future.get();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt(); // ignore/reset
        } catch (ExecutionException e) {
            Throwable e2 = e.getCause();

            if (e2 instanceof ECHOException) {
                throw (ECHOException) e2;
            }

            throw new RuntimeException(e2);
        }
    }

    return null;
}

From source file:io.github.carlorodriguez.alarmon.AlarmClockService.java

private void handleStart(Intent intent) {
    if (intent != null && intent.hasExtra(COMMAND_EXTRA)) {
        Bundle extras = intent.getExtras();
        int command = extras.getInt(COMMAND_EXTRA, COMMAND_UNKNOWN);

        final Handler handler = new Handler();
        final Runnable maybeShutdown = new Runnable() {
            @Override//from   w  ww  . j  av  a  2 s . c  o  m
            public void run() {
                if (pendingAlarms.size() == 0) {
                    stopSelf();
                }
            }
        };

        switch (command) {
        case COMMAND_NOTIFICATION_REFRESH:
            refreshNotification();
            handler.post(maybeShutdown);
            break;
        case COMMAND_DEVICE_BOOT:
            fixPersistentSettings();
            handler.post(maybeShutdown);
            break;
        case COMMAND_TIMEZONE_CHANGE:
            if (AppSettings.isDebugMode(getApplicationContext())) {
                Toast.makeText(getApplicationContext(), "TIMEZONE CHANGE, RESCHEDULING...", Toast.LENGTH_SHORT)
                        .show();
            }
            for (long alarmId : pendingAlarms.pendingAlarms()) {
                scheduleAlarm(alarmId);
                if (AppSettings.isDebugMode(getApplicationContext())) {
                    Toast.makeText(getApplicationContext(), "ALARM " + alarmId, Toast.LENGTH_SHORT).show();
                }
            }
            handler.post(maybeShutdown);
            break;
        default:
            throw new IllegalArgumentException("Unknown service command.");
        }
    }
}

From source file:com.mikhaellopez.saveinsta.activity.MainActivity.java

public void onEventMainThread(final EventInstaPictureLoad eventInstaPictureLoad) {
    if (eventInstaPictureLoad != null && eventInstaPictureLoad.isLoadWell()) {
        // Save userName and id image
        mUserName = eventInstaPictureLoad.getUserName();
        mIdInstaContent = eventInstaPictureLoad.getIdContent();

        // Load User Name to View
        mTextUserName.setText(eventInstaPictureLoad.getUserFullName());

        // If is video, Save URL
        mVideoToDownload.setVisibility(View.GONE);
        if (eventInstaPictureLoad.isVideo()) {
            mIsVideo = true;/*from www .  j a v  a  2  s .c o m*/
            mUrlVideo = eventInstaPictureLoad.getUrlVideo();
            mImageActionPlay.setVisibility(View.VISIBLE);
        } else {
            mIsVideo = false;
            mImageActionPlay.setVisibility(View.GONE);
        }

        final Handler handler = new Handler();
        new Thread(new Runnable() {
            @Override
            public void run() {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        // Load Image to View
                        Picasso.with(MainActivity.this).load(eventInstaPictureLoad.getUrlImage())
                                .into(mImageToDownload, new Callback() {
                                    @Override
                                    public void onSuccess() {
                                        EventBus.getDefault().post(new EventChangeDominantColor());

                                        // Show Result
                                        mProgressBar.setVisibility(View.GONE);
                                        mCardView.setVisibility(View.VISIBLE);
                                    }

                                    @Override
                                    public void onError() {
                                    }
                                });

                        // Load Profil Icon to View
                        Picasso.with(MainActivity.this).load(eventInstaPictureLoad.getUrlIconProfil())
                                .into(mIconProfil);
                    }
                });
            }
        }).start();
    } else {
        initView(null);
        // Show erreur
        Snackbar.make(mCoordinatorLayout, R.string.snackbar_load_photo_failed, Snackbar.LENGTH_SHORT).show();
    }
}