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: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 .  j  a v a2  s. c om*/
        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:org.openremote.android.console.AppSettingsActivity.java

/**
 * Initializes the SSL related UI widget properties and event handlers to deal with user
 * interactions./*from   www  . jav a2  s.c  o  m*/
 */
private void initSSLState() {
    // Get UI Widget references...

    final ToggleButton sslToggleButton = (ToggleButton) findViewById(R.id.ssl_toggle);
    final EditText sslPortEditField = (EditText) findViewById(R.id.ssl_port);

    final TextView pin = (TextView) findViewById(R.id.ssl_clientcert_pin);

    // Configure UI to current settings state...

    boolean sslEnabled = AppSettingsModel.isSSLEnabled(this);

    sslToggleButton.setChecked(sslEnabled);
    sslPortEditField.setText("" + AppSettingsModel.getSSLPort(this));

    // If SSL is off, disable the port edit field by default...

    if (!sslEnabled) {
        sslPortEditField.setEnabled(false);
        sslPortEditField.setFocusable(false);
        sslPortEditField.setFocusableInTouchMode(false);
    }

    // Manage state changes to SSL toggle...

    sslToggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isEnabled) {

            // If SSL is being disabled, and the user had soft keyboard open, close it...

            if (!isEnabled) {
                InputMethodManager input = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                input.hideSoftInputFromWindow(sslPortEditField.getWindowToken(), 0);
            }

            // Set SSL state in config model accordingly...

            AppSettingsModel.enableSSL(AppSettingsActivity.this, isEnabled);

            // Enable/Disable SSL Port text field according to SSL toggle on/off state...

            sslPortEditField.setEnabled(isEnabled);
            sslPortEditField.setFocusable(isEnabled);
            sslPortEditField.setFocusableInTouchMode(isEnabled);
        }
    });

    pin.setText("...");

    final Handler pinHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            pin.setText(msg.getData().getString("pin"));
        }
    };

    new Thread() {
        public void run() {
            String pin = ORKeyPair.getInstance().getPIN(getApplicationContext());

            Bundle bundle = new Bundle();
            bundle.putString("pin", pin);

            Message msg = pinHandler.obtainMessage();
            msg.setData(bundle);

            msg.sendToTarget();
        }
    }.start();

    sslPortEditField.setOnKeyListener(new OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            //TODO not very user friendly
            if (keyCode == KeyEvent.KEYCODE_ENTER) {
                String sslPortStr = ((EditText) v).getText().toString();

                try {
                    int sslPort = Integer.parseInt(sslPortStr.trim());
                    AppSettingsModel.setSSLPort(AppSettingsActivity.this, sslPort);
                }

                catch (NumberFormatException ex) {
                    Toast toast = Toast.makeText(getApplicationContext(), "SSL port format is not correct.", 1);
                    toast.show();

                    return false;
                }

                catch (IllegalArgumentException e) {
                    Toast toast = Toast.makeText(getApplicationContext(), e.getMessage(), 2);
                    toast.show();

                    sslPortEditField.setText("" + AppSettingsModel.getSSLPort(AppSettingsActivity.this));

                    return false;
                }
            }

            return false;
        }

    });

}

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

/**
 * Download the content for the given NodeRef
 * @param ref/*from w  w w  .  ja  v  a 2 s. co  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
 * /*  w w w. ja va2 s . c  om*/
 * @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:fr.pasteque.client.utils.URLTextGetter.java

public static void getText(final String url, final Map<String, String> getParams,
        final Map<String, String> postParams, final Handler h) {
    new Thread() {
        @Override/*from  www . j  a  va 2  s. c o 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;
                if (postParams == null) {
                    HttpGet req = new HttpGet(fullUrl);
                    response = client.execute(req);
                } else {
                    HttpPost req = new HttpPost(fullUrl);
                    List<NameValuePair> args = new ArrayList<NameValuePair>();
                    for (String key : postParams.keySet()) {
                        String value = postParams.get(key);
                        args.add(new BasicNameValuePair(key, value));
                    }
                    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(args, HTTP.UTF_8);
                    req.setEntity(entity);
                    response = client.execute(req);
                }
                int status = response.getStatusLine().getStatusCode();
                if (status == HttpStatus.SC_OK) {
                    // Get http response
                    String content = "";
                    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 = new String(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.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);/* ww  w  . j a  v a 2 s  . co  m*/
    handler.sendMessage(msg1);
}

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 .  j  ava 2  s  .  co m*/
    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  w  w  . j  a v a2 s .c o  m*/
    msg1.setData(b);
    handler.sendMessage(msg1);
}