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:com.nachiket.titan.LibraryActivity.java

/**
 * Called when a new page becomes visible.
 *
 * @param position The position of the new page.
 * @param adapter The new visible adapter.
 *//* ww  w .  j av  a 2  s . c om*/
public void onPageChanged(int position, LibraryAdapter adapter) {
    mCurrentAdapter = adapter;
    mLastActedId = LibraryAdapter.INVALID_ID;
    updateLimiterViews();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        CompatHoneycomb.selectTab(this, position);
    }
    if (adapter != null && adapter.getLimiter() == null) {
        // 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.changhong.sync.web.SnowySyncService.java

public void getAuthUri(final String server, final Handler handler) {

    execInThread(new Runnable() {

        public void run() {

            // Reset the authentication credentials
            OAuthConnection auth = new OAuthConnection();
            Uri authUri = null;/*  w  w w.  ja  v a2 s . co m*/

            try {
                authUri = auth.getAuthorizationUrl(server);

            } catch (UnknownHostException e) {
                TLog.e(TAG, "Internet connection not available");
                sendMessage(NO_INTERNET);
            }

            Message message = new Message();
            message.obj = authUri;
            handler.sendMessage(message);
        }

    });
}

From source file:com.cm.beer.util.DrawableManager.java

/**
 * /*from   w w w.j  a va  2  s . co  m*/
 * @param urlString
 * @param imageView
 */
public void fetchDrawableOnThread(final String urlString, final ImageView imageView) {
    if (mDrawableCache.containsKey(urlString)) {
        if (Logger.isLogEnabled())
            Logger.log("Returning Drawable from Cache:" + urlString);
        SoftReference<Drawable> softReference = mDrawableCache.get(urlString);
        if ((softReference == null) || (softReference.get() == null)) {
            mDrawableCache.remove(urlString);
            if (Logger.isLogEnabled())
                Logger.log("fetchDrawableOnThread():Soft Reference has been Garbage Collected:" + urlString);
        } else {
            imageView.setImageDrawable(softReference.get());
            return;
        }

    }

    final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message message) {
            imageView.setImageDrawable((Drawable) message.obj);
        }
    };

    Thread thread = new Thread() {
        @Override
        public void run() {
            while (mLockCache.containsKey(urlString)) {
                if (Logger.isLogEnabled())
                    Logger.log("URI download request in progress:" + urlString);
                try {
                    Thread.sleep(1000L);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    Log.e(this.getClass().getName(), e.getMessage());
                }
            }
            Drawable drawable = fetchDrawable(urlString);
            Message message = handler.obtainMessage(1, drawable);
            handler.sendMessage(message);
        }
    };
    thread.start();
}

From source file:com.neudesic.mobile.pulse.ui.drawable.DrawableManager.java

public void fetchDrawableOnThread(final String urlString, final ImageView imageView) {

    final Handler handler = new Handler() {
        @Override//w ww  .j a  va  2s  .  c  o m
        public void handleMessage(Message message) {
            try {
                imageView.setImageDrawable((Drawable) message.obj);

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };

    Thread thread = new Thread() {

        @Override
        public void run() {
            // TODO : set imageView to a "pending" image
            try {
                Drawable drawable;
                if (drawableMap.containsKey(urlString)) {
                    // imageView.setImageDrawable(drawableMap.get(urlString));
                    drawable = drawableMap.get(urlString);

                } else {

                    drawable = fetchDrawable(urlString);
                }
                Message message = handler.obtainMessage(1, drawable);
                handler.sendMessage(message);
            } catch (Exception e) {
                Log.w(getClass().getPackage().getName(), "Unable to fetch drawable, using default instead", e);
                Message message = handler.obtainMessage(1, emptyAvatar);
                handler.sendMessage(message);
            }
        }
    };
    thread.start();
}

From source file:com.anton.gavel.ComplaintSubmission.java

public void submit() {

    //Body of your click handler
    Thread trd = new Thread(new Runnable() {
        @Override/*from   w ww . j  a v  a 2  s  .c o m*/
        public void run() {
            String formPath = "http://www.hamilton.ca/Hamilton.Portal/Templates/COHShell.aspx?NRMODE=Published&NRORIGINALURL=%2fCityDepartments%2fCorporateServices%2fITS%2fForms%2bin%2bDevelopment%2fMunicipal%2bLaw%2bEnforcement%2bOnline%2bComplaint%2bForm%2ehtm&NRNODEGUID=%7b4319AA7C-7E5E-4D65-9F46-CCBEC9AB86E0%7d&NRCACHEHINT=Guest";
            String hideString = "document.getElementById('mainform').style.display = 'none';";
            //this javascript will be added to the page if we are successful - we can look
            //for it to identify whether our form was successfully submitted

            // Create a new HttpClient and Post Header
            HttpClient httpClient = new DefaultHttpClient();

            ArrayList<NameValuePair> parameters = new ArrayList<NameValuePair>();

            for (String key : post_params.keySet()) {
                parameters.add(new BasicNameValuePair(key, post_params.get(key)));
                String value = post_params.get(key);
                if (value != null && value.length() > 0) {
                    value = value.substring(0, Math.min(70, value.length()));
                }
                Log.d("Runs", "key: '" + key + "', value: '" + value);
            }
            //convert to a list of name-value pairs (dum, dee dum  -  duuuuumm...)

            HttpPost request = new HttpPost(formPath);

            //set up handler/bundle to give output to main thread
            Handler handler = ((GavelMain) mContext).submissionHandler;
            Message msg = handler.obtainMessage();
            Bundle bundle = new Bundle();

            try {
                request.setEntity(new UrlEncodedFormEntity(parameters));

                HttpResponse httpResponse = httpClient.execute(request);
                HttpEntity responseEntity = httpResponse.getEntity();

                String response = responseEntity == null ? ""
                        : EntityUtils.toString(responseEntity, EntityUtils.getContentCharSet(responseEntity));
                //read the html page posted in response to our request

                appendLog(response); // logs html page response to a text file on sd card

                bundle.putBoolean("succeeded",
                        httpResponse.getStatusLine().getStatusCode() == 200 && response.contains(hideString));

                msg.setData(bundle);
                handler.sendMessage(msg);
            } catch (ClientProtocolException e) {
                bundle.putBoolean("succeeded", false);
                msg.setData(bundle);
                handler.sendMessage(msg);
            } catch (IOException e) {
                bundle.putBoolean("succeeded", false);
                msg.setData(bundle);
                handler.sendMessage(msg);
            } //code to do the HTTP request            
        }
    });
    trd.start();

    //

    return;

}

From source file:org.zeroxlab.zeroxbenchmark.Benchmark.java

private void initAuto() {
        Intent intent = getIntent();//from w  w  w  . j  av  a 2 s.co m
        String TAG = intent.getStringExtra("TAG");
        String CAT = intent.getStringExtra("CAT");

        _checkAllCase(false);
        if (TAG != null)
            _checkTagCase(TAG.split(","));
        if (CAT != null)
            _checkCatCase(CAT.split(","));
        if (TAG == null && CAT == null)
            _checkAllCase(true);
        final Handler h = new Handler() {
            public void handleMessage(Message msg) {
                if (msg.what == 0x1234)
                    onClick(mRun);
            }
        };

        final ProgressDialog dialog = new ProgressDialog(this).show(this, "Starting Benchmark", "Please wait...",
                true, false);
        new Thread() {
            public void run() {
                SystemClock.sleep(1000);
                dialog.dismiss();
                Message m = new Message();
                m.what = 0x1234;
                h.sendMessage(m);
            }
        }.start();
        mTouchable = true;
    }

From source file:org.zeroxlab.benchmark.Benchmark.java

@SuppressWarnings("unused")
private void initAuto() {
    Intent intent = getIntent();/*from  www  .j a  v  a2  s .  c  om*/
    String TAG = intent.getStringExtra("TAG");
    String CAT = intent.getStringExtra("CAT");

    _checkAllCase(false);
    if (TAG != null)
        _checkTagCase(TAG.split(","));
    if (CAT != null)
        _checkCatCase(CAT.split(","));
    if (TAG == null && CAT == null)
        _checkAllCase(true);
    final Handler h = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 0x1234)
                onClick(mRun);
        }
    };

    final ProgressDialog dialog = ProgressDialog.show(this, "Starting Benchmark", "Please wait...", true,
            false);

    new Thread() {
        public void run() {
            SystemClock.sleep(1000);
            dialog.dismiss();
            Message m = new Message();
            m.what = 0x1234;
            h.sendMessage(m);
        }
    }.start();
    mTouchable = true;
}

From source file:com.cloverstudio.spika.utils.BitmapManager.java

public void queueJob(final String url, final ImageView imageView, final ProgressBar pbLoading) {
    /* Create handler in UI thread. */
    final Handler handler = new Handler() {
        @Override/* ww w.j av a  2  s . c  om*/
        public void handleMessage(Message msg) {
            String tag = imageViews.get(imageView);
            if (tag != null && tag.equals(url)) {
                if (msg.obj != null) {
                    if (smallImg) {
                        imageView.setScaleType(ImageView.ScaleType.CENTER);
                    } else {
                        imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
                    }
                    imageView.setImageBitmap((Bitmap) msg.obj);
                    if (pbLoading != null)
                        pbLoading.setVisibility(View.GONE);
                } else {
                    //                  imageView.setImageBitmap(placeholder);
                    imageView.setImageResource(R.drawable.image_stub);
                    if (pbLoading != null)
                        pbLoading.setVisibility(View.GONE);
                }
            }
        }
    };

    pool.submit(new Runnable() {
        @Override
        public void run() {
            final Bitmap bmp = downloadBitmap(url);
            Message message = Message.obtain();
            message.obj = bmp;

            handler.sendMessage(message);
        }
    });
}

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/*from www  .j  a va2  s  . 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;
}

From source file:com.noah.lol.network.RequestNetwork.java

protected void asyncRequestGet(final String url, final NetworkListener<String> listener) {

    if (url == null) {
        return;//from  w  w  w.ja v a2  s  .  co  m
    }

    try {
        environmentCheck();
    } catch (EnvironmentException e) {
        if (listener != null) {
            e.setStatus(BAD_REQUEST_ENVIRONMENT_CONFIG);
            listener.onNetworkFail(BAD_REQUEST_ENVIRONMENT_CONFIG, e);
        }
        return;
    }

    final Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            Bundle bundle = msg.getData();
            switch (msg.what) {
            case REQUEST_SUCCESS:
                String responseBody = bundle.getString(RESPONSE_KEY);

                if (listener != null && responseBody != null) {
                    listener.onSuccess(responseBody);
                }
                break;
            case REQUEST_FAIL:
                NetworkException e = (NetworkException) bundle.getSerializable(EXCEPTION_KEY);
                if (listener != null) {
                    listener.onNetworkFail(e.getStatus(), e);
                }
                break;
            }
        }
    };

    new Thread(new Runnable() {

        @Override
        public void run() {

            String responseBody = null;
            Message message = new Message();

            try {
                responseBody = syncRequestGet(url);
                Bundle bundle = new Bundle();
                bundle.putString(RESPONSE_KEY, responseBody);
                message = Message.obtain(handler, REQUEST_SUCCESS);
                message.setData(bundle);
                handler.sendMessage(message);
            } catch (NetworkException e) {
                Bundle bundle = new Bundle();
                bundle.putSerializable(EXCEPTION_KEY, e);
                message = Message.obtain(handler, REQUEST_FAIL);
                message.setData(bundle);
                handler.sendMessage(message);
                e.printStackTrace();
            }

        }
    }).start();

}