Example usage for android.os Message obtain

List of usage examples for android.os Message obtain

Introduction

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

Prototype

public static Message obtain() 

Source Link

Document

Return a new Message instance from the global pool.

Usage

From source file:com.ab.http.AsyncHttpResponseHandler.java

/**
 * Obtain message./*from   ww w .j a  va2 s. c o m*/
 *
 * @param responseMessage the response message
 * @param response the response
 * @return the message
 */
protected Message obtainMessage(int responseMessage, Object response) {
    Message msg;
    if (handler != null) {
        msg = handler.obtainMessage(responseMessage, response);
    } else {
        msg = Message.obtain();
        if (msg != null) {
            msg.what = responseMessage;
            msg.obj = response;
        }
    }
    return msg;
}

From source file:pl.poznan.put.cs.ify.app.MainActivity.java

public void removeAvailableRecipe(String name) {
    if (mService != null) {
        Message msg = Message.obtain();
        Bundle b = new Bundle();
        msg.what = ServiceHandler.REQUEST_REMOVE_AVAILABLE_RECIPE;
        b.putString(YRecipesService.Recipe, name);
        msg.setData(b);//  w w w.j a v  a 2s.c o m
        try {
            mService.send(msg);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.android.yijiang.kzx.http.AsyncHttpResponseHandler.java

/**
 * Helper method to create Message instance from handler
 *
 * @param responseMessageId   constant to identify Handler message
 * @param responseMessageData object to be passed to message receiver
 * @return Message instance, should not be null
 *//*  www  .ja  v  a 2s. c  o  m*/
protected Message obtainMessage(int responseMessageId, Object responseMessageData) {
    Message msg;
    if (handler == null) {
        msg = Message.obtain();
        if (msg != null) {
            msg.what = responseMessageId;
            msg.obj = responseMessageData;
        }
    } else {
        msg = Message.obtain(handler, responseMessageId, responseMessageData);
    }
    return msg;
}

From source file:cgeo.geocaching.CacheDetailActivity.java

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

    // get parameters
    final Bundle extras = getIntent().getExtras();
    final Uri uri = AndroidBeam.getUri(getIntent());

    // try to get data from extras
    String name = null;/*from  ww  w.  jav a 2s.co m*/
    String guid = null;

    if (extras != null) {
        geocode = extras.getString(Intents.EXTRA_GEOCODE);
        name = extras.getString(Intents.EXTRA_NAME);
        guid = extras.getString(Intents.EXTRA_GUID);
    }

    // When clicking a cache in MapsWithMe, we get back a PendingIntent
    if (StringUtils.isEmpty(geocode)) {
        geocode = MapsMeCacheListApp.getCacheFromMapsWithMe(this, getIntent());
    }

    if (geocode == null && uri != null) {
        geocode = ConnectorFactory.getGeocodeFromURL(uri.toString());
    }

    // try to get data from URI
    if (geocode == null && guid == null && uri != null) {
        final String uriHost = uri.getHost().toLowerCase(Locale.US);
        final String uriPath = uri.getPath().toLowerCase(Locale.US);
        final String uriQuery = uri.getQuery();

        if (uriQuery != null) {
            Log.i("Opening URI: " + uriHost + uriPath + "?" + uriQuery);
        } else {
            Log.i("Opening URI: " + uriHost + uriPath);
        }

        if (uriHost.contains("geocaching.com")) {
            if (StringUtils.startsWith(uriPath, "/geocache/gc")) {
                geocode = StringUtils.substringBefore(uriPath.substring(10), "_").toUpperCase(Locale.US);
            } else {
                geocode = uri.getQueryParameter("wp");
                guid = uri.getQueryParameter("guid");

                if (StringUtils.isNotBlank(geocode)) {
                    geocode = geocode.toUpperCase(Locale.US);
                    guid = null;
                } else if (StringUtils.isNotBlank(guid)) {
                    geocode = null;
                    guid = guid.toLowerCase(Locale.US);
                } else {
                    showToast(res.getString(R.string.err_detail_open));
                    finish();
                    return;
                }
            }
        }
    }

    // no given data
    if (geocode == null && guid == null) {
        showToast(res.getString(R.string.err_detail_cache));
        finish();
        return;
    }

    // If we open this cache from a search, let's properly initialize the title bar, even if we don't have cache details
    setCacheTitleBar(geocode, name, null);

    final LoadCacheHandler loadCacheHandler = new LoadCacheHandler(this, progress);

    try {
        String title = res.getString(R.string.cache);
        if (StringUtils.isNotBlank(name)) {
            title = name;
        } else if (geocode != null && StringUtils.isNotBlank(geocode)) { // can't be null, but the compiler doesn't understand StringUtils.isNotBlank()
            title = geocode;
        }
        progress.show(this, title, res.getString(R.string.cache_dialog_loading_details), true,
                loadCacheHandler.disposeMessage());
    } catch (final RuntimeException ignored) {
        // nothing, we lost the window
    }

    final int pageToOpen = savedInstanceState != null ? savedInstanceState.getInt(STATE_PAGE_INDEX, 0)
            : Settings.isOpenLastDetailsPage() ? Settings.getLastDetailsPage() : 1;
    createViewPager(pageToOpen, new OnPageSelectedListener() {

        @Override
        public void onPageSelected(final int position) {
            if (Settings.isOpenLastDetailsPage()) {
                Settings.setLastDetailsPage(position);
            }
            // lazy loading of cache images
            if (getPage(position) == Page.IMAGES) {
                loadCacheImages();
            }
            requireGeodata = getPage(position) == Page.DETAILS;
            startOrStopGeoDataListener(false);

            // dispose contextual actions on page change
            if (currentActionMode != null) {
                currentActionMode.finish();
            }
        }
    });
    requireGeodata = pageToOpen == 1;

    final String realGeocode = geocode;
    final String realGuid = guid;
    AndroidRxUtils.networkScheduler.scheduleDirect(new Runnable() {
        @Override
        public void run() {
            search = Geocache.searchByGeocode(realGeocode, StringUtils.isBlank(realGeocode) ? realGuid : null,
                    false, loadCacheHandler);
            loadCacheHandler.sendMessage(Message.obtain());
        }
    });

    // Load Generic Trackables
    if (StringUtils.isNotBlank(geocode)) {
        AndroidRxUtils.bindActivity(this,
                // Obtain the active connectors and load trackables in parallel.
                Observable.fromIterable(ConnectorFactory.getGenericTrackablesConnectors())
                        .flatMap(new Function<TrackableConnector, Observable<Trackable>>() {
                            @Override
                            public Observable<Trackable> apply(final TrackableConnector trackableConnector) {
                                processedBrands.add(trackableConnector.getBrand());
                                return Observable.defer(new Callable<Observable<Trackable>>() {
                                    @Override
                                    public Observable<Trackable> call() {
                                        return Observable
                                                .fromIterable(trackableConnector.searchTrackables(geocode));
                                    }
                                }).subscribeOn(AndroidRxUtils.networkScheduler);
                            }
                        }).toList())
                .subscribe(new Consumer<List<Trackable>>() {
                    @Override
                    public void accept(final List<Trackable> trackables) {
                        // Todo: this is not really a good method, it may lead to duplicates ; ie: in OC connectors.
                        // Store trackables.
                        genericTrackables.addAll(trackables);
                        if (!trackables.isEmpty()) {
                            // Update the UI if any trackables were found.
                            notifyDataSetChanged();
                        }
                    }
                });
    }

    locationUpdater = new CacheDetailsGeoDirHandler(this);

    // If we have a newer Android device setup Android Beam for easy cache sharing
    AndroidBeam.enable(this, this);
}

From source file:de.qspool.clementineremote.ui.fragments.PlaylistFragment.java

private void playSong(MySong song) {
    Message msg = Message.obtain();
    msg.obj = ClementineMessageFactory.buildRequestChangeSong(song.getIndex(), getPlaylistId());
    App.ClementineConnection.mHandler.sendMessage(msg);

    mPlaylistManager.setActivePlaylist(getPlaylistId());
}

From source file:org.sufficientlysecure.keychain.ui.dialog.AddEditKeyserverDialogFragment.java

/**
 * Send message back to handler which is initialized in a activity
 *
 * @param what Message integer you want to send
 *///from  www  .  j  a va  2  s . c  om
private void sendMessageToHandler(Integer what, Bundle data) {
    Message msg = Message.obtain();
    msg.what = what;
    if (data != null) {
        msg.setData(data);
    }

    try {
        mMessenger.send(msg);
    } catch (RemoteException e) {
        Log.w(Constants.TAG, "Exception sending message, Is handler present?", e);
    } catch (NullPointerException e) {
        Log.w(Constants.TAG, "Messenger is null!", e);
    }
}

From source file:com.softanalle.scma.MainActivity.java

private void takeColorSeries() {
    logger.debug("takeColorSeries()");
    logger.debug("imageSequence started");

    mLedState[mFocusLedIndex] = false;/*w w  w  .  j av  a  2s  . com*/
    mPulseWidth[mFocusLedIndex] = mDefaultPulseWidth[mFocusLedIndex];

    try {
        mImagePrefix = Long.toString(System.currentTimeMillis());

        for (int index = 0; index < mLedCount; index++) {

            synchronized (lock_) {
                mCurrentLedIndex = index;
                mLedState[index] = true;
                mPulseWidth[index] = mDefaultPulseWidth[index];
            }

            Thread.sleep(mLedWaitDelay);

            String imageFilename = mStorageDir + "/" + mImagePrefix + "_" + mImageSuffix[index];

            mPreview.startPreview();

            logger.debug("Take picture: " + imageFilename);
            //logger.debug("--store JPG: " + saveModeJPEG);
            logger.debug("--store RAW info: " + saveModeRAW);
            mPreview.takePicture(saveModeRAW, imageFilename);
            /*
            if ( saveModeJPEG ) {
               Thread.sleep(mRawPictureDelay);
            }
            */
            // Thread.sleep(mLedWaitDelay);

            if (saveModeRAW) {
                Thread.sleep(mRawPictureDelay);
            }

            Thread.sleep(mCameraRetryDelay);

            Message m = Message.obtain();
            m.what = MSG_IMAGE_READY;
            _messagehandler.handleMessage(m);

            mPulseWidth[index] = 0;
            mLedState[index] = false;

            // sleep till leds are really turned off
            Thread.sleep(mLedWaitDelay);
        }

        synchronized (lock_) {
            mShutdown = true;

        }

        powerState_ = false;
        mImageSequenceComplete = true;
        logger.debug("Image sequence completed.");
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    if (mImageSequenceComplete) {
        logger.debug("Image sequence completed - 2");
        ledIndicator_.setPowerState(false);
        toggleButton_.setChecked(false);
        pictureButton_.setEnabled(false);
        focusButton_.setEnabled(true);
        powerLedsOff();
        mPreview.stopPreview();

        openImageAreaSelector();
    }

}

From source file:de.qspool.clementineremote.ui.fragments.LibraryFragment.java

private void addSongsToPlaylist(LinkedList<SongSelectItem> l) {
    Message msg = Message.obtain();
    LinkedList<String> urls = new LinkedList<>();
    for (SongSelectItem item : l) {
        urls.add(item.getUrl());//from ww  w  .  ja va2s . c  o  m
    }

    msg.obj = ClementineMessageFactory.buildInsertUrl(App.Clementine.getPlaylistManager().getActivePlaylistId(),
            urls);

    App.ClementineConnection.mHandler.sendMessage(msg);

    String text = getActivity().getResources().getQuantityString(R.plurals.songs_added, urls.size(),
            urls.size());
    Toast.makeText(getActivity(), text, Toast.LENGTH_SHORT).show();
}

From source file:com.gelakinetic.mtgfam.activities.MainActivity.java

public void showDialogFragment(final int id) {
    // DialogFragment.show() will take care of adding the fragment
    // in a transaction. We also want to remove any currently showing
    // dialog, so make our own transaction and take care of that here.
    this.showContent();
    FragmentTransaction ft = this.getSupportFragmentManager().beginTransaction();
    Fragment prev = getSupportFragmentManager().findFragmentByTag(FamiliarFragment.DIALOG_TAG);
    if (prev != null) {
        ft.remove(prev);//from ww w .j  ava2 s . c  o m
    }

    // Create and show the dialog.
    FamiliarDialogFragment newFragment = new FamiliarDialogFragment() {

        @Override
        public void onDismiss(DialogInterface mDialog) {
            super.onDismiss(mDialog);
            if (bounceMenu) {
                getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
                bounceMenu = false;
                Runnable r = new Runnable() {

                    @Override
                    public void run() {
                        long timeStarted = System.currentTimeMillis();
                        Message msg = Message.obtain();
                        msg.arg1 = OPEN;
                        bounceHandler.sendMessage(msg);
                        while (System.currentTimeMillis() < (timeStarted + 1500)) {
                            ;
                        }
                        msg = Message.obtain();
                        msg.arg1 = CLOSE;
                        bounceHandler.sendMessage(msg);
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED);
                            }
                        });
                    }
                };

                Thread t = new Thread(r);
                t.start();
            }
        }

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            switch (id) {
            case DONATEDIALOG: {
                AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
                builder.setTitle(R.string.main_donate_dialog_title);
                builder.setNeutralButton(R.string.dialog_thanks_anyway, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });

                LayoutInflater inflater = this.getActivity().getLayoutInflater();
                View dialoglayout = inflater.inflate(R.layout.about_dialog,
                        (ViewGroup) findViewById(R.id.dialog_layout_root));

                TextView text = (TextView) dialoglayout.findViewById(R.id.aboutfield);
                text.setText(ImageGetterHelper.jellyBeanHack(getString(R.string.main_donate_text)));
                text.setMovementMethod(LinkMovementMethod.getInstance());

                text.setTextSize(15);

                ImageView paypal = (ImageView) dialoglayout.findViewById(R.id.imageview1);
                paypal.setImageResource(R.drawable.paypal);
                paypal.setOnClickListener(new View.OnClickListener() {

                    public void onClick(View v) {
                        Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(
                                "https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=SZK4TAH2XBZNC&lc=US&item_name=MTG%20Familiar&currency_code=USD&bn=PP%2dDonationsBF%3abtn_donate_LG%2egif%3aNonHosted"));

                        startActivity(myIntent);
                    }
                });
                ((ImageView) dialoglayout.findViewById(R.id.imageview2)).setVisibility(View.GONE);

                builder.setView(dialoglayout);
                return builder.create();
            }
            case ABOUTDIALOG: {
                AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());

                // You have to catch the exception because the package stuff is all
                // run-time
                if (pInfo != null) {
                    builder.setTitle(getString(R.string.main_about) + " " + getString(R.string.app_name) + " "
                            + pInfo.versionName);
                } else {
                    builder.setTitle(getString(R.string.main_about) + " " + getString(R.string.app_name));
                }

                builder.setNeutralButton(R.string.dialog_thanks, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });

                LayoutInflater inflater = this.getActivity().getLayoutInflater();
                View dialoglayout = inflater.inflate(R.layout.about_dialog,
                        (ViewGroup) findViewById(R.id.dialog_layout_root));

                TextView text = (TextView) dialoglayout.findViewById(R.id.aboutfield);
                text.setText(ImageGetterHelper.jellyBeanHack(getString(R.string.main_about_text)));
                text.setMovementMethod(LinkMovementMethod.getInstance());

                builder.setView(dialoglayout);
                return builder.create();
            }
            case CHANGELOGDIALOG: {
                AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());

                if (pInfo != null) {
                    builder.setTitle(getString(R.string.main_whats_new_in_title) + " " + pInfo.versionName);
                } else {
                    builder.setTitle(R.string.main_whats_new_title);
                }

                builder.setNeutralButton(R.string.dialog_enjoy, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });

                builder.setMessage(ImageGetterHelper.jellyBeanHack(getString(R.string.main_whats_new_text)));
                return builder.create();
            }
            default: {
                savedInstanceState.putInt("id", id);
                return super.onCreateDialog(savedInstanceState);
            }
            }
        }
    };
    newFragment.show(ft, FamiliarFragment.DIALOG_TAG);
}

From source file:org.ymkm.lib.controller.support.ControlledDialogFragment.java

/**
 * Sends a message to the controller via its supplied {@link Messenger}
 * <p>//ww  w.ja  v a2s.  com
 * A {@link ControlledDialogFragment} can only communicate with the
 * {@link FragmentController}.
 * </p>
 * The sent message wraps the actual message that will be dispatched by the
 * controller, and has the following values :
 * <dl>
 * <dt>what</dt>
 * <dd>{@link FragmentController#MSG_DISPATCH_MESSAGE} => Dispatches the
 * message in the controller</dd>
 * <dt>arg1</dt>
 * <dd>The control ID assigned to the ControlledDialogFragment that owns this
 * callback</dd>
 * <dt>arg2</dt>
 * <dd>The {@code what} passed as a parameter that needs to be dispatched</dd>
 * <dt>obj</dt>
 * <dd>{@link Message} that will get dispatched (the {@code what} will be
 * added to it)</dd>
 * </dl>
 * obj is a message instance that will eventually contain what, arg1, arg2,
 * obj passed as parameters of this method.<br>
 * 
 * @param what
 *            message ID to get dispatched by the controller
 * @param arg1
 *            first message int argument
 * @param arg2
 *            second message int argment
 * @param obj
 *            Object argument
 * @return {@code true} if message could be sent, {@code false} otherwise
 */
@Override
public final boolean sendToController(int what, int arg1, int arg2, Object obj) {
    if (null != mControllerMessenger) {
        Message m = Message.obtain();
        m.what = FragmentController.MSG_DISPATCH_MESSAGE;
        m.arg1 = getControlId();
        m.arg2 = what;
        m.obj = FragmentController.CallbackMessage.obtain(arg1, arg2, obj);
        Bundle b = new Bundle();
        b.putString("controllableName", mControllableName);
        m.setData(b);
        try {
            mControllerMessenger.send(m);
        } catch (RemoteException e) {
            e.printStackTrace();
            return false;
        }
    }
    return true;
}