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:mp.teardrop.LibraryActivity.java

/**
 * Called when a new page becomes visible.
 *
 * @param position The position of the new page.
 * @param adapter  The new visible adapter.
 *///from   ww w .j  a v  a 2  s .co  m
public void onPageChanged(int position, LibraryAdapter adapter) {
    mLastActedId = LibraryAdapter.INVALID_ID;
    updateLimiterViews();
    if (adapter != null && adapter.getLimiter() == null) { //TODO: this may not be working at the moment, fix it
        // Save current page so it is opened on next startup. Don't save if
        // the page was expanded to, as the expanded page isn't the starting
        // point.
        Handler handler = mHandler;
        handler.sendMessage(mHandler.obtainMessage(MSG_SAVE_PAGE, position, 0));
    }
}

From source file:org.planetmono.dcuploader.SignOnGallog.java

public Runnable getMethodSignOn(final Application app, final Bundle b, final Handler resultHandler) {
    return new Runnable() {
        public void run() {
            String id, password;/*from   w w w  .  ja  va 2  s .c  o m*/

            id = b.getString("id");
            password = b.getString("password");

            Message m = resultHandler.obtainMessage();
            Bundle bm = m.getData();

            Log.d(Application.TAG, "logging in...");

            HttpPost post = new HttpPost(SIGNON_URL);
            List<NameValuePair> vlist = new ArrayList<NameValuePair>();
            vlist.add(new BasicNameValuePair("user_id", id));
            vlist.add(new BasicNameValuePair("password", password));
            vlist.add(new BasicNameValuePair("x", "0"));
            vlist.add(new BasicNameValuePair("y", "0"));
            vlist.add(new BasicNameValuePair("s_url", "about:blank"));
            try {
                post.setEntity(new UrlEncodedFormEntity(vlist));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            post.setHeader("Origin", SIGNON_BASE_URL);
            post.setHeader("Referer", SIGNON_PAGE_URL);

            HttpResponse response = null;
            try {
                response = app.sendPostRequest(post);
            } catch (Exception e) {
                e.printStackTrace();

                bm.putBoolean("result", false);
                bm.putString("resultString", " ");
                resultHandler.sendMessage(m);
                return;
            }

            HttpEntity entity = response.getEntity();
            BufferedReader r;
            try {
                r = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));

                while (true) {
                    String line = r.readLine();
                    if (line == null)
                        break;

                    if (line.contains(" ")
                            || line.contains("?? ? ")) {
                        bm.putBoolean("result", false);
                        bm.putString("resultString", "? ");
                        resultHandler.sendMessage(m);
                        entity.consumeContent();
                        return;
                    } else if (line.contains("about:blank")) {
                        /* successful */
                        bm.putBoolean("result", true);
                        bm.putInt("method", getMethodId());
                        resultHandler.sendMessage(m);
                        entity.consumeContent();
                        return;
                    }
                }
            } catch (Exception e) {
                bm.putBoolean("result", false);
                bm.putString("resultString", " ");
                resultHandler.sendMessage(m);

                try {
                    entity.consumeContent();
                } catch (IOException e1) {
                }

                return;
            }

            try {
                entity.consumeContent();
            } catch (IOException e) {
            }

            /* abnormal status. */
            bm.putBoolean("result", false);
            bm.putString("resultString", "   .");
            resultHandler.sendMessage(m);
        }
    };
}

From source file:com.qddagu.app.meetreader.ui.MainActivity.java

/**
 * ?/*ww w  .ja v a2 s . c o  m*/
 * @param handler
 */
public void loadMeeting(final String url) {
    final ProgressDialog mLoadingDialog = new ProgressDialog(this);
    mLoadingDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    mLoadingDialog.setTitle("??");
    mLoadingDialog.setMessage("??...");
    mLoadingDialog.setCancelable(false);
    mLoadingDialog.show();
    final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            mLoadingDialog.dismiss();
            if (msg.what == 1) { //?
                Meeting meeting = ((Meeting) msg.obj);
                User user = meeting.getUser();
                if (user != null) {
                    //??
                    appContext.saveUserInfo(user);
                }
                appContext.setMeeting(meeting);//?
                appContext.saveHistory(meeting);//??

                UIHelper.showMeeting(MainActivity.this);
            } else if (msg.what == 0) { //
                UIHelper.ToastMessage(MainActivity.this, "");
            } else if (msg.what == -1 && msg.obj != null) {
                ((AppException) msg.obj).makeToast(MainActivity.this);
            }
        }
    };
    new Thread() {
        public void run() {
            Message msg = new Message();
            try {
                Meeting meeting = appContext.getMeeting(url);
                msg.what = (meeting != null && meeting.getId() > 0) ? 1 : 0;
                msg.obj = meeting;
            } catch (AppException e) {
                e.printStackTrace();
                msg.what = -1;
                msg.obj = e;
            }
            handler.sendMessage(msg);
        }
    }.start();
}

From source file:org.planetmono.dcuploader.SignOnRealName.java

public Runnable getMethodSignOn(final Application app, final Bundle b, final Handler resultHandler) {
    return new Runnable() {
        public void run() {
            Message m = resultHandler.obtainMessage();
            Bundle bm = m.getData();/* www  .j av  a2s.  c  o m*/

            Log.d("dcuploader", "authenticating...");

            String encdata = b.getString("enc_data");
            String name = b.getString("name");
            String code1 = b.getString("code1");
            String code2 = b.getString("code2");

            HttpPost post = new HttpPost(AUTH_URL);
            List<NameValuePair> vlist = new ArrayList<NameValuePair>();
            vlist.add(new BasicNameValuePair("enc_data", encdata));
            vlist.add(new BasicNameValuePair("result_code", "1"));
            vlist.add(new BasicNameValuePair("contract_type", "S"));
            vlist.add(new BasicNameValuePair("au_chk", "F"));
            vlist.add(new BasicNameValuePair("name", name));
            vlist.add(new BasicNameValuePair("juminid1", code1));
            vlist.add(new BasicNameValuePair("juminid2", code2));
            try {
                post.setEntity(new UrlEncodedFormEntity(vlist));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            HttpResponse response = null;
            try {
                response = app.sendPostRequest(post);
            } catch (Exception e) {
                e.printStackTrace();

                bm.putBoolean("result", false);
                bm.putString("resultString", " ");
                resultHandler.sendMessage(m);
                return;
            }

            HttpEntity entity = response.getEntity();
            BufferedReader r;
            try {
                r = new BufferedReader(new InputStreamReader(entity.getContent(), "EUC-KR"));

                while (true) {
                    String line = r.readLine();
                    if (line == null)
                        break;

                    if (line.contains(" ??  ")) {
                        bm.putBoolean("result", false);
                        bm.putString("resultString", "?? ");
                        resultHandler.sendMessage(m);
                        return;
                    }
                }
            } catch (Exception e) {
                bm.putBoolean("result", false);
                bm.putString("resultString", " ");
                resultHandler.sendMessage(m);

                return;
            }

            /* abnormal status. traffic limit exceeded? */
            bm.putBoolean("result", true);
            resultHandler.sendMessage(m);
        }
    };
}

From source file:com.tcl.lzhang1.mymusic.ui.MusicListAcitivity.java

/**
 * load data//from  ww  w .  j  a v a 2 s .co m
 * 
 * @param pageIndex
 * @param pageSize
 * @param tag
 * @param orderCol
 * @param handler
 */
public void loadData(final int pageIndex, final int pageSize, final int tag, final String orderCol,
        final Handler handler) {
    new Thread(new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            Message message = handler.obtainMessage();
            try {
                if (tag == UIHelper.LISTVIEW_ACTION_REFRESH) {// scan music

                }

                @SuppressWarnings("unchecked")
                List<SongModel> msongs = (List<SongModel>) mDbOperator.sliptPage(pageIndex, pageSize, orderCol);
                message.what = LOADDATA_SUCCESS;
                message.obj = msongs;
                message.arg1 = msongs.size();
                message.arg2 = tag;
                handler.sendMessage(message);
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
                handler.sendEmptyMessage(LOADDATA_FAILED);
            }

        }
    }).start();
}

From source file:com.norman0406.slimgress.API.Game.GameState.java

public synchronized void intHandshake(final Handler handler) {
    mInterface.handshake(new Handshake.Callback() {
        @Override/*  ww w  .ja  va2  s  . c  o  m*/
        public void handle(Handshake handshake) {
            mHandshake = handshake;
            mKnobs = mHandshake.getKnobs();

            Message msg = new Message();
            Bundle bundle = new Bundle();
            bundle.putBoolean("Successful", mHandshake.isValid());

            if (!mHandshake.isValid()) {
                String errString;
                if (mHandshake.getPregameStatus() == Handshake.PregameStatus.ClientMustUpgrade)
                    errString = "Client must upgrade";
                else if (mHandshake.getAgent() == null)
                    errString = "Invalid agent data";
                else
                    errString = "Unknown error";

                bundle.putString("Error", errString);
            }

            msg.setData(bundle);
            handler.sendMessage(msg);
        }
    });
}

From source file:com.zia.freshdocs.widget.CMISAdapter.java

/**
 * Download the content for the given NodeRef
 * @param ref//from  w  ww .j a  va  2  s  . c o m
 * @param handler
 */
protected void downloadContent(final NodeRef ref, final Handler handler) {
    startProgressDlg(false);
    _progressDlg.setMax(Long.valueOf(ref.getContentLength()).intValue());

    _dlThread = new ChildDownloadThread(handler, new Downloadable() {
        public Object execute() {
            File f = null;

            try {
                CMISApplication app = (CMISApplication) getContext().getApplicationContext();
                URL url = new URL(ref.getContent());
                String name = ref.getName();
                long fileSize = ref.getContentLength();
                f = app.getFile(name, fileSize);

                if (f != null && f.length() != fileSize) {
                    Thread.currentThread().setPriority(Thread.MIN_PRIORITY);

                    FileOutputStream fos = new FileOutputStream(f);
                    InputStream is = _cmis.get(url.getPath());

                    byte[] buffer = new byte[BUF_SIZE];
                    int len = is.read(buffer);
                    int total = len;
                    Message msg = null;
                    Bundle b = null;

                    while (len != -1) {
                        msg = handler.obtainMessage();
                        b = new Bundle();
                        b.putInt("progress", total);
                        msg.setData(b);
                        handler.sendMessage(msg);

                        fos.write(buffer, 0, len);
                        len = is.read(buffer);
                        total += len;

                        if (Thread.interrupted()) {
                            fos.close();
                            f = null;
                            throw new InterruptedException();
                        }
                    }

                    fos.flush();
                    fos.close();
                }
            } catch (Exception e) {
                Log.e(CMISAdapter.class.getSimpleName(), "", e);
            }

            return f;
        }
    });
    _dlThread.start();
}

From source file:com.zia.freshdocs.widget.adapter.CMISAdapter.java

/**
 * Download the content for the given NodeRef
 * /*from   w  w w.  j a va2s .co  m*/
 * @param ref
 * @param handler
 */
protected void downloadContent(final NodeRef ref, final Handler handler) {
    startProgressDlg(false);
    mProgressDlg.setMax(Long.valueOf(ref.getContentLength()).intValue());

    mDlThread = new ChildDownloadThread(handler, new Downloadable() {
        public Object execute() {
            File f = null;

            try {
                CMISApplication app = (CMISApplication) getContext().getApplicationContext();
                URL url = new URL(ref.getContent());
                String name = ref.getName();
                long fileSize = ref.getContentLength();
                f = app.getFile(name, fileSize);

                if (f != null && f.length() != fileSize) {
                    Thread.currentThread().setPriority(Thread.MIN_PRIORITY);

                    FileOutputStream fos = new FileOutputStream(f);
                    InputStream is = mCmis.get(url.getPath());

                    byte[] buffer = new byte[BUF_SIZE];
                    int len = is.read(buffer);
                    int total = len;
                    Message msg = null;
                    Bundle b = null;

                    while (len != -1) {
                        msg = handler.obtainMessage();
                        b = new Bundle();
                        b.putInt("progress", total);
                        msg.setData(b);
                        handler.sendMessage(msg);

                        fos.write(buffer, 0, len);
                        len = is.read(buffer);
                        total += len;

                        if (Thread.interrupted()) {
                            fos.close();
                            f = null;
                            throw new InterruptedException();
                        }
                    }

                    fos.flush();
                    fos.close();
                }
            } catch (Exception e) {
                Log.e(CMISAdapter.class.getSimpleName(), "", e);
            }

            return f;
        }
    });
    mDlThread.start();
}

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

/**
 * Sets the RESULT_OK intent. Adds the recorded audio data if the caller has requested it
 * and the requested format is supported or unset.
 *//*ww  w  .  j av a  2s.co  m*/
private void setResultIntent(final Handler handler, ArrayList<String> matches) {
    Intent intent = new Intent();
    if (mExtras.getBoolean(Extras.GET_AUDIO)) {
        String audioFormat = mExtras.getString(Extras.GET_AUDIO_FORMAT);
        if (audioFormat == null) {
            audioFormat = Constants.DEFAULT_AUDIO_FORMAT;
        }
        if (Constants.SUPPORTED_AUDIO_FORMATS.contains(audioFormat)) {
            try {
                FileOutputStream fos = openFileOutput(Constants.AUDIO_FILENAME, Context.MODE_PRIVATE);
                fos.write(mService.getCompleteRecordingAsWav());
                fos.close();

                Uri uri = Uri
                        .parse("content://" + FileContentProvider.AUTHORITY + "/" + Constants.AUDIO_FILENAME);
                // TODO: not sure about the type (or if it's needed)
                intent.setDataAndType(uri, audioFormat);
            } catch (FileNotFoundException e) {
                Log.e(LOG_TAG, "FileNotFoundException: " + e.getMessage());
            } catch (IOException e) {
                Log.e(LOG_TAG, "IOException: " + e.getMessage());
            }
        } else {
            if (Log.DEBUG) {
                handler.sendMessage(createMessage(MSG_TOAST,
                        String.format(getString(R.string.toastRequestedAudioFormatNotSupported), audioFormat)));
            }
        }
    }
    intent.putStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS, matches);
    setResult(Activity.RESULT_OK, intent);
}

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

/**
 * /*  w  ww  . j a  va  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 setLikeDictNameByValueToView(final String url, 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(url, 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();

}