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:MainActivity.java

private void startPreview(CameraCaptureSession session) {
    mCameraCaptureSession = session;//from ww  w .j  a va 2  s . c o m
    mCaptureRequestBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
    HandlerThread backgroundThread = new HandlerThread("CameraPreview");
    backgroundThread.start();
    Handler backgroundHandler = new Handler(backgroundThread.getLooper());
    try {
        mCameraCaptureSession.setRepeatingRequest(mCaptureRequestBuilder.build(), null, backgroundHandler);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}

From source file:com.phonegap.plugins.speech.XSpeechRecognizer.java

private void stopSpeechRecognitionActivity() {
    Handler loopHandler = new Handler(Looper.getMainLooper());
    loopHandler.post(new Runnable() {

        @Override/*from  w ww.  j a va 2s .com*/
        public void run() {
            recognizer.stopListening();
            // recognizer.cancel();
        }

    });
}

From source file:com.felkertech.n.tv.fragments.VideoDetailsFragment.java

private void setupDetailsOverviewRow() {
    final DetailsOverviewRow row = new DetailsOverviewRow(jsonChannel);
    row.setImageDrawable(getResources().getDrawable(R.drawable.c_background5));
    int width = Utils.convertDpToPixel(getActivity().getApplicationContext(), DETAIL_THUMB_WIDTH);
    int height = Utils.convertDpToPixel(getActivity().getApplicationContext(), DETAIL_THUMB_HEIGHT);
    new Thread(new Runnable() {
        @Override//ww  w. j av  a  2 s.c  o m
        public void run() {
            try {
                final Bitmap bitmap = Picasso.with(getActivity()).load(jsonChannel.getLogo()).centerInside()
                        .error(R.drawable.c_background5).resize(DETAIL_THUMB_WIDTH, DETAIL_THUMB_HEIGHT).get();
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        row.setImageBitmap(getActivity(), bitmap);
                        mAdapter.notifyArrayItemRangeChanged(0, mAdapter.size());
                    }
                });
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start();

    ArrayObjectAdapter actions = new ArrayObjectAdapter();
    // Add another action IF it isn't a channel you already have:
    ChannelDatabase cdn = ChannelDatabase.getInstance(getActivity());
    if (cdn.findChannelByMediaUrl(jsonChannel.getMediaUrl()) == null) {
        actions.add(new Action(ACTION_ADD, getString(R.string.add_channel_txt)));
    } else {
        actions.add(new Action(ACTION_EDIT, getString(R.string.edit_channel)));
    }
    actions.add(new Action(ACTION_WATCH, getString(R.string.play)));
    row.setActionsAdapter(actions);
    mAdapter.add(row);
}

From source file:com.dmsl.anyplace.tasks.AnyplaceSuggestionsTask.java

@Override
protected String doInBackground(Void... params) {
    try {//  www. j a  v a2s  .  c om
        // get the search suggestions
        if (searchType == SearchTypes.INDOOR_MODE) {
            // if we are at a zoom level higher than 19 then we use the
            // AnyPlacePOI API

            // sleep for a while to avoid execution in case another task
            // started and check afterwards if you are cancelled
            Thread.sleep(150);
            if (isCancelled()) {
                return "Cancelled!";
            }

            // use the 2-step method to get out quickly if this task is
            // cancelled
            List<PoisModel> places = queryStaticAnyPlacePOI(query);
            if (isCancelled()) {
                return "Cancelled!";
            }

            // create the cursor for the results
            // cursor = AnyPlaceSeachingHelper.prepareSearchViewCursor(places);
            pois = places;

        } else if (searchType == SearchTypes.OUTDOOR_MODE) {
            // at a lower zoom level we use the Google Places API for search
            // in order to allow the user to search more coarsely for
            // locations

            // sleep for a while to avoid execution in case another task
            // started and check afterwards if you are cancelled
            Thread.sleep(500);
            if (isCancelled()) {
                return "Cancelled!";
            }

            // Get a handler that can be used to post to the main thread
            Handler mainHandler = new Handler(ctx.getMainLooper());

            Runnable myRunnable = new Runnable() {

                @Override
                public void run() {
                    try {
                        List<IPoisClass> places = new ArrayList<IPoisClass>(1);
                        PoisModel pm = new PoisModel();
                        pm.name = "Searching through Google ...";
                        places.add(pm);
                        Cursor cursor = AnyPlaceSeachingHelper.prepareSearchViewCursor(places);
                        mListener.onUpdateStatus("Dummy Result", cursor);
                    } finally {
                        synchronized (sync) {
                            run = true;
                            sync.notifyAll();
                        }
                    }
                }
            };

            mainHandler.post(myRunnable);

            // cursor = AnyplacePOIProvider.queryStatic(query,
            // AnyplacePOIProvider.POI_GOOGLE_PLACES, position);
            PlacesList places = GooglePlaces.queryStaticGoogle(query, position);
            if (isCancelled())
                return "Cancelled!";

            // create the cursor for the results
            // cursor = AnyPlaceSeachingHelper.prepareSearchViewCursor(places.results);
            pois = places.results;

            synchronized (sync) {
                while (run == false) {
                    sync.wait();
                }
            }

        }

        if (isCancelled()) {
            return "Cancelled!";
        }

        return "Success!";

    } catch (ConnectTimeoutException e) {
        exceptionOccured = true;
        return "Connecting to the server is taking too long!";
    } catch (SocketTimeoutException e) {
        exceptionOccured = true;
        return "Communication with the server is taking too long!";
    } catch (IOException e) {
        exceptionOccured = true;
        return "Communication error[ " + e.getMessage() + " ]";
    } catch (InterruptedException e) {
        exceptionOccured = true;
        return "Suggestions task interrupted!";
    }

}

From source file:com.kaltura.playersdk.PlayerViewController.java

private void setupPlayerViewController(final Context context) {
    mPowerManager = (PowerManager) context.getSystemService(context.POWER_SERVICE);
    // Get a handler that can be used to post to the main thread
    Handler mainHandler = new Handler(context.getMainLooper());
    Runnable myRunnable = new Runnable() {
        @Override/* www.  jav  a2  s  .  c om*/
        public void run() {
            if (!ChromecastHandler.initialized)
                ChromecastHandler.initialize(context, new OnCastDeviceChangeListener() {

                    @Override
                    public void onCastDeviceChange(CastDevice oldDevice, CastDevice newDevice) {
                        if (ChromecastHandler.selectedDevice != null) {
                            notifyKPlayer("trigger", new String[] { "chromecastDeviceConnected" });
                        } else {
                            notifyKPlayer("trigger", new String[] { "chromecastDeviceDisConnected" });
                        }
                        //                                    createPlayerInstance();
                    }
                }, new OnCastRouteDetectedListener() {
                    @Override
                    public void onCastRouteDetected() {
                        setChromecastVisiblity();
                    }
                });
        }
    };
    mainHandler.post(myRunnable);
}

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    if (item.getTitle().equals(getString(R.string.comment_edit_save))) {

        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setTitle(getString(R.string.comment_reply_submitting_title));
        progressDialog.setMessage(getString(R.string.comment_reply_submitting_message));
        progressDialog.setIndeterminate(true);
        progressDialog.setCancelable(true);
        progressDialog.setCanceledOnTouchOutside(false);

        progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            public void onCancel(final DialogInterface dialogInterface) {
                General.quickToast(CommentEditActivity.this, R.string.comment_reply_oncancel);
                progressDialog.dismiss();
            }/*w  w  w  .j a v  a  2  s. c o  m*/
        });

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

                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    General.quickToast(CommentEditActivity.this, R.string.comment_reply_oncancel);
                    progressDialog.dismiss();
                }

                return true;
            }
        });

        final APIResponseHandler.ActionResponseHandler handler = new APIResponseHandler.ActionResponseHandler(
                this) {
            @Override
            protected void onSuccess() {
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    public void run() {
                        if (progressDialog.isShowing())
                            progressDialog.dismiss();
                        General.quickToast(CommentEditActivity.this, R.string.comment_edit_done);
                        finish();
                    }
                });
            }

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

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

                final RRError error = General.getGeneralErrorForFailure(context, type, t, status);

                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    public void run() {
                        General.showResultDialog(CommentEditActivity.this, error);
                        if (progressDialog.isShowing())
                            progressDialog.dismiss();
                    }
                });
            }

            @Override
            protected void onFailure(final APIFailureType type) {

                final RRError error = General.getGeneralErrorForFailure(context, type);

                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    public void run() {
                        General.showResultDialog(CommentEditActivity.this, error);
                        if (progressDialog.isShowing())
                            progressDialog.dismiss();
                    }
                });
            }
        };

        final CacheManager cm = CacheManager.getInstance(this);
        final RedditAccount selectedAccount = RedditAccountManager.getInstance(this).getDefaultAccount();

        RedditAPI.editComment(cm, handler, selectedAccount, commentIdAndType, textEdit.getText().toString(),
                this);

        progressDialog.show();

    } else if (item.getTitle().equals(getString(R.string.comment_reply_preview))) {
        MarkdownPreviewDialog.newInstance(textEdit.getText().toString()).show(getSupportFragmentManager());
    }

    return true;
}

From source file:me.willowcheng.makerthings.core.OpenHABVoiceService.java

private void performHttpPost(final String itemName, final StringEntity command) {
    /* Call MyAsyncHttpClient on the main UI thread in order to retrieve the callbacks correctly.
     * If calling MyAsyncHttpClient directly, the following would happen:
     * (1) MyAsyncHttpClient performs the HTTP post asynchronously
     * (2) OpenHABVoiceService stops because all intents have been handled
     * (3) MyAsyncHttpClient tries to call onSuccess() or onFailure(), which is not possible
     *     anymore because OpenHABVoiceService is already stopped/destroyed.
     *//*from   ww w  . j ava  2 s .c  o  m*/
    new Handler(Looper.getMainLooper()).post(new Runnable() {
        @Override
        public void run() {
            mAsyncHttpClient.post(OpenHABVoiceService.this, mOpenHABBaseUrl + "rest/items/" + itemName, command,
                    "text/plain;charset=UTF-8", new AsyncHttpResponseHandler() {
                        @Override
                        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                            Log.d(TAG, "Command was sent successfully");
                        }

                        @Override
                        public void onFailure(int statusCode, Header[] headers, byte[] responseBody,
                                Throwable error) {
                            Log.e(TAG, "Got command error " + statusCode, error);
                        }
                    });
        }
    });
}

From source file:com.grumpysailor.cordova.magnetsensor.MagnetSensor.java

/**
 * Start listening for acceleration sensor.
 * //from   w w w .jav a2  s . c  om
 * @return          status of listener
*/
private int start() {
    // If already starting or running, then just return
    if ((this.status == MagnetSensor.RUNNING) || (this.status == MagnetSensor.STARTING)) {
        return this.status;
    }

    this.setStatus(MagnetSensor.STARTING);

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

    // If found, then register as listener
    if ((list != null) && (list.size() > 0)) {
        this.mMagnetometer = list.get(0);
        this.mSensorManager.registerListener(this, this.mMagnetometer, SensorManager.SENSOR_DELAY_UI);
        this.setStatus(MagnetSensor.STARTING);
    } else {
        this.setStatus(MagnetSensor.ERROR_FAILED_TO_START);
        this.fail(MagnetSensor.ERROR_FAILED_TO_START,
                "No sensors found to register magnet sensor 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.CommentEditActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    if (item.getTitle().equals(getString(R.string.comment_edit_save))) {

        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setTitle(getString(R.string.comment_reply_submitting_title));
        progressDialog.setMessage(getString(R.string.comment_reply_submitting_message));
        progressDialog.setIndeterminate(true);
        progressDialog.setCancelable(true);
        progressDialog.setCanceledOnTouchOutside(false);

        progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            public void onCancel(final DialogInterface dialogInterface) {
                General.quickToast(CommentEditActivity.this, R.string.comment_reply_oncancel);
                progressDialog.dismiss();
            }//from ww  w. ja  va 2  s.c o m
        });

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

                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    General.quickToast(CommentEditActivity.this, R.string.comment_reply_oncancel);
                    progressDialog.dismiss();
                }

                return true;
            }
        });

        final APIResponseHandler.ActionResponseHandler handler = new APIResponseHandler.ActionResponseHandler(
                this) {
            @Override
            protected void onSuccess() {
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    public void run() {
                        if (progressDialog.isShowing())
                            progressDialog.dismiss();
                        General.quickToast(CommentEditActivity.this, R.string.comment_edit_done);
                        finish();
                    }
                });
            }

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

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

                final RRError error = General.getGeneralErrorForFailure(context, type, t, status, null);

                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    public void run() {
                        General.showResultDialog(CommentEditActivity.this, error);
                        if (progressDialog.isShowing())
                            progressDialog.dismiss();
                    }
                });
            }

            @Override
            protected void onFailure(final APIFailureType type) {

                final RRError error = General.getGeneralErrorForFailure(context, type);

                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    public void run() {
                        General.showResultDialog(CommentEditActivity.this, error);
                        if (progressDialog.isShowing())
                            progressDialog.dismiss();
                    }
                });
            }
        };

        final CacheManager cm = CacheManager.getInstance(this);
        final RedditAccount selectedAccount = RedditAccountManager.getInstance(this).getDefaultAccount();

        RedditAPI.editComment(cm, handler, selectedAccount, commentIdAndType, textEdit.getText().toString(),
                this);

        progressDialog.show();

    } else if (item.getTitle().equals(getString(R.string.comment_reply_preview))) {
        MarkdownPreviewDialog.newInstance(textEdit.getText().toString()).show(getSupportFragmentManager());
    }

    return true;
}

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    if (item.getTitle().equals(getString(R.string.comment_reply_send))) {

        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setTitle(getString(R.string.comment_reply_submitting_title));
        progressDialog.setMessage(getString(R.string.comment_reply_submitting_message));
        progressDialog.setIndeterminate(true);
        progressDialog.setCancelable(true);
        progressDialog.setCanceledOnTouchOutside(false);

        progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            public void onCancel(final DialogInterface dialogInterface) {
                General.quickToast(CommentReplyActivity.this, getString(R.string.comment_reply_oncancel));
                progressDialog.dismiss();
            }/*from   w  w  w .j a  v a  2  s  .  c  o  m*/
        });

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

                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    General.quickToast(CommentReplyActivity.this, getString(R.string.comment_reply_oncancel));
                    progressDialog.dismiss();
                }

                return true;
            }
        });

        final APIResponseHandler.ActionResponseHandler handler = new APIResponseHandler.ActionResponseHandler(
                this) {
            @Override
            protected void onSuccess() {
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    public void run() {
                        if (progressDialog.isShowing())
                            progressDialog.dismiss();
                        General.quickToast(CommentReplyActivity.this, getString(R.string.comment_reply_done));
                        finish();
                    }
                });
            }

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

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

                final RRError error = General.getGeneralErrorForFailure(context, type, t, status);

                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    public void run() {
                        General.showResultDialog(CommentReplyActivity.this, error);
                        if (progressDialog.isShowing())
                            progressDialog.dismiss();
                    }
                });
            }

            @Override
            protected void onFailure(final APIFailureType type) {

                final RRError error = General.getGeneralErrorForFailure(context, type);

                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    public void run() {
                        General.showResultDialog(CommentReplyActivity.this, error);
                        if (progressDialog.isShowing())
                            progressDialog.dismiss();
                    }
                });
            }
        };

        final CacheManager cm = CacheManager.getInstance(this);

        final ArrayList<RedditAccount> accounts = RedditAccountManager.getInstance(this).getAccounts();
        RedditAccount selectedAccount = null;

        for (RedditAccount account : accounts) {
            if (!account.isAnonymous()
                    && account.username.equalsIgnoreCase((String) usernameSpinner.getSelectedItem())) {
                selectedAccount = account;
                break;
            }
        }

        RedditAPI.comment(cm, handler, selectedAccount, parentIdAndType, textEdit.getText().toString(), this);

        progressDialog.show();

    } else if (item.getTitle().equals(getString(R.string.comment_reply_preview))) {
        MarkdownPreviewDialog.newInstance(textEdit.getText().toString()).show(getSupportFragmentManager());
    }

    return true;
}