Example usage for android.os Handler Handler

List of usage examples for android.os Handler Handler

Introduction

In this page you can find the example usage for android.os Handler Handler.

Prototype

@UnsupportedAppUsage
public Handler(boolean async) 

Source Link

Document

Use the Looper for the current thread and set whether the handler should be asynchronous.

Usage

From source file:com.android.volley.RequestQueue.java

/**
 * Creates the worker pool. Processing will not begin until {@link #start()} is called.
 *
 * @param cache A Cache to use for persisting responses to disk
 * @param network A Network interface for performing HTTP requests
 * @param threadPoolSize Number of network dispatcher threads to create
 */// w w  w .j  a v a  2  s.co m
public RequestQueue(Cache cache, Network network, int threadPoolSize) {
    this(cache, network, threadPoolSize, new ExecutorDelivery(new Handler(Looper.getMainLooper())));
}

From source file:com.ryan.ryanreader.fragments.AddAccountDialog.java

@Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {

    if (alreadyCreated)
        return getDialog();
    alreadyCreated = true;//from  w w  w. j ava  2 s  .  c  o m

    super.onCreateDialog(savedInstanceState);

    final AlertDialog.Builder builder = new AlertDialog.Builder(getSupportActivity());
    builder.setTitle(R.string.accounts_add);

    final View view = getSupportActivity().getLayoutInflater().inflate(R.layout.dialog_login, null);
    builder.setView(view);
    builder.setCancelable(true);

    final EditText usernameBox = ((EditText) view.findViewById(R.id.login_username));
    usernameBox.setText(lastUsername);
    usernameBox.requestFocus();
    usernameBox.requestFocusFromTouch();

    builder.setPositiveButton(R.string.accounts_login, new DialogInterface.OnClickListener() {
        public void onClick(final DialogInterface dialogInterface, final int i) {

            final String username = ((EditText) getDialog().findViewById(R.id.login_username)).getText()
                    .toString().trim();
            final String password = ((EditText) getDialog().findViewById(R.id.login_password)).getText()
                    .toString();

            lastUsername = username;

            final ProgressDialog progressDialog = new ProgressDialog(getSupportActivity());
            final Thread thread;
            progressDialog.setTitle(R.string.accounts_loggingin);
            progressDialog.setMessage(getString(R.string.accounts_loggingin_msg));
            progressDialog.setIndeterminate(true);

            final AtomicBoolean cancelled = new AtomicBoolean(false);

            progressDialog.setCancelable(true);
            progressDialog.setCanceledOnTouchOutside(false);

            progressDialog.show();

            progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                public void onCancel(final DialogInterface dialogInterface) {
                    cancelled.set(true);
                    progressDialog.dismiss();
                }
            });

            progressDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                public boolean onKey(final DialogInterface dialogInterface, final int keyCode,
                        final KeyEvent keyEvent) {

                    if (keyCode == KeyEvent.KEYCODE_BACK) {
                        cancelled.set(true);
                        progressDialog.dismiss();
                    }

                    return true;
                }
            });

            thread = new Thread() {
                @Override
                public void run() {

                    // TODO better HTTP client
                    final RedditAccount.LoginResultPair result = RedditAccount.login(getSupportActivity(),
                            username, password, new DefaultHttpClient());

                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        public void run() {

                            if (cancelled.get())
                                return; // safe, since we're in the UI thread

                            progressDialog.dismiss();

                            final AlertDialog.Builder alertBuilder = new AlertDialog.Builder(
                                    getSupportActivity());
                            alertBuilder.setNeutralButton(R.string.dialog_close,
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {
                                            new AccountListDialog().show(getSupportActivity());
                                        }
                                    });

                            // TODO handle errors better
                            switch (result.result) {
                            case CONNECTION_ERROR:
                                alertBuilder.setTitle(R.string.error_connection_title);
                                alertBuilder.setMessage(R.string.message_cannotlogin);
                                break;
                            case INTERNAL_ERROR:
                                alertBuilder.setTitle(R.string.error_unknown_title);
                                alertBuilder.setMessage(R.string.message_cannotlogin);
                                break;
                            case JSON_ERROR:
                                alertBuilder.setTitle(R.string.error_parse_title);
                                alertBuilder.setMessage(R.string.message_cannotlogin);
                                break;
                            case REQUEST_ERROR:
                                alertBuilder.setTitle(R.string.error_connection_title);
                                alertBuilder.setMessage(R.string.message_cannotlogin);
                                break;
                            case UNKNOWN_REDDIT_ERROR:
                                alertBuilder.setTitle(R.string.error_unknown_title);
                                alertBuilder.setMessage(R.string.message_cannotlogin);
                                break;
                            case WRONG_PASSWORD:
                                alertBuilder.setTitle(R.string.error_invalid_password_title);
                                alertBuilder.setMessage(R.string.error_invalid_password_message);
                                break;
                            case RATELIMIT:
                                alertBuilder.setTitle(R.string.error_ratelimit_title);
                                alertBuilder.setMessage(String.format("%s \"%s\"",
                                        getString(R.string.error_ratelimit_message), result.extraMessage));
                                break;
                            case SUCCESS:
                                RedditAccountManager.getInstance(getSupportActivity())
                                        .addAccount(result.account);
                                RedditAccountManager.getInstance(getSupportActivity())
                                        .setDefaultAccount(result.account);
                                alertBuilder.setTitle(R.string.general_success);
                                alertBuilder.setMessage(R.string.message_nowloggedin);
                                lastUsername = "";
                                break;
                            default:
                                throw new RuntimeException();
                            }

                            final AlertDialog alertDialog = alertBuilder.create();
                            alertDialog.show();
                        }
                    });
                }
            };

            thread.start();
        }
    });

    builder.setNegativeButton(R.string.dialog_cancel, null);

    return builder.create();
}

From source file:com.android.adcnx.adlib.plugin.AdConnectLibrary.java

private PluginResult createAdBlock(JSONObject params, final String callbackID) {
    final String action = "create";

    if (_lib != null) {
        return createResultWithJSONMessage(Status.ERROR,
                "There is already an instance of the library" + "currently running.");
    }//from  w  ww. j a v  a2 s .  co m

    if (params == null) {
        return createResultWithJSONMessage(Status.ERROR, "No params passed for action " + action);
    }

    //_createCallbackID = callbackID;
    log("Creating a new AdBlock");

    final String publisherID = params.optString("id");

    if (publisherID.equalsIgnoreCase("")) {
        return createResultWithJSONMessage(Status.ERROR, "Missing publisher id");
    }

    log("have publisher id.");

    JSONObject size = params.optJSONObject("size");

    if (size == null) {
        return createResultWithJSONMessage(Status.ERROR, "Missing AdSize");
    }

    final int width = size.optInt("width");
    final int height = size.optInt("height");

    if (width < 1 || height < 1) {
        return createResultWithJSONMessage(Status.ERROR, "AdSize is too small");
    }

    final JSONObject layout = params.optJSONObject("layout");

    log("have AdSize");

    Handler h = new Handler(ctx.getContext().getMainLooper());
    final AdConnectLibrary self = this;
    h.post(new Runnable() {

        public void run() {
            _lib = new AdBlock(ctx.getContext(), new AdSize(width, height), publisherID);

            _lib.setAdListener(self);
            LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

            if (layout != null) {
                log("setting the layout");

                String gravity = layout.optString("gravity");
                if (!gravity.equalsIgnoreCase("")) {
                    log("Have gravity: " + gravity);
                    layoutParams.gravity = getGravity(gravity);
                }
            }

            log("have a new lib");

            ((LinearLayout) webView.getParent()).addView(_lib, layoutParams);

            log("successfully added adblock to webview");

            updateAdBlockCreation(callbackID);
        }

    });

    PluginResult result = createResultWithJSONMessage(Status.NO_RESULT, "Awaiting AdBlockCreation");
    result.setKeepCallback(true);
    return result;
}

From source file:io.v.android.apps.account_manager.AccountActivity.java

private void getIdentity() {
    if (mAccountName == null || mAccountName.isEmpty()) {
        replyWithError("Empty account name.");
        return;/* w w  w  .  j  a va 2s . c o  m*/
    }
    Account[] accounts = AccountManager.get(this).getAccountsByType("com.google");
    Account account = null;
    for (int i = 0; i < accounts.length; i++) {
        if (accounts[i].name.equals(mAccountName)) {
            account = accounts[i];
        }
    }
    if (account == null) {
        replyWithError("Couldn't find Google account with name: " + mAccountName);
        return;
    }
    AccountManager.get(this).getAuthToken(account, OAUTH_SCOPE, new Bundle(), false, new OnTokenAcquired(),
            new Handler(new Handler.Callback() {
                @Override
                public boolean handleMessage(Message msg) {
                    replyWithError("Error getting auth token: " + msg.toString());
                    return true;
                }
            }));
}

From source file:com.facebook.share.internal.VideoUploader.java

private static synchronized Handler getHandler() {
    if (handler == null) {
        handler = new Handler(Looper.getMainLooper());
    }/*from   w w  w . j  a v a  2 s. c  om*/
    return handler;
}

From source file:facebook.TiFacebookModule.java

public void makeMeRequest(final AccessToken accessToken) {
    new Handler(Looper.getMainLooper()).post(new Runnable() {
        @Override// ww w  .jav a  2  s .c o  m
        public void run() {
            GraphRequest request = GraphRequest.newMeRequest(accessToken,
                    new GraphRequest.GraphJSONObjectCallback() {
                        @Override
                        public void onCompleted(JSONObject user, GraphResponse response) {
                            FacebookRequestError err = response.getError();
                            KrollDict data = new KrollDict();

                            if (user != null) {
                                Log.d(TAG, "user is not null");

                                data.put(TiFacebookModule.PROPERTY_CANCELLED, false);
                                data.put(TiFacebookModule.PROPERTY_SUCCESS, true);
                                data.put(TiFacebookModule.PROPERTY_UID, user.optString("id"));
                                data.put(TiFacebookModule.PROPERTY_DATA, user.toString());
                                data.put(TiFacebookModule.PROPERTY_CODE, 0);
                                Log.d(TAG, "firing login event from module");
                                fireEvent(TiFacebookModule.EVENT_LOGIN, data);
                            }

                            if (err != null) {
                                String errorString = TiFacebookModule.handleError(err);
                                Log.e(TAG, "me request callback error");
                                Log.e(TAG, "error message: " + err.getErrorMessage());
                                data.put(TiFacebookModule.PROPERTY_ERROR, errorString);
                                fireEvent(TiFacebookModule.EVENT_LOGIN, data);
                            }
                        }
                    });
            request.executeAsync();
        }
    });
}

From source file:ai.api.sample.AIDialogSampleActivity.java

@Override
public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_aidialog_sample);

    resultTextView = (TextView) findViewById(R.id.resultTextView);
    resultTextView.setMovementMethod(new ScrollingMovementMethod());

    final AIConfiguration config = new AIConfiguration(Config.ACCESS_TOKEN,
            AIConfiguration.SupportedLanguages.English, AIConfiguration.RecognitionEngine.System);

    aiDialog = new AIDialog(this, config);
    aiDialog.setResultsListener(this);
    dialogue = "";
    handler = new Handler(Looper.getMainLooper());
    isDialogEnd = false;//from  w w w  . j av a  2s . c o  m
    //aiDialog.getAIService().resetContexts();
    itemsToAdd = new ArrayList<String>();
}

From source file:com.ryan.ryanreader.activities.CaptchaActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {

    PrefsUtility.applyTheme(this);
    getSupportActionBar().setTitle(R.string.post_captcha_title);

    super.onCreate(savedInstanceState);

    final LoadingView loadingView = new LoadingView(this, R.string.download_waiting, true, true);
    setContentView(loadingView);/*w ww. ja va  2s . c o  m*/

    final RedditAccount selectedAccount = RedditAccountManager.getInstance(this)
            .getAccount(getIntent().getStringExtra("username"));

    final CacheManager cm = CacheManager.getInstance(this);

    RedditAPI.newCaptcha(cm, new APIResponseHandler.NewCaptchaResponseHandler(this) {
        @Override
        protected void onSuccess(final String captchaId) {

            final URI captchaUrl = Constants.Reddit.getUri("/captcha/" + captchaId);

            cm.makeRequest(new CacheRequest(captchaUrl, RedditAccountManager.getAnon(), null,
                    Constants.Priority.CAPTCHA, 0, CacheRequest.DownloadType.FORCE, Constants.FileType.CAPTCHA,
                    false, false, true, CaptchaActivity.this) {
                @Override
                protected void onCallbackException(Throwable t) {
                    BugReportActivity.handleGlobalError(CaptchaActivity.this, t);
                }

                @Override
                protected void onDownloadNecessary() {
                }

                @Override
                protected void onDownloadStarted() {
                    loadingView.setIndeterminate(R.string.download_downloading);
                }

                @Override
                protected void onFailure(RequestFailureType type, Throwable t, StatusLine status,
                        String readableMessage) {
                    final RRError error = General.getGeneralErrorForFailure(CaptchaActivity.this, type, t,
                            status);
                    General.showResultDialog(CaptchaActivity.this, error);
                    finish();
                }

                @Override
                protected void onProgress(long bytesRead, long totalBytes) {
                    loadingView.setProgress(R.string.download_downloading,
                            (float) ((double) bytesRead / (double) totalBytes));
                }

                @Override
                protected void onSuccess(final CacheManager.ReadableCacheFile cacheFile, long timestamp,
                        UUID session, boolean fromCache, String mimetype) {

                    final Bitmap image;
                    try {
                        image = BitmapFactory.decodeStream(cacheFile.getInputStream());
                    } catch (IOException e) {
                        BugReportActivity.handleGlobalError(CaptchaActivity.this, e);
                        return;
                    }

                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        public void run() {

                            final LinearLayout ll = new LinearLayout(CaptchaActivity.this);
                            ll.setOrientation(LinearLayout.VERTICAL);

                            final ImageView captchaImg = new ImageView(CaptchaActivity.this);
                            ll.addView(captchaImg);
                            final LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) captchaImg
                                    .getLayoutParams();
                            layoutParams.setMargins(20, 20, 20, 20);
                            layoutParams.height = General.dpToPixels(context, 100);
                            captchaImg.setScaleType(ImageView.ScaleType.FIT_CENTER);

                            final EditText captchaText = new EditText(CaptchaActivity.this);
                            ll.addView(captchaText);
                            ((LinearLayout.LayoutParams) captchaText.getLayoutParams()).setMargins(20, 0, 20,
                                    20);
                            captchaText.setInputType(android.text.InputType.TYPE_CLASS_TEXT
                                    | android.text.InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
                                    | InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS);

                            captchaImg.setImageBitmap(image);

                            final Button submitButton = new Button(CaptchaActivity.this);
                            submitButton.setText(R.string.post_captcha_submit_button);
                            ll.addView(submitButton);
                            ((LinearLayout.LayoutParams) submitButton.getLayoutParams()).setMargins(20, 0, 20,
                                    20);
                            ((LinearLayout.LayoutParams) submitButton
                                    .getLayoutParams()).gravity = Gravity.RIGHT;
                            ((LinearLayout.LayoutParams) submitButton
                                    .getLayoutParams()).width = LinearLayout.LayoutParams.WRAP_CONTENT;

                            submitButton.setOnClickListener(new View.OnClickListener() {
                                public void onClick(View v) {
                                    final Intent result = new Intent();
                                    result.putExtra("captchaId", captchaId);
                                    result.putExtra("captchaText", captchaText.getText().toString());
                                    setResult(RESULT_OK, result);
                                    finish();
                                }
                            });

                            final ScrollView sv = new ScrollView(CaptchaActivity.this);
                            sv.addView(ll);
                            setContentView(sv);
                        }
                    });

                }
            });
        }

        @Override
        protected void onCallbackException(Throwable t) {
            BugReportActivity.handleGlobalError(CaptchaActivity.this, t);
        }

        @Override
        protected void onFailure(RequestFailureType type, Throwable t, StatusLine status,
                String readableMessage) {
            final RRError error = General.getGeneralErrorForFailure(CaptchaActivity.this, type, t, status);
            General.showResultDialog(CaptchaActivity.this, error);
            finish();
        }

        @Override
        protected void onFailure(APIFailureType type) {
            final RRError error = General.getGeneralErrorForFailure(CaptchaActivity.this, type);
            General.showResultDialog(CaptchaActivity.this, error);
            finish();
        }
    }, selectedAccount, this);
}

From source file:com.connectsdk.discovery.provider.CastDiscoveryProvider.java

@Override
public void stop() {
    if (addCallbackTimer != null) {
        addCallbackTimer.cancel();//from  w  ww  .j  a  va2s .c  o  m
    }

    if (removeCallbackTimer != null) {
        removeCallbackTimer.cancel();
    }

    if (mMediaRouter != null) {
        new Handler(Looper.getMainLooper()).post(new Runnable() {

            @Override
            public void run() {
                mMediaRouter.removeCallback(mMediaRouterCallback);
            }
        });
    }
}

From source file:com.nhn.android.archetype.base.AABaseApplicationOrg.java

protected void init() {
    workExecutor = Executors.newCachedThreadPool();
    statsWorkExecutor = Executors.newFixedThreadPool(1);

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

    backgroundHandlerThread = new HandlerThread("BandBackgroundHandlerThread");
    backgroundHandlerThread.start();//from   www.  j  a  v  a  2  s.  c  om

    backgroundHandler = new Handler(backgroundHandlerThread.getLooper());

    JsonWorker.init();

    logger.d("Application init completed.....");
}