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:name.gudong.translate.listener.ListenClipboardService.java

@Override
public void showTipToast(String msg) {
    Handler h = new Handler(getApplicationContext().getMainLooper());
    h.post(new Runnable() {
        @Override/*from  w w w  .  j a  v  a 2 s  .c o m*/
        public void run() {
            Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
        }
    });
}

From source file:com.lurencun.cfuture09.androidkit.http.Http.java

/**
 * //  w  w w  . j  av  a2s  . c o  m
 *
 * @param url
 *            ?
 * @param savePath
 *            ??
 * @param overwrite
 *            ?
 * @param listener
 *            ??
 */
public static void downloadAsync(final String url, final File savePath, final boolean overwrite,
        final HttpSimpleListener listener) {
    final Handler handler = HandlerFactory.newBackgroundHandler(idGenerator.next() + "");
    final Runnable task = new Runnable() {

        @Override
        public void run() {
            try {
                download(url, savePath, overwrite);
                listener.onFinish(url);
            } catch (final IOException e) {
                listener.onFailed(e.getMessage());
                log.w(e.getMessage(), e);
            }
            handler.removeCallbacks(this);
        }
    };
    handler.post(task);
}

From source file:com.f2prateek.dfg.core.GenerateMultipleFramesService.java

public void notifyFinished() {
    Handler handler = new Handler(Looper.getMainLooper());
    handler.post(new Runnable() {
        @Override//from  w w w.  java 2  s. com
        public void run() {
            bus.post(new Events.MultipleImagesProcessed(device, processedImageUris));
        }
    });

    if (processedImageUris.size() == 0) {
        return;
    }

    String text = resources.getString(R.string.multiple_screenshots_saved, processedImageUris.size(),
            device.name());

    Intent viewImagesIntent = new Intent(Intent.ACTION_VIEW);
    viewImagesIntent.setData(processedImageUris.get(0));
    viewImagesIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    notificationBuilder.setContentTitle(resources.getString(R.string.screenshot_saved_title))
            .setContentText(text).setContentIntent(PendingIntent.getActivity(this, 0, viewImagesIntent, 0))
            .setProgress(0, 0, false);
    notificationManager.notify(DFG_NOTIFICATION_ID, notificationBuilder.build());
}

From source file:com.packpublishing.asynchronousandroid.chapter5.Sha1HashBroadCastUnhService.java

private void broadcastResult(final String text, final String digest) {

    Looper mainLooper = Looper.getMainLooper();
    Handler handler = new Handler(mainLooper);
    handler.post(new Runnable() {
        @Override//w  w w.  ja  v a  2  s . c  om
        public void run() {
            Intent intent = new Intent(DIGEST_BROADCAST);
            intent.putExtra(RESULT, digest);
            LocalBroadcastManager.getInstance(Sha1HashBroadCastUnhService.this).sendBroadcastSync(intent);
            boolean handled = intent.getBooleanExtra(HANDLED, false);
            if (!handled) {
                notifyUser(text, digest);
            }
        }
    });

}

From source file:com.f2prateek.dfg.core.GenerateFrameService.java

@Override
public void doneImage(final Uri imageUri) {
    Handler handler = new Handler(Looper.getMainLooper());
    handler.post(new Runnable() {
        @Override//from www .j  a  va  2 s. c  om
        public void run() {
            bus.post(new Events.SingleImageProcessed(device, imageUri));
        }
    });

    // Create the intent to let the user share the image
    Intent sharingIntent = new Intent(Intent.ACTION_SEND);
    sharingIntent.setType("image/png");
    sharingIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
    Intent chooserIntent = Intent.createChooser(sharingIntent, null);
    chooserIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
    notificationBuilder.addAction(R.drawable.ic_action_share, getResources().getString(R.string.share),
            PendingIntent.getActivity(this, 0, chooserIntent, PendingIntent.FLAG_CANCEL_CURRENT));

    // Create the intent to let the user rate the app
    Intent rateIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(AppConstants.MARKET_URL));
    notificationBuilder.addAction(R.drawable.ic_action_rate, getResources().getString(R.string.rate),
            PendingIntent.getActivity(this, 0, rateIntent, PendingIntent.FLAG_CANCEL_CURRENT));

    // Create the intent to show the screenshot in gallery
    Intent launchIntent = new Intent(Intent.ACTION_VIEW);
    launchIntent.setDataAndType(imageUri, "image/png");
    launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    notificationBuilder.setContentTitle(resources.getString(R.string.screenshot_saved_title))
            .setContentText(resources.getString(R.string.single_screenshot_saved, device.name()))
            .setContentIntent(PendingIntent.getActivity(this, 0, launchIntent, 0))
            .setWhen(System.currentTimeMillis()).setProgress(0, 0, false).setAutoCancel(true);

    notificationManager.notify(DFG_NOTIFICATION_ID, notificationBuilder.build());
}

From source file:org.sufficientlysecure.keychain.service.ServiceProgressHandler.java

public void showProgressDialog(String progressDialogMessage, int progressDialogStyle, boolean cancelable) {

    final ProgressDialogFragment frag = ProgressDialogFragment.newInstance(progressDialogMessage,
            progressDialogStyle, cancelable);

    // TODO: This is a hack!, see
    // http://stackoverflow.com/questions/10114324/show-dialogfragment-from-onactivityresult
    final FragmentManager manager = mActivity.getSupportFragmentManager();
    Handler handler = new Handler();
    handler.post(new Runnable() {
        public void run() {
            frag.show(manager, TAG_PROGRESS_DIALOG);
        }//from  ww  w.  j  a  v a  2s .  co  m
    });

}

From source file:io.v.syncslides.DeckChooserFragment.java

/**
 * Creates a toast in the main looper.  Useful since lots of this class runs in a
 * background thread./*from w  w w.  j av a  2 s  .  c o  m*/
 */
private void toast(final String msg) {
    Handler handler = new Handler(Looper.getMainLooper());
    handler.post(() -> Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show());
}

From source file:london.vyne.pos.GcmIntentService.java

private void sendNotification(String msg) {
    Log.d(TAG, "Message Received");
    Log.d(TAG, msg);/*from  ww w.j  av a  2 s .co  m*/
    NotificationManager notificationManager = (NotificationManager) this
            .getSystemService(Context.NOTIFICATION_SERVICE);

    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher).setContentTitle("Vyne Notification")
            .setStyle(new NotificationCompat.BigTextStyle().bigText(msg)).setContentText(msg);

    builder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
    builder.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });

    builder.setContentIntent(contentIntent);
    notificationManager.notify(NOTIFICATION_ID, builder.build());

    Handler h = new Handler(Looper.getMainLooper());

    final String message = msg;

    h.post(new Runnable() {

        public void run() {
            Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
        }
    });

}

From source file:com.sspai.dkjt.service.GenerateFrameService.java

@Override
public void doneImage(final Uri imageUri) {
    Handler handler = new Handler(Looper.getMainLooper());
    handler.post(new Runnable() {
        @Override//  ww  w  .  ja va2  s.  c o  m
        public void run() {
            bus.post(new Events.SingleImageProcessed(device, imageUri));
        }
    });

    // Create the intent to let the user share the image
    Intent sharingIntent = new Intent(Intent.ACTION_SEND);
    sharingIntent.setType("image/png");
    sharingIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
    Intent chooserIntent = Intent.createChooser(sharingIntent, null);
    chooserIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
    notificationBuilder.addAction(R.drawable.ic_action_share, getResources().getString(R.string.share),
            PendingIntent.getActivity(this, 0, chooserIntent, PendingIntent.FLAG_CANCEL_CURRENT));

    // Create the intent to let the user rate the app
    Intent rateIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(ConfigString.MARKET_URL));
    notificationBuilder.addAction(R.drawable.ic_action_rate, getResources().getString(R.string.rate),
            PendingIntent.getActivity(this, 0, rateIntent, PendingIntent.FLAG_CANCEL_CURRENT));

    // Create the intent to show the screenshot in gallery
    Intent launchIntent = new Intent(Intent.ACTION_VIEW);
    launchIntent.setDataAndType(imageUri, "image/png");
    launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    notificationBuilder.setContentTitle(resources.getString(R.string.screenshot_saved_title))
            .setContentText(resources.getString(R.string.single_screenshot_saved, device.name()))
            .setContentIntent(PendingIntent.getActivity(this, 0, launchIntent, 0))
            .setWhen(System.currentTimeMillis()).setProgress(0, 0, false).setAutoCancel(true);

    notificationManager.notify(DFG_NOTIFICATION_ID, notificationBuilder.build());
}

From source file:com.dngames.mobilewebcam.PhotoSettings.java

public static void GETSettings(final Context context) {
    // check for new settings when done
    final SharedPreferences prefs = context.getSharedPreferences(MobileWebCam.SHARED_PREFS_NAME, 0);
    final String settingsurl = prefs.getString("remote_config_url", "");
    final int settingsfreq = Math.max(1, PhotoSettings.getEditInt(context, prefs, "remote_config_every", 1));
    final String login = prefs.getString("remote_config_login", "");
    final String password = prefs.getString("remote_config_password", "");
    final boolean noToasts = prefs.getBoolean("no_messages", false);
    if (settingsurl.length() > 0 && gLastGETSettingsPictureCnt < MobileWebCam.gPictureCounter
            && (MobileWebCam.gPictureCounter % settingsfreq) == 0) {
        gLastGETSettingsPictureCnt = MobileWebCam.gPictureCounter;

        Handler h = new Handler(context.getMainLooper());
        h.post(new Runnable() {
            @Override//from   w  w  w. j  av a2  s . c om
            public void run() {
                new AsyncTask<String, Void, String>() {
                    @Override
                    protected String doInBackground(String... params) {
                        try {
                            DefaultHttpClient httpclient = new DefaultHttpClient();
                            if (login.length() > 0) {
                                try {
                                    ((AbstractHttpClient) httpclient).getCredentialsProvider().setCredentials(
                                            new AuthScope(null, -1),
                                            new UsernamePasswordCredentials(login, password));
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    if (e.getMessage() != null)
                                        MobileWebCam.LogE("http login " + e.getMessage());
                                    else
                                        MobileWebCam.LogE("http: unable to log in");

                                    return null;
                                }
                            }
                            HttpGet get = new HttpGet(settingsurl);
                            HttpResponse response = httpclient.execute(get);
                            HttpEntity ht = response.getEntity();
                            BufferedHttpEntity buf = new BufferedHttpEntity(ht);
                            InputStream is = buf.getContent();
                            BufferedReader r = new BufferedReader(new InputStreamReader(is));
                            StringBuilder total = new StringBuilder();
                            String line;
                            while ((line = r.readLine()) != null)
                                total.append(line + "\n");

                            if (ht.getContentType().getValue().startsWith("text/plain"))
                                return total.toString();
                            else
                                return "GET Config Error!\n" + total.toString();
                        } catch (Exception e) {
                            e.printStackTrace();
                            if (e.getMessage() != null) {
                                MobileWebCam.LogE(e.getMessage());
                                return "GET Config Error!\n" + e.getMessage();
                            }
                        }

                        return null;
                    }

                    @Override
                    protected void onPostExecute(String result) {
                        if (result != null) {
                            if (result.startsWith("GET Config Error!\n")) {
                                if (!noToasts)
                                    Toast.makeText(context, result, Toast.LENGTH_SHORT).show();
                            } else {
                                PhotoSettings.GETSettings(context, result, prefs);
                            }
                        } else if (!noToasts)
                            Toast.makeText(context, "GET config failed!", Toast.LENGTH_SHORT).show();
                    }
                }.execute();
            }
        });
    }
}