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.plugins.MagnetometerListener.java

/**
 * Start listening for speed sensor.//from  ww w.j  a  v a  2 s.  c  o m
 *
 * @return          status of listener
*/
private int start() {
    // If already starting or running, then just return
    if ((this.status == MagnetometerListener.RUNNING) || (this.status == MagnetometerListener.STARTING)) {
        return this.status;
    }

    this.setStatus(MagnetometerListener.STARTING);

    // Get magnetometer from sensor manager
    List<Sensor> list = this.sensorManager.getSensorList(Sensor.TYPE_MAGNETIC_FIELD);

    // If found, then register as listener
    if ((list != null) && (list.size() > 0)) {
        this.mSensor = list.get(0);
        this.sensorManager.registerListener(this, this.mSensor, SensorManager.SENSOR_DELAY_UI);
        this.setStatus(MagnetometerListener.STARTING);
    } else {
        this.setStatus(MagnetometerListener.ERROR_FAILED_TO_START);
        this.fail(MagnetometerListener.ERROR_FAILED_TO_START,
                "No sensors found to register magnetometer listening to.");
        return this.status;
    }

    // Set a timeout callback on the main thread.
    stopTimeout();
    mainHandler = new Handler(Looper.getMainLooper());
    mainHandler.postDelayed(mainRunnable, 2000);

    return this.status;
}

From source file:com.android.plugins.GyroscopeListener.java

/**
 * Start listening for speed sensor.//from w  ww.ja  v  a  2  s  . c om
 *
 * @return          status of listener
*/
private int start() {
    // If already starting or running, then just return
    if ((this.status == GyroscopeListener.RUNNING) || (this.status == GyroscopeListener.STARTING)) {
        return this.status;
    }

    this.setStatus(GyroscopeListener.STARTING);

    // Get gyroscope from sensor manager
    List<Sensor> list = this.sensorManager.getSensorList(Sensor.TYPE_GYROSCOPE);

    // If found, then register as listener
    if ((list != null) && (list.size() > 0)) {
        this.mSensor = list.get(0);
        this.sensorManager.registerListener(this, this.mSensor, SensorManager.SENSOR_DELAY_UI);
        this.setStatus(GyroscopeListener.STARTING);
    } else {
        this.setStatus(GyroscopeListener.ERROR_FAILED_TO_START);
        this.fail(GyroscopeListener.ERROR_FAILED_TO_START,
                "No sensors found to register gyroscope listening to.");
        return this.status;
    }

    // Set a timeout callback on the main thread.
    stopTimeout();
    mainHandler = new Handler(Looper.getMainLooper());
    mainHandler.postDelayed(mainRunnable, 2000);

    return this.status;
}

From source file:org.quantumbadger.redreader.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);//from w w w  .ja  v  a 2  s .co  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, url.toString());
                    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,
                    null);
            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:mobisocial.musubi.service.AddressBookUpdateHandler.java

public AddressBookUpdateHandler(Context context, SQLiteOpenHelper dbh, HandlerThread thread,
        ContentResolver resolver) {//from ww w.  j  a va  2  s .  co  m
    super(new Handler(thread.getLooper()));
    mThread = thread;
    mContext = context.getApplicationContext();
    mContactThumbnailCache = App.getContactCache(context);
    mAccountType = mContext.getString(R.string.account_type);

    resolver.registerContentObserver(MusubiService.FORCE_RESCAN_CONTACTS, false,
            new ContentObserver(new Handler(thread.getLooper())) {
                public void onChange(boolean selfChange) {
                    mLastRun = -1;
                    AddressBookUpdateHandler.this.dispatchChange(false);
                }
            });

    dispatchChange(false);
}

From source file:com.appnexus.opensdk.ANNativeAdResponse.java

/**
 * Process the metadata of native response from ad server
 *
 * @param metaData JsonObject that contains info of native ad
 * @return ANNativeResponse if no issue happened during processing
 *//*from  ww w  . jav a2s  .c  o  m*/
static ANNativeAdResponse create(JSONObject metaData) {
    if (metaData == null) {
        return null;
    }
    JSONArray impTrackerJson = JsonUtil.getJSONArray(metaData, KEY_IMP_TRACK);
    ArrayList<String> imp_trackers = JsonUtil.getStringArrayList(impTrackerJson);
    if (imp_trackers == null) {
        return null;
    }
    ANNativeAdResponse response = new ANNativeAdResponse();
    response.imp_trackers = imp_trackers;
    response.title = JsonUtil.getJSONString(metaData, KEY_TITLE);
    response.description = JsonUtil.getJSONString(metaData, KEY_DESCRIPTION);
    JSONArray main_media = JsonUtil.getJSONArray(metaData, KEY_MAIN_MEDIA);
    if (main_media != null) {
        int l = main_media.length();
        for (int i = 0; i < l; i++) {
            JSONObject media = JsonUtil.getJSONObjectFromArray(main_media, i);
            if (media != null) {
                String label = JsonUtil.getJSONString(media, KEY_IMAGE_LABEL);
                if (label != null && label.equals(VALUE_DEFAULT_IMAGE)) {
                    response.imageUrl = JsonUtil.getJSONString(media, KEY_IMAGE_URL);
                    break;
                }
            }
        }
    }
    ;
    response.iconUrl = JsonUtil.getJSONString(metaData, KEY_ICON);
    response.socialContext = JsonUtil.getJSONString(metaData, KEY_CONTEXT);
    response.callToAction = JsonUtil.getJSONString(metaData, KEY_CTA);
    response.clickUrl = JsonUtil.getJSONString(metaData, KEY_CLICK_URL);
    response.clickFallBackUrl = JsonUtil.getJSONString(metaData, KEY_CLICK_FALLBACK_URL);
    JSONObject rating = JsonUtil.getJSONObject(metaData, KEY_RATING);
    response.rating = new Rating(JsonUtil.getJSONDouble(rating, KEY_RATING_VALUE),
            JsonUtil.getJSONDouble(rating, KEY_RATING_SCALE));
    JSONArray clickTrackerJson = JsonUtil.getJSONArray(metaData, KEY_CLICK_TRACK);
    response.click_trackers = JsonUtil.getStringArrayList(clickTrackerJson);
    JSONObject custom = JsonUtil.getJSONObject(metaData, KEY_CUSTOM);
    response.nativeElements = JsonUtil.getStringObjectHashMap(custom);
    Handler handler = new Handler(Looper.getMainLooper());
    handler.postDelayed(response.expireRunnable, Settings.NATIVE_AD_RESPONSE_EXPIRATION_TIME);
    return response;
}

From source file:com.arellomobile.android.push.PushManager.java

public static void sendTags(final Context context, final Map<String, Object> tags,
        final SendPushTagsCallBack callBack) {
    Handler handler = new Handler(context.getMainLooper());
    handler.post(new Runnable() {
        @SuppressWarnings("unchecked")
        public void run() {
            new SendPushTagsAsyncTask(context, callBack).execute(tags);
        }//  w  ww.java2s  .co  m
    });
}

From source file:Main.java

public static Handler runInUIThread(final Runnable runnable, boolean runImmediatelyIfPossible) {
    if (runnable == null) {
        return null;
    }/*from  w w w .ja  v a  2 s  .  com*/

    final Handler handler;
    Looper mainLooper = Looper.getMainLooper();
    if (runImmediatelyIfPossible && (Thread.currentThread() == mainLooper.getThread())) {
        handler = null;
        runnable.run();
    } else {
        handler = new Handler(mainLooper);
        handler.post(runnable);
    }

    return handler;
}

From source file:com.github.yuukis.businessmap.app.ContactsTaskFragment.java

private void showProgress() {
    String title = getString(R.string.title_geocoding);
    String message = getString(R.string.message_geocoding);
    int max = mGeocodingResultCache.size();

    Bundle args = new Bundle();
    args.putString(ProgressDialogFragment.TITLE, title);
    args.putString(ProgressDialogFragment.MESSAGE, message);
    args.putBoolean(ProgressDialogFragment.CANCELABLE, true);
    args.putInt(ProgressDialogFragment.MAX, max);
    final DialogFragment dialog = ProgressDialogFragment.newInstance();
    dialog.setArguments(args);//from  w  ww.  j a v a 2s.co  m
    if (getActivity() != null) {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                dialog.show(getActivity().getSupportFragmentManager(), ProgressDialogFragment.TAG);
            }
        });
    }
}

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

@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
        final Bundle savedInstanceState) {

    // TODO load menu position?

    final Context context;

    // /*from   www. j ava  2  s.co m*/
    if (container != null) {
        context = container.getContext(); // TODO just use the inflater's
        // context in every case?
    } else {
        context = inflater.getContext();
    }

    // 
    final RedditAccount user = RedditAccountManager.getInstance(context).getDefaultAccount();

    final LinearLayout outer = new LinearLayout(context);

    // 
    outer.setOrientation(LinearLayout.VERTICAL);

    notifications = new LinearLayout(context);
    notifications.setOrientation(LinearLayout.VERTICAL);

    loadingView = new LoadingView(context, R.string.download_waiting, true, true);

    final ListView lv = new ListView(context);
    lv.setDivider(null);

    // listview?
    lv.addFooterView(notifications);

    final int paddingPx = General.dpToPixels(context, 8);
    lv.setPadding(paddingPx, 0, paddingPx, 0);

    adapter = new MainMenuAdapter(context, user, this);
    lv.setAdapter(adapter);

    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(final AdapterView<?> adapterView, final View view, final int position,
                final long id) {
            adapter.clickOn(position);
        }
    });

    final AtomicReference<APIResponseHandler.SubredditResponseHandler> accessibleSubredditResponseHandler = new AtomicReference<APIResponseHandler.SubredditResponseHandler>(
            null);

    final APIResponseHandler.SubredditResponseHandler responseHandler = new APIResponseHandler.SubredditResponseHandler(
            context) {

        @Override
        protected void onDownloadNecessary() {
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                public void run() {
                    notifications.addView(loadingView);
                }
            });
        }

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

        @Override
        protected void onSuccess(final List<RedditSubreddit> result, final long timestamp) {

            if (result.size() == 0) {
                // Just get the defaults instead
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    public void run() {
                        notifications.removeView(loadingView);
                        RedditAPI.getUserSubreddits(CacheManager.getInstance(context),
                                accessibleSubredditResponseHandler.get(), RedditAccountManager.getAnon(),
                                force ? CacheRequest.DownloadType.FORCE
                                        : CacheRequest.DownloadType.IF_NECESSARY,
                                force, context);
                    }
                });

            } else {

                adapter.setSubreddits(result);

                if (loadingView != null)
                    loadingView.setDone(R.string.download_done);
            }
        }

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

        @Override
        protected void onFailure(final RequestFailureType type, final Throwable t, final StatusLine status,
                final String readableMessage) {

            if (loadingView != null)
                loadingView.setDone(R.string.download_failed);
            final RRError error = General.getGeneralErrorForFailure(context, type, t, status);

            new Handler(Looper.getMainLooper()).post(new Runnable() {
                public void run() {
                    notifications.addView(new ErrorView(getSupportActivity(), error));
                }
            });
        }

        @Override
        protected void onFailure(final APIFailureType type) {

            if (loadingView != null)
                loadingView.setDone(R.string.download_failed);
            final RRError error = General.getGeneralErrorForFailure(context, type);

            new Handler(Looper.getMainLooper()).post(new Runnable() {
                public void run() {
                    notifications.addView(new ErrorView(getSupportActivity(), error));
                }
            });
        }
    };

    accessibleSubredditResponseHandler.set(responseHandler);

    RedditAPI.getUserSubreddits(CacheManager.getInstance(context), responseHandler, user,
            force ? CacheRequest.DownloadType.FORCE : CacheRequest.DownloadType.IF_NECESSARY, force, context);

    outer.addView(lv);
    lv.getLayoutParams().height = ViewGroup.LayoutParams.MATCH_PARENT;

    return outer;
}

From source file:com.bluetooth.activities.WiFiControl.java

public void buttonClick(View v) {
    isRunning = !isRunning;//  w  ww  .ja v  a 2  s. c om
    if (isRunning) {
        Thread server = new Thread(new ServerThread(new Handler(this)));
        server.start();
        bToggle.setText(R.string.serverStop);
    } else {
        tvIP.setText("");
        bToggle.setText(R.string.serverStart);
    }
}