Example usage for android.os Handler obtainMessage

List of usage examples for android.os Handler obtainMessage

Introduction

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

Prototype

public final Message obtainMessage() 

Source Link

Document

Returns a new android.os.Message Message from the global message pool.

Usage

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;// w w  w. ja v a  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:org.planetmono.dcuploader.SignOnGallog.java

public Runnable getMethodSignOff(final Application app, final Handler resultHandler) {
    return new Runnable() {
        public void run() {
            HttpGet get = new HttpGet(SIGNOFF_URL + "?s_url=about:blank");
            try {
                app.sendGetRequest(get);
            } catch (Exception e) {
                e.printStackTrace();//from  ww w.j a  v a2 s .c om
            }

            Message m = resultHandler.obtainMessage();
            m.getData().putBoolean("result", true);
            resultHandler.handleMessage(m);
        }
    };
}

From source file:de.jerleo.samsung.knox.firewall.MainActivity.java

private void applyRules() {

    // Get context
    final Context context = this;

    // Show progress
    final ProgressDialog progress = new ProgressDialog(this);

    // Finish message
    final Toast completed = Toast.makeText(this, getString(R.string.firewall_rules_complete),
            Toast.LENGTH_SHORT);// w w  w  .j a  va 2s . co  m
    progress.setIndeterminate(true);
    progress.setProgress(0);
    progress.show();

    // Handler to dismiss progress
    @SuppressLint("HandlerLeak")
    final Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            super.handleMessage(msg);
            progress.dismiss();
            completed.show();
        }
    };

    // Apply firewall rules
    new Thread(new Runnable() {

        @Override
        public void run() {

            progress.setMessage(getString(R.string.firewall_rules_create));
            Firewall.createRules(context);
            handler.sendMessage(handler.obtainMessage());
        }
    }).start();
}

From source file:net.evecom.androidecssp.activity.pub.imagescan.NativeImageLoader.java

/**
 * mPointImageViewImageViewBitmap/*from   www . java2 s  .c om*/
 * loadNativeImage(final String path, final NativeImageCallBack
 * mCallBack)
 * 
 * @param path
 * @param mPoint
 * @param mCallBack
 * @return
 */
public Bitmap loadNativeImage(final String path, final Point mPoint, final NativeImageCallBack mCallBack) {
    // Bitmap
    Bitmap bitmap = getBitmapFromMemCache(path);

    final Handler mHander = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            mCallBack.onImageLoader((Bitmap) msg.obj, path);
        }

    };

    // BitmapBitmapmMemoryCache
    if (bitmap == null) {
        mImageThreadPool.execute(new Runnable() {

            @Override
            public void run() {
                // 
                Bitmap mBitmap = decodeThumbBitmapForFile(path, mPoint == null ? 0 : mPoint.x,
                        mPoint == null ? 0 : mPoint.y);
                Message msg = mHander.obtainMessage();
                msg.obj = mBitmap;
                mHander.sendMessage(msg);

                // 
                addBitmapToMemoryCache(path, mBitmap);
            }
        });
    }
    return bitmap;

}

From source file:com.dv.BitMap.Native.DvNativeImageLoader.java

/**
 * ?mPoint??ImageView?ImageView???Bitmap
 * ??loadNativeImage(final String path, final NativeImageCallBack mCallBack)?
 *
 * @param path/*from ww  w  .j a v a2  s  .c  om*/
 * @param mPoint
 * @param mCallBack
 * @return
 */
public Bitmap loadNativeImage(final String path, final Point mPoint, final DvNativeImageCallBack mCallBack) {

    // ?Bitmap
    Bitmap bitmap = getBitmapFromMemCache(path);
    final Handler mHander = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            mCallBack.onImageLoader((Bitmap) msg.obj, path);
        }
    };

    // Bitmap??BitmapmMemoryCache
    if (bitmap == null) {
        mImageThreadPool.execute(new Runnable() {
            @Override
            public void run() {

                // ?
                Bitmap mBitmap = decodeThumbBitmapForFile(path, (mPoint == null) ? 0 : mPoint.x,
                        (mPoint == null) ? 0 : mPoint.y);
                Message msg = mHander.obtainMessage();

                msg.obj = mBitmap;
                mHander.sendMessage(msg);

                // 
                addBitmapToMemoryCache(path, mBitmap);
            }
        });
    }

    return bitmap;
}

From source file:net.sf.golly.HelpActivity.java

private String DownloadFile(String urlstring, String filepath) {
    // we cannot do network connections on main thread, so we do the
    // download on a new thread, but we have to wait for it to finish
    final Handler handler = new LooperInterrupter();

    cancelled = false;/*from  w  ww  .j av  a 2  s .  c  o  m*/
    progbar.setProgress(0);
    // don't show proglayout immediately
    // proglayout.setVisibility(LinearLayout.VISIBLE);

    dresult = "";
    final String durl = urlstring;
    final String dfile = filepath;
    Thread download_thread = new Thread(new Runnable() {
        public void run() {
            dresult = downloadURL(durl, dfile);
            handler.sendMessage(handler.obtainMessage());
        }
    });

    download_thread.setPriority(Thread.MAX_PRIORITY);
    download_thread.start();

    // wait for thread to finish
    try {
        Looper.loop();
    } catch (RuntimeException re) {
    }

    proglayout.setVisibility(LinearLayout.INVISIBLE);

    if (dresult.length() > 0 && !cancelled) {
        Toast.makeText(this, "Download failed! " + dresult, Toast.LENGTH_SHORT).show();
    }
    return dresult;
}

From source file:fr.pasteque.client.utils.URLTextGetter.java

public static void getBinary(final String url, final Map<String, String> getParams, final Handler h) {
    new Thread() {
        @Override//from w ww  . j a v  a2 s  .co m
        public void run() {
            try {
                String fullUrl = url;
                if (getParams != null && getParams.size() > 0) {
                    fullUrl += "?";
                    for (String param : getParams.keySet()) {
                        fullUrl += URLEncoder.encode(param, "utf-8") + "="
                                + URLEncoder.encode(getParams.get(param), "utf-8") + "&";
                    }
                }
                if (fullUrl.endsWith("&")) {
                    fullUrl = fullUrl.substring(0, fullUrl.length() - 1);
                }
                HttpClient client = new DefaultHttpClient();
                HttpResponse response = null;
                HttpGet req = new HttpGet(fullUrl);
                response = client.execute(req);
                int status = response.getStatusLine().getStatusCode();
                if (status == HttpStatus.SC_OK) {
                    // Get http response
                    byte[] content = null;
                    try {
                        final int size = 10240;
                        ByteArrayOutputStream bos = new ByteArrayOutputStream(size);
                        byte[] buffer = new byte[size];
                        BufferedInputStream bis = new BufferedInputStream(response.getEntity().getContent(),
                                size);
                        int read = bis.read(buffer, 0, size);
                        while (read != -1) {
                            bos.write(buffer, 0, read);
                            read = bis.read(buffer, 0, size);
                        }
                        content = bos.toByteArray();
                    } catch (IOException ioe) {
                        ioe.printStackTrace();
                    }
                    if (h != null) {
                        Message m = h.obtainMessage();
                        m.what = SUCCESS;
                        m.obj = content;
                        m.sendToTarget();
                    }
                } else {
                    if (h != null) {
                        Message m = h.obtainMessage();
                        m.what = STATUS_NOK;
                        m.obj = new Integer(status);
                        m.sendToTarget();
                    }
                }
            } catch (IOException e) {
                if (h != null) {
                    Message m = h.obtainMessage();
                    m.what = ERROR;
                    m.obj = e;
                    m.sendToTarget();
                }
            }
        }
    }.start();
}

From source file:com.easemob.chatuidemo.activity.MainActivity.java

public void setXG() {
    BroadcastReceiver receiver = new BroadcastReceiver() {

        @Override/*from www  .ja  v  a2 s .  c  om*/
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            System.out.println("hahahhahahah");
        }

    };
    IntentFilter intent = new IntentFilter();
    intent.addAction("bobo.com");
    this.registerReceiver(receiver, intent);
    Handler handler = new HandlerExtension(this);
    m = handler.obtainMessage();

    XGPushManager.registerPush(getApplicationContext(), Preferences.getUserName(), new XGIOperateCallback() {

        @Override
        public void onSuccess(Object arg0, int arg1) {
            // TODO Auto-generated method stub
            System.out.println("?");
            m.sendToTarget();
        }

        @Override
        public void onFail(Object arg0, int arg1, String arg2) {
            // TODO Auto-generated method stub
            m.sendToTarget();
            System.out.println("");
        }
    });
}

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

/**
 * load data/*from w  w w  .jav  a  2  s  .  c o 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.hunch.ImageManager.java

protected Runnable getDownloadTask(final URL url, final Callback callback, final Context context,
        final CachePolicy... level) {
    // hander to deal with the image once UI thread has it
    final Handler imgHandler = new Handler() {
        @Override//w  w  w . ja  va 2s  .  c o  m
        public void handleMessage(Message msg) {
            Drawable d = (Drawable) msg.obj;

            callback.callComplete(d);
        }
    };

    // the job to grab the image off the network and cache it
    Runnable task = new Runnable() {
        @Override
        public void run() {
            try {
                Log.d(Const.TAG, String.format("[%d] fetching image from URI (%s)",
                        Thread.currentThread().getId(), url.toString()));
                InputStream iStream = ImageManager.this.getInputStream(url);
                final Bitmap image = BitmapFactory.decodeStream(iStream);
                BitmapDrawable drawable = new BitmapDrawable(context.getResources(), image);

                final Message msg = imgHandler.obtainMessage();

                msg.obj = drawable;

                // send off the message with the drawable
                imgHandler.sendMessage(msg);

                // then cache the stream
                cacheBitmap(image, url, context, level);
            } catch (FileNotFoundException e) {
                Log.e(Const.TAG, "couldn't get image off network (404 error)");
            } catch (IOException e) {
                Log.e(Const.TAG, "couldn't get image off network");
            }
        }
    };

    return task;
}