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.sentaroh.android.Utilities.Dialog.FileSelectDialogFragment.java

private void reInitViewWidget() {
    if (mDebugEnable)
        Log.v(APPLICATION_TAG, "reInitViewWidget");
    if (!mTerminateRequired) {
        Handler hndl = new Handler();
        hndl.post(new Runnable() {
            @Override// w  w w.  ja  v a 2  s  . com
            public void run() {
                mDialog.hide();
                saveViewContents();
                mDialog.getWindow().getCurrentFocus().invalidate();
                initViewWidget();
                restoreViewContents();
                CommonDialog.setDlgBoxSizeLimit(mDialog, true);
                mDialog.onContentChanged();
                mDialog.show();
            }
        });
    }
}

From source file:com.dmbstream.android.util.Util.java

public static void showPlayingNotification(final Context context, final DownloadServiceImpl downloadService,
        Handler handler, Track song) {

    // Use the same text for the ticker and the expanded notification
    String title = song.title;//  w  w  w .  ja  v a2  s  .  c  o  m
    String text = song.artist;

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

    RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.partial_notification);

    // set the text for the notifications
    contentView.setTextViewText(R.id.notification_title, title);
    contentView.setTextViewText(R.id.notification_artist, text);

    Pair<Integer, Integer> colors = getNotificationTextColors(context);
    if (colors.getFirst() != null) {
        contentView.setTextColor(R.id.notification_title, colors.getFirst());
    }
    if (colors.getSecond() != null) {
        contentView.setTextColor(R.id.notification_artist, colors.getSecond());
    }

    notification.contentView = contentView;

    // Send them to the main menu when if they click the notification
    // TODO: Send them to the concert, playlist, compilation details or chat page?
    Intent notificationIntent = new Intent(context, MainMenuActivity.class);
    notification.contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

    // Send the notification and put the service in the foreground.
    handler.post(new Runnable() {
        @Override
        public void run() {
            startForeground(downloadService, Constants.NOTIFICATION_ID_PLAYING, notification);
        }
    });

    // Update widget
    DmbstreamAppWidgetProvider.getInstance().notifyChange(context, downloadService, true);
}

From source file:net.gsantner.opoc.util.ShareUtil.java

/**
 * Share given text on a hastebin compatible server
 * (https://github.com/seejohnrun/haste-server)
 * Permission needed: Internet/*from  w  w  w  . java 2 s .  c  o  m*/
 * Pastes will be deleted after 30 days without access
 *
 * @param text            The text to paste
 * @param callback        Callback after paste try
 * @param serverOrNothing Supply one or no hastebin server. If empty, the default gets taken
 */
public void pasteOnHastebin(final String text, final Callback.a2<Boolean, String> callback,
        String... serverOrNothing) {
    final Handler handler = new Handler();
    final String server = (serverOrNothing != null && serverOrNothing.length > 0 && serverOrNothing[0] != null)
            ? serverOrNothing[0]
            : "https://hastebin.com";
    new Thread() {
        public void run() {
            // Returns a simple result, handleable without json parser {"key":"feediyujiq"}
            String ret = NetworkUtils.performCall(server + "/documents", NetworkUtils.POST, text);
            final String key = (ret.length() > 15) ? ret.split("\"")[3] : "";
            handler.post(() -> callback.callback(!key.isEmpty(), server + "/" + key));
        }
    }.start();
}

From source file:com.owncloud.android.ui.activity.FolderSyncActivity.java

/**
 * loads all media/synced folders, adds them to the recycler view adapter and shows the list.
 *
 * @param perFolderMediaItemLimit the amount of media items to be loaded/shown per media folder
 *///from www. j a  v a 2  s . c o m
private void load(final int perFolderMediaItemLimit) {
    if (mAdapter.getItemCount() > 0) {
        return;
    }
    setListShown(false);
    final Handler mHandler = new Handler();
    new Thread(new Runnable() {
        @Override
        public void run() {
            final List<MediaFolder> mediaFolders = MediaProvider.getMediaFolders(getContentResolver(),
                    perFolderMediaItemLimit);
            List<SyncedFolder> syncedFolderArrayList = mSyncedFolderProvider.getSyncedFolders();
            List<SyncedFolder> currentAccountSyncedFoldersList = new ArrayList<SyncedFolder>();
            Account currentAccount = AccountUtils.getCurrentOwnCloudAccount(FolderSyncActivity.this);
            for (SyncedFolder syncedFolder : syncedFolderArrayList) {
                if (syncedFolder.getAccount().equals(currentAccount.name)) {
                    currentAccountSyncedFoldersList.add(syncedFolder);
                }
            }

            syncFolderItems = sortSyncedFolderItems(
                    mergeFolderData(currentAccountSyncedFoldersList, mediaFolders));

            mHandler.post(new TimerTask() {
                @Override
                public void run() {
                    mAdapter.setSyncFolderItems(syncFolderItems);
                    setListShown(true);
                }
            });
        }
    }).start();
}

From source file:com.echopf.ECHOInstallation.java

/**
 * Does Get registration id from the GCM server in a background thread.
 * /*from w ww. j  av a2  s.c  om*/
 * @param sync if set TRUE, then the main (UI) thread is waited for complete the fetching in a background thread. 
 *              (a synchronous communication)
 * @param callback invoked after the getting is completed
 * @throws ECHOException 
 */
protected void doGetRegistrationId(final boolean sync, final InstallationCallback callback)
        throws ECHOException {
    // if(!checkPlayServices(ECHO.context)) return;

    // Get senderId from AndroidManifest.xml
    String senderId = null;
    try {
        ApplicationInfo appInfo = ECHO.context.getPackageManager()
                .getApplicationInfo(ECHO.context.getPackageName(), PackageManager.GET_META_DATA);
        senderId = appInfo.metaData.getString(GCM_SENDER_ID_KEY);
        senderId = (senderId.startsWith("id:")) ? senderId.substring(3) : null;
    } catch (NameNotFoundException ignored) {
        // skip
    }
    if (senderId == null)
        throw new RuntimeException("`" + GCM_SENDER_ID_KEY + "` is not specified in `AndroidManifest.xml`.");

    // Get ready a background thread
    final Handler handler = new Handler();
    final String fSenderId = senderId;

    ExecutorService executor = Executors.newSingleThreadExecutor();
    Callable<Object> communictor = new Callable<Object>() {

        @Override
        public Object call() throws ECHOException {
            ECHOException exception = null;

            // InstanceID instanceID = InstanceID.getInstance(ECHO.context);
            String token = null;

            // Get updated InstanceID token.
            token = FirebaseInstanceId.getInstance().getToken();
            // Log.d(TAG, "Refreshed token: " + refreshedToken);
            // TODO: Implement this method to send any registration to your app's servers.

            // token = instanceID.getToken(fSenderId, GoogleCloudMessaging.INSTANCE_ID_SCOPE);
            synchronized (lock) {
                deviceToken = token;
            }

            if (sync == false) {

                // Execute a callback method in the main (UI) thread.
                final ECHOException fException = exception;
                final String fToken = token;

                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        ECHOInstallation.this.deviceToken = fToken;
                        callback.done(fException);
                    }
                });

            } else {

                if (exception != null)
                    throw exception;

            }

            return null;
        }
    };

    Future<Object> future = executor.submit(communictor);

    if (sync) {
        try {
            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);
        }
    }
}

From source file:com.iride.ayride.HomePageActivity.java

private void animateMarkerTo(final Marker marker, final double lat, final double lng) {
    final Handler handler = new Handler();
    final long start = SystemClock.uptimeMillis();
    final long DURATION_MS = 1000;
    final Interpolator interpolator = new AccelerateDecelerateInterpolator();
    final LatLng startPosition = marker.getPosition();
    handler.post(new Runnable() {
        @Override//w ww  .j  av a2 s  . c  om
        public void run() {
            float elapsed = SystemClock.uptimeMillis() - start;
            float t = elapsed / DURATION_MS;
            float v = interpolator.getInterpolation(t);

            double currentLat = (lat - startPosition.latitude) * v + startPosition.latitude;
            double currentLng = (lng - startPosition.longitude) * v + startPosition.longitude;
            marker.setPosition(new LatLng(currentLat, currentLng));

            // if animation is not finished yet, repeat
            if (t < 1) {
                handler.postDelayed(this, 16);
            }
        }
    });
}

From source file:org.cryptsecure.Utility.java

/**
 * Show toast short async from non-UI thread.
 * /*from   w w w.  java 2 s .c om*/
 * @param context
 *            the context
 * @param toastText
 *            the toast text
 */
public static void showToastShortAsync(final Context context, final String toastText) {
    final Handler mUIHandler = new Handler(Looper.getMainLooper());
    mUIHandler.post(new Thread() {
        @Override
        public void run() {
            super.run();
            int duration = Toast.LENGTH_SHORT;
            Toast toast = Toast.makeText(context, toastText, duration);
            toast.show();
        }
    });
}

From source file:org.cryptsecure.Utility.java

/**
 * Show toast async from non-UI thread.//from w w w .  j a v a  2 s .c om
 * 
 * @param context
 *            the context
 * @param toastText
 *            the toast text
 */
public static void showToastAsync(final Context context, final String toastText) {
    final Handler mUIHandler = new Handler(Looper.getMainLooper());
    mUIHandler.post(new Thread() {
        @Override
        public void run() {
            super.run();
            int duration = Toast.LENGTH_LONG;
            Toast toast = Toast.makeText(context, toastText, duration);
            toast.show();
        }
    });
}

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

public static void LoadImage(final String url, ImageView image, final String displayname, final boolean rounded,
        boolean fromCache) {
    final WeakReference<ImageView> imageView = new WeakReference<ImageView>(image);
    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(imageView.get().getResources(), bitmap);
                roundedBitmap.setCircular(true);
                imageView.get().setImageDrawable(roundedBitmap);
            } else {
                imageView.get().setImageBitmap(bitmap);
            }/*from www . j  a v  a2s .  com*/
            imageView.get().setContentDescription(displayname);
            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 (imageView != null && imageView.get() != null) {
                        uiHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                if (imageView.get() != null) {
                                    if (rounded) {
                                        RoundedBitmapDrawable roundedBitmap = RoundedBitmapDrawableFactory
                                                .create(imageView.get().getResources(), response);
                                        roundedBitmap.setCircular(true);
                                        imageView.get().setImageDrawable(roundedBitmap);
                                    } else {
                                        imageView.get().setImageBitmap(response);
                                    }
                                    imageView.get().setContentDescription(displayname);
                                }

                            }

                        });

                    }
                }

                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:com.gmail.boiledorange73.ut.map.MapActivityBase.java

/**
 * Starts location services and timer to stop after specfied time.
 * /*from   w  w  w  . j a  va2 s .  c  om*/
 * @see http://d.hatena.ne.jp/orangesignal/20101223/1293079002
 */
private void startLocationService(boolean highaccuracy) {
    //
    this.stopLocationService();
    this.mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    if (this.mLocationManager == null) {
        // this device has no location service. DOES NOTHING.
        return;
    }

    // gets active location providers.
    // if requires high accuracy, creates filtered provider list.
    List<String> providerList = this.mLocationManager.getProviders(true);
    if (highaccuracy) {
        ArrayList<String> candidateList = new ArrayList<String>();
        if (providerList != null) {
            for (String providerName : providerList) {
                if (providerName != null) {
                    LocationProvider provider = this.mLocationManager.getProvider(providerName);
                    if (provider != null && provider.getAccuracy() == Criteria.ACCURACY_FINE) {
                        candidateList.add(providerName);
                    }
                }
            }
        }
        providerList = candidateList;
    }
    // checks whether at least one location provider is available.
    if (providerList == null || !(providerList.size() > 0)) {
        // Shows the dialog which let user to open system preference.
        AlertDialogHelper.showConfirmationDialog(this, Messages.getString("P_LOCATION_PROVIDER_ERROR"),
                Messages.getString("P_CONFIRM_OPEN_LOACTIONPROVIDER_SETTINGS"),
                android.R.drawable.ic_dialog_info, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(final DialogInterface dialog, final int which) {
                        try {
                            startActivity(new Intent("android.settings.LOCATION_SOURCE_SETTINGS"));
                        } catch (final ActivityNotFoundException e) {
                            // DOES NOTHING
                            e.printStackTrace();
                        }
                    }
                });
        this.stopLocationService();
        return;
    }
    // Starts timer. Checks whether timed out frequently,
    // and stops location services when specified time comes.
    final boolean onlyPassive = (providerList.size() == 1 && "passive".equals(providerList.get(0)));
    this.mLocationTimer = new Timer(true);
    this.mTimedOut = System.currentTimeMillis() + 30000L;
    final Handler handler = new Handler();
    this.mToast = Toast.makeText(this, Messages.getString("P_MYLOCATION_FINDING"), Toast.LENGTH_SHORT);
    this.mToast.show();
    this.mLocationTimer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            // Sends the procedure checks whether timed out.
            handler.post(new Runnable() {
                @Override
                public void run() {
                    long current = System.currentTimeMillis();
                    if (current >= MapActivityBase.this.mTimedOut) {
                        // timed out.
                        MapActivityBase.this.onLocationServiceTimedout(onlyPassive);
                    } else {
                        // NOT timed out. Shows the TOAST.
                        MapActivityBase.this.mToast.show();
                    }
                }
            });
        }
    }, 0L, 1000L);
    // starts
    this.mLocationListener = new LocationListener() {
        @Override
        public void onLocationChanged(final Location location) {
            // New location got. Sends it to JS.
            setLocation(location, true);
        }

        @Override
        public void onProviderDisabled(final String provider) {
            // DOES NOTHING.
        }

        @Override
        public void onProviderEnabled(final String provider) {
            // DOES NOTHING.
        }

        @Override
        public void onStatusChanged(final String provider, final int status, final Bundle extras) {
            // DOES NOTHING.
        }
    };
    for (String provider : providerList) {
        this.mLocationManager.requestLocationUpdates(provider, 0, 0, this.mLocationListener);
    }
}