Example usage for android.os Handler sendMessage

List of usage examples for android.os Handler sendMessage

Introduction

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

Prototype

public final boolean sendMessage(Message msg) 

Source Link

Document

Pushes a message onto the end of the message queue after all pending messages before the current time.

Usage

From source file:net.evecom.androidecssp.base.BaseActivity.java

/**
 * //from   ww w.  java  2  s .c  o m
 *  dictValue dictKey TextViewDictName
 * 
 * @author Mars zhang
 * @created 2015-11-25 9:50:55
 * @param dictKey
 * @param value
 * @param view
 */
protected void setDictNameByValueToView(final String dictKey, final String dictValue, final TextView view) {
    final Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
            case MESSAGETYPE_01:
                view.setText(msg.getData().getString("dictname"));
                break;
            default:
                break;
            }
        };
    };
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                HashMap<String, String> entityMap = new HashMap<String, String>();
                entityMap.put("dictkey", dictKey);
                String result = connServerForResultPost("jfs/ecssp/mobile/pubCtr/getDictByKey", entityMap);
                List<BaseModel> baseModels = getObjsInfo(result);
                HashMap<String, String> keyValehashmap = new HashMap<String, String>();
                for (int i = 0; i < baseModels.size(); i++) {
                    keyValehashmap.put(baseModels.get(i).get("dictvalue") + "",
                            baseModels.get(i).get("name") + "");
                }
                String dictname = ifnull(keyValehashmap.get(dictValue), "");
                Message message = new Message();
                Bundle mbundle = new Bundle();
                mbundle.putString("dictname", dictname);
                message.setData(mbundle);
                message.what = MESSAGETYPE_01;
                mHandler.sendMessage(message);
            } catch (ClientProtocolException e) {
                Log.v("mars", e.getMessage());
            } catch (IOException e) {
                Log.v("mars", e.getMessage());
            } catch (JSONException e) {
                Log.v("mars", e.getMessage());
            }
        }
    }).start();

}

From source file:com.google.ytd.SubmitActivity.java

public void asyncUpload(final Uri uri, final Handler handler) {
    new Thread(new Runnable() {
        @Override/*from   w w w. j  a  v  a 2 s .  c  o m*/
        public void run() {
            Message msg = new Message();
            Bundle bundle = new Bundle();
            msg.setData(bundle);

            String videoId = null;
            int submitCount = 0;
            try {
                while (submitCount <= MAX_RETRIES && videoId == null) {
                    try {
                        submitCount++;
                        videoId = startUpload(uri);
                        assert videoId != null;
                    } catch (Internal500ResumeException e500) { // TODO - this should not really happen
                        if (submitCount < MAX_RETRIES) {
                            Log.w(LOG_TAG, e500.getMessage());
                            Log.d(LOG_TAG, String.format("Upload retry :%d.", submitCount));
                        } else {
                            Log.d(LOG_TAG, "Giving up");
                            Log.e(LOG_TAG, e500.getMessage());
                            throw new IOException(e500.getMessage());
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
                bundle.putString("error", e.getMessage());
                handler.sendMessage(msg);
                return;
            } catch (YouTubeAccountException e) {
                e.printStackTrace();
                bundle.putString("error", e.getMessage());
                handler.sendMessage(msg);
                return;
            } catch (SAXException e) {
                e.printStackTrace();
                bundle.putString("error", e.getMessage());
                handler.sendMessage(msg);
            } catch (ParserConfigurationException e) {
                e.printStackTrace();
                bundle.putString("error", e.getMessage());
                handler.sendMessage(msg);
            }

            bundle.putString("videoId", videoId);
            handler.sendMessage(msg);
        }
    }).start();
}

From source file:com.sharpcart.android.wizardpager.SharpCartLoginActivity.java

public void checkIfRegistered(final String email, final String password) {
    final Handler handler = new Handler() {
        @Override//from w  w w .  ja  v  a  2  s  .com
        public void handleMessage(final Message msg) {
            final Bundle bundle = msg.getData();
            isRegistered = bundle.getBoolean("isRegistered");

            //if the user is already registered, go back to first screen and let the user know
            if (isRegistered) {
                mPager.setCurrentItem(0);
                Toast.makeText(mContext, "You already have an account", Toast.LENGTH_SHORT).show();
            }
        }
    };

    final Runnable runnable = new Runnable() {
        @Override
        public void run() {
            final Message msg = handler.obtainMessage();
            boolean isRegistered = false;
            try {
                //before we perform a login we check that there is an Internet connection
                if (SharpCartUtilities.getInstance()
                        .hasActiveInternetConnection(SharpCartApplication.getAppContext())) {
                    final String response = LoginServiceImpl.sendCredentials(email, password);

                    if (response.equalsIgnoreCase(SharpCartConstants.SUCCESS)
                            || response.equalsIgnoreCase(SharpCartConstants.USER_EXISTS_IN_DB_CODE))
                        isRegistered = true;
                    else
                        isRegistered = false;
                }

            } catch (final SharpCartException e) {

            }

            final Bundle bundle = new Bundle();
            bundle.putBoolean("isRegistered", isRegistered);
            msg.setData(bundle);
            handler.sendMessage(msg);
        }
    };

    final Thread mythread = new Thread(runnable);
    mythread.start();

}

From source file:ee.ioc.phon.android.speak.RecognizerIntentActivity.java

/**
 * <p>Returns the transcription results (matches) to the caller,
 * or sends them to the pending intent, or performs a web search.</p>
 *
 * <p>If a pending intent was specified then use it. This is the case with
 * applications that use the standard search bar (e.g. Google Maps and YouTube).</p>
 *
 * <p>Otherwise. If there was no caller (i.e. we cannot return the results), or
 * the caller asked us explicitly to perform "web search", then do that, possibly
 * disambiguating the results or redoing the recognition.
 * This is the case when K6nele was launched from its launcher icon (i.e. no caller),
 * or from a browser app./*w  w  w.  j  a v a2  s .  c  om*/
 * (Note that trying to return the results to Google Chrome does not seem to work.)</p>
 *
 * <p>Otherwise. Just return the results to the caller.</p>
 *
 * <p>Note that we assume that the given list of matches contains at least one
 * element.</p>
 *
 * @param handler message handler
 * @param matches transcription results (one or more hypotheses)
 */
private void returnOrForwardMatches(final Handler handler, ArrayList<String> matches) {
    // Throw away matches that the user is not interested in
    int maxResults = mExtras.getInt(RecognizerIntent.EXTRA_MAX_RESULTS);
    if (maxResults > 0 && matches.size() > maxResults) {
        matches.subList(maxResults, matches.size()).clear();
    }

    if (mExtraResultsPendingIntent == null) {
        if (getCallingActivity() == null || RecognizerIntent.ACTION_WEB_SEARCH.equals(getIntent().getAction())
                || mExtras.getBoolean(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY)) {
            handleResultsByWebSearch(this, handler, matches);
            return;
        } else {
            setResultIntent(handler, matches);
        }
    } else {
        Bundle bundle = mExtras.getBundle(RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT_BUNDLE);
        if (bundle == null) {
            bundle = new Bundle();
        }
        String match = matches.get(0);
        //mExtraResultsPendingIntentBundle.putString(SearchManager.QUERY, match);
        Intent intent = new Intent();
        intent.putExtras(bundle);
        // This is for Google Maps, YouTube, ...
        intent.putExtra(SearchManager.QUERY, match);
        // This is for SwiftKey X, ...
        intent.putStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS, matches);
        String message = "";
        if (matches.size() == 1) {
            message = match;
        } else {
            message = matches.toString();
        }
        // Display a toast with the transcription.
        handler.sendMessage(
                createMessage(MSG_TOAST, String.format(getString(R.string.toastForwardedMatches), message)));
        try {
            mExtraResultsPendingIntent.send(this, Activity.RESULT_OK, intent);
        } catch (CanceledException e) {
            handler.sendMessage(createMessage(MSG_TOAST, e.getMessage()));
        }
    }
    finish();
}

From source file:com.BeatYourRecord.SubmitActivity.java

public void asyncUpload(final Uri uri, final Handler handler) {
    new Thread(new Runnable() {
        @Override// w  w w  .  j  a v  a 2 s .  c  om
        public void run() {
            Message msg = new Message();
            Bundle bundle = new Bundle();
            msg.setData(bundle);

            String videoId = null;
            int submitCount = 0;
            try {
                while (submitCount <= MAX_RETRIES && videoId == null) {
                    try {
                        submitCount++;
                        videoId = startUpload(uri);
                        //log.v("please",videoId);
                        assert videoId != null;
                    } catch (Internal500ResumeException e500) { // TODO - this should not really happen
                        if (submitCount < MAX_RETRIES) {
                            Log.w(LOG_TAG, e500.getMessage());
                            Log.d(LOG_TAG, String.format("Upload retry :%d.", submitCount));
                        } else {
                            Log.d(LOG_TAG, "Giving up");
                            Log.e(LOG_TAG, e500.getMessage());
                            throw new IOException(e500.getMessage());
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
                bundle.putString("error", e.getMessage());
                handler.sendMessage(msg);
                return;
            } catch (YouTubeAccountException e) {
                e.printStackTrace();
                bundle.putString("error", e.getMessage());
                handler.sendMessage(msg);
                return;
            } catch (SAXException e) {
                e.printStackTrace();
                bundle.putString("error", e.getMessage());
                handler.sendMessage(msg);
            } catch (ParserConfigurationException e) {
                e.printStackTrace();
                bundle.putString("error", e.getMessage());
                handler.sendMessage(msg);
            }

            bundle.putString("videoId", videoId);
            handler.sendMessage(msg);
        }
    }).start();
}

From source file:com.max2idea.android.limbo.main.LimboActivity.java

public static void showAlertHtml(String title, String message, Handler handler) {
    Message msg1 = handler.obtainMessage();
    Bundle b = new Bundle();
    b.putInt("message_type", Const.UIUTILS_SHOWALERT_HTML);
    b.putString("title", title);
    b.putString("body", message);
    msg1.setData(b);/* w  ww  .  ja va  2 s  .c o  m*/
    handler.sendMessage(msg1);
}

From source file:com.max2idea.android.limbo.main.LimboActivity.java

public static void showAlertLicense(String title, String message, Handler handler) {
    Message msg1 = handler.obtainMessage();
    Bundle b = new Bundle();
    b.putInt("message_type", Const.UIUTILS_SHOWALERT_LICENSE);
    b.putString("title", title);
    b.putString("body", message);
    msg1.setData(b);/*from  w ww.  j a  va2  s  .  com*/
    handler.sendMessage(msg1);
}

From source file:com.max2idea.android.limbo.main.LimboActivity.java

public static void sendHandlerMessage(Handler handler, int message_type, String[] message_var,
        String[] message_value) {
    Message msg1 = handler.obtainMessage();
    Bundle b = new Bundle();
    b.putInt("message_type", message_type);
    for (int i = 0; i < message_var.length; i++) {
        b.putString(message_var[i], message_value[i]);
    }//from  w  ww . jav  a 2 s  .co m
    msg1.setData(b);
    handler.sendMessage(msg1);
}

From source file:com.android.providers.downloads.OmaDownload.java

/**
* This method notifies the server for the status of the download operation.
* It sends a status report to a Web server if installNotify attribute is specified in the download descriptor.
@param  component   the component that contains attributes in the descriptor.
@param  handler     the handler used to send and process messages. A message
                indicates whether the media object is available to the user
                or not (READY or DISCARD).
*//*from  w  ww  .  j a va 2s.c o  m*/
//protected static void installNotify (OmaDescription component, Handler handler) {
protected static int installNotify(OmaDescription component, Handler handler) {

    int ack = -1;
    int release = OmaStatusHandler.DISCARD;
    URL url = component.getInstallNotifyUrl();

    if (url != null) {
        DefaultHttpClient client = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost(url.toString());

        try {
            HttpParams params = postRequest.getParams();
            HttpProtocolParams.setUseExpectContinue(params, false);
            postRequest.setEntity(
                    new StringEntity(OmaStatusHandler.statusCodeToString(component.getStatusCode()) + "\n\r"));
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        client.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler() {
            @Override
            public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
                // TODO Auto-generated method stub
                Log.i("@M_" + Constants.LOG_OMA_DL, "Retry the request...");
                return (executionCount <= OmaStatusHandler.MAXIMUM_RETRY);
            }
        });

        try {
            HttpResponse response = client.execute(postRequest);

            if (response.getStatusLine() != null) {
                ack = response.getStatusLine().getStatusCode();

                //200-series response code
                if (ack == HttpStatus.SC_OK || ack == HttpStatus.SC_ACCEPTED || ack == HttpStatus.SC_CREATED
                        || ack == HttpStatus.SC_MULTI_STATUS
                        || ack == HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION || ack == HttpStatus.SC_NO_CONTENT
                        || ack == HttpStatus.SC_PARTIAL_CONTENT || ack == HttpStatus.SC_RESET_CONTENT) {
                    if (component.getStatusCode() == OmaStatusHandler.SUCCESS) {
                        release = OmaStatusHandler.READY;
                    }
                }

                final HttpEntity entity = response.getEntity();
                if (entity != null) {
                    InputStream inputStream = null;
                    try {
                        inputStream = entity.getContent();
                        if (inputStream != null) {
                            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));

                            String s;
                            while ((s = br.readLine()) != null) {
                                Log.v("@M_" + Constants.LOG_OMA_DL, "Response: " + s);
                            }
                        }

                    } finally {
                        if (inputStream != null) {
                            inputStream.close();
                        }
                        entity.consumeContent();
                    }
                }
            }
        } catch (ConnectTimeoutException e) {
            Log.e("@M_" + Constants.LOG_OMA_DL, e.toString());
            postRequest.abort();
            //After time out period, the client releases the media object for use.
            if (component.getStatusCode() == OmaStatusHandler.SUCCESS) {
                release = OmaStatusHandler.READY;
            }
        } catch (NoHttpResponseException e) {
            Log.e("@M_" + Constants.LOG_OMA_DL, e.toString());
            postRequest.abort();
            //After time out period, the client releases the media object for use.
            if (component.getStatusCode() == OmaStatusHandler.SUCCESS) {
                release = OmaStatusHandler.READY;
            }
        } catch (IOException e) {
            Log.e("@M_" + Constants.LOG_OMA_DL, e.toString());
            postRequest.abort();
        }
        if (client != null) {
            client.getConnectionManager().shutdown();
        }
    } else {
        if (component.getStatusCode() == OmaStatusHandler.SUCCESS) {
            release = OmaStatusHandler.READY;
        }
    }

    if (handler != null) {
        Message mg = Message.obtain();
        mg.arg1 = release;
        handler.sendMessage(mg);
    }
    return release;
}

From source file:cgeo.geocaching.cgBase.java

public static void dropCache(cgeoapplication app, Activity activity, cgCache cache, Handler handler) {
    try {//from  w w w .j a  v  a  2  s  .  c  o  m
        app.markDropped(cache.geocode);
        app.removeCacheFromCache(cache.geocode);

        handler.sendMessage(new Message());
    } catch (Exception e) {
        Log.e(cgSettings.tag, "cgBase.dropCache: " + e.toString());
    }
}