Example usage for android.os Message Message

List of usage examples for android.os Message Message

Introduction

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

Prototype

public Message() 

Source Link

Document

Constructor (but the preferred way to get a Message is to call #obtain() Message.obtain() ).

Usage

From source file:com.zsxj.pda.ui.client.LoginActivity.java

@Override
public void onReponse(Object id, InputStream data) throws IOException {
    if (null != mUpdateDataId && mUpdateDataId.toString().equals(id.toString())) {

        try {//from  w w  w .  j  a  va2 s  .c o m
            String rtnData = new String(Util.readDataFromIS(data));
            if (null == rtnData || rtnData.equals("")) {
                sendCheckUpdateRequest();
                return;
            }

            JSONObject result = new JSONObject(rtnData);
            // Message return 
            Bundle bundle = new Bundle();
            bundle.putInt("update_type", result.optJSONObject("init_response").optInt("update_type"));
            bundle.putInt("update_method", result.optJSONObject("init_response").optInt("update_method"));
            bundle.putString("update_url", result.optJSONObject("init_response").optString("update_url"));
            bundle.putString("update_ver", result.optJSONObject("init_response").optString("update_ver"));
            bundle.putLong("update_size", result.optJSONObject("init_response").optLong("update_size"));
            bundle.putString("update_msg", result.optJSONObject("init_response").optString("update_msg"));
            Message message = new Message();
            message.what = HandlerCases.UPDATE_CHECK;
            message.setData(bundle);
            handler.sendMessage(message);
        } catch (Exception e) {
        }
    }
}

From source file:cn.xiaocool.android_etong.net.constant.request.MainRequest.java

public void UpdateShopPhoto(final String id, final String photo) {
    new Thread() {
        Message msg = new Message();

        @Override/*from   w w w .  j  a  v a  2 s.  c o m*/
        public void run() {
            String data = "&id=" + id + "&photo=" + photo;
            Log.e("data=", data);
            String result_data = NetUtil.getResponse(WebAddress.UPDATESHOPPHOTO, data);
            Log.e("result_data = ", result_data);
            try {
                JSONObject jsonObject = new JSONObject(result_data);
                msg.what = CommunalInterfaces.UPDATASHOPADDRESS;
                msg.obj = jsonObject;
            } catch (JSONException e) {
                e.printStackTrace();
            } finally {
                handler.sendMessage(msg);
            }
        }
    }.start();
}

From source file:com.cleverzone.zhizhi.capture.CaptureActivity.java

private void handleDecodeInternally(Result rawResult, ResultHandler resultHandler, Bitmap barcode) {

    final CharSequence displayContents = resultHandler.getDisplayContents();

    //        if (copyToClipboard && !resultHandler.areContentsSecure()) {
    //            ClipboardInterface.setText(displayContents, this);
    //        }//  w w w  .  j a  va2 s . com

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    //        if (resultHandler.getDefaultButtonID() != null && prefs.getBoolean(PreferencesActivity.KEY_AUTO_OPEN_WEB, false)) {
    //            resultHandler.handleButtonPress(resultHandler.getDefaultButtonID());
    //            return;
    //        }

    statusView.setVisibility(View.GONE);
    viewfinderView.setVisibility(View.GONE);
    resultView.setVisibility(View.VISIBLE);

    ImageView barcodeImageView = (ImageView) findViewById(R.id.barcode_image_view);
    if (barcode == null) {
        barcodeImageView.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
    } else {
        barcodeImageView.setImageBitmap(barcode);
    }

    TextView formatTextView = (TextView) findViewById(R.id.format_text_view);
    formatTextView.setText(rawResult.getBarcodeFormat().toString());

    TextView typeTextView = (TextView) findViewById(R.id.type_text_view);
    typeTextView.setText(resultHandler.getType().toString());

    DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
    TextView timeTextView = (TextView) findViewById(R.id.time_text_view);
    timeTextView.setText(formatter.format(new Date(rawResult.getTimestamp())));

    TextView metaTextView = (TextView) findViewById(R.id.meta_text_view);
    View metaTextViewLabel = findViewById(R.id.meta_text_view_label);
    metaTextView.setVisibility(View.GONE);
    metaTextViewLabel.setVisibility(View.GONE);
    Map<ResultMetadataType, Object> metadata = rawResult.getResultMetadata();
    if (metadata != null) {
        StringBuilder metadataText = new StringBuilder(20);
        for (Map.Entry<ResultMetadataType, Object> entry : metadata.entrySet()) {
            if (DISPLAYABLE_METADATA_TYPES.contains(entry.getKey())) {
                metadataText.append(entry.getValue()).append('\n');
            }
        }
        if (metadataText.length() > 0) {
            metadataText.setLength(metadataText.length() - 1);
            metaTextView.setText(metadataText);
            metaTextView.setVisibility(View.VISIBLE);
            metaTextViewLabel.setVisibility(View.VISIBLE);
        }
    }

    final TextView contentsTextView = (TextView) findViewById(R.id.contents_text_view);
    final String baseUrl = "http://qrk.kuaipai.cn/loganal/base/scan/show-json-advert.action?code=";
    new Thread(new Runnable() {
        @Override
        public void run() {
            HttpGet get = new HttpGet(baseUrl + displayContents);
            Log.e(TAG, "full url = " + baseUrl + displayContents);
            HttpClient client = new DefaultHttpClient();
            try {
                HttpResponse response = client.execute(get);
                String json = EntityUtils.toString(response.getEntity(), "UTF-8");
                JSONObject jsonObject = new JSONObject(json);
                NetScanResult result = new NetScanResult();
                result.name = jsonObject.getString("name");
                result.url = jsonObject.getString("img");
                Message message = new Message();
                message.obj = result;
                message.what = 1;
                mNetHandler.sendMessage(message);

            } catch (Exception e) {
                mNetHandler.sendEmptyMessage(-1);
                e.printStackTrace();
            }
        }
    }).start();
    //        contentsTextView.setText(displayContents);
    int scaledSize = Math.max(22, 32 - displayContents.length() / 4);
    contentsTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, scaledSize);

    TextView supplementTextView = (TextView) findViewById(R.id.contents_supplement_text_view);
    supplementTextView.setText("");
    supplementTextView.setOnClickListener(null);
    //        if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean(
    //                PreferencesActivity.KEY_SUPPLEMENTAL, true)) {
    //            SupplementalInfoRetriever.maybeInvokeRetrieval(supplementTextView,
    //                    resultHandler.getResult(),
    //                    historyManager,
    //                    this);
    //        }

    int buttonCount = resultHandler.getButtonCount();
    ViewGroup buttonView = (ViewGroup) findViewById(R.id.result_button_view);
    buttonView.requestFocus();
    for (int x = 0; x < ResultHandler.MAX_BUTTON_COUNT; x++) {
        TextView button = (TextView) buttonView.getChildAt(x);
        if (x < buttonCount) {
            button.setVisibility(View.VISIBLE);
            button.setText(resultHandler.getButtonText(x));
            button.setOnClickListener(new ResultButtonListener(resultHandler, x));
        } else {
            button.setVisibility(View.GONE);
        }
    }

}

From source file:com.loftcat.ui.utils.slidingmenu.fragment.MiddleFragment.java

@Override
public void onFooterRefresh(PullToRefreshView view) {
    puRefreshView = view;/*  w w w  .j a  v  a  2s  . co m*/
    if (list_id == 0) {
        statusesAPI.friendsTimeline(0l, 0l, 20, count++, false, FEATURE.ALL, false, new RequestListener() {

            @Override
            public void onIOException(IOException arg0) {
                Log.d("RESULT", "arg0:    ||   " + arg0);

            }

            @Override
            public void onError(WeiboException arg0) {
                Log.d("RESULT", "arg0:    ||   " + arg0);

            }

            @Override
            public void onComplete(String arg0) {
                Message message = new Message();
                message.obj = arg0;
                message.what = 3;
                hanlder.sendMessage(message);
            }
        });
    } else {
        friendshipsAPI.groups_timeline(list_id, 0, 0, 20, count++, 0, 0, new RequestListener() {

            @Override
            public void onIOException(IOException arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onError(WeiboException arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onComplete(String arg0) {
                Message message = new Message();
                message.obj = arg0;
                message.what = 3;
                hanlder.sendMessage(message);
            }
        });
    }

}

From source file:com.sabdroidex.controllers.couchpotato.CouchPotatoController.java

/**
 * Download a release of a movie//  w w  w .j av  a 2 s .  c  om
 * 
 * @param messageHandler Handler
 * @param releaseId ID of release to download
 */
public static void downloadRelease(final Handler messageHandler, final int releaseId) {
    if (!Preferences.isSet(Preferences.COUCHPOTATO_URL)) {
        return;
    }

    Thread thread = new Thread() {

        @Override
        public void run() {

            try {
                String result = makeApiCall(MESSAGE.RELEASE_DOWNLOAD.toString().toLowerCase(),
                        "id=" + releaseId);
                JSONObject jsonObject = new JSONObject(result);

                Message message = new Message();
                message.setTarget(messageHandler);
                message.what = MESSAGE.RELEASE_DOWNLOAD.hashCode();
                message.obj = jsonObject.getBoolean("success");
                message.sendToTarget();
            } catch (IOException e) {
                Log.w(TAG, " " + e.getLocalizedMessage());
            } catch (Throwable e) {
                Log.w(TAG, " " + e.getLocalizedMessage());
            }
        }
    };
    thread.start();
}

From source file:cn.xiaocool.android_etong.net.constant.request.MainRequest.java

public void updateshopname(final String id, final String shopname) {
    new Thread() {
        Message msg = new Message();

        @Override/*ww  w. j a  va 2 s .  com*/
        public void run() {
            String data = "&id=" + id + "&shopname=" + shopname;
            Log.e("data=", data);
            String result_data = NetUtil.getResponse(WebAddress.UPDATASHOPNAME, data);
            Log.e("result_data = ", result_data);
            try {
                JSONObject jsonObject = new JSONObject(result_data);
                msg.what = CommunalInterfaces.UPDATASHOPNAME;
                msg.obj = jsonObject;
            } catch (JSONException e) {
                e.printStackTrace();
            } finally {
                handler.sendMessage(msg);
            }
        }
    }.start();
}

From source file:ca.spencerelliott.mercury.Changesets.java

private synchronized void startThread() {
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

    //Create the thread that will process the incoming feed
    load_thread = new Thread() {
        @Override// w w  w  .  j av a  2s  .co  m
        public void run() {
            changesets_list.clear();

            DatabaseHelper db_helper = DatabaseHelper.getInstance(getApplicationContext());
            EncryptionHelper encrypt_helper = EncryptionHelper.getInstance("DEADBEEF".toCharArray(),
                    new byte[] { 'L', 'O', 'L' });

            //Get the repository information from the local database
            Beans.RepositoryBean repo_type = db_helper.getRepository(repo_id, encrypt_helper);
            AtomHandler feed_handler = null;

            //Detect the type of repository and create a parser based on that
            switch (repo_type.getType()) {
            case Mercury.RepositoryTypes.HGSERVE:
                feed_handler = new HGWebAtomHandler();
                break;
            case Mercury.RepositoryTypes.GOOGLECODE:
                feed_handler = new GoogleCodeAtomHandler();
                break;
            case Mercury.RepositoryTypes.BITBUCKET:
                feed_handler = new BitbucketAtomHandler();
                break;
            case Mercury.RepositoryTypes.CODEPLEX:
                feed_handler = new CodePlexAtomHandler();
                break;
            }

            HttpURLConnection conn = null;
            boolean connected = false;

            try {
                // XXX We need to use our own factory to make all ssl certs work
                HttpsURLConnection.setDefaultSSLSocketFactory(NaiveSSLSocketFactory.getSocketFactory());

                String repo_url_string = (repo_type.getUrl().endsWith("/") || repo_type.getUrl().endsWith("\\")
                        ? feed_handler
                                .formatURL(repo_type.getUrl().substring(0, repo_type.getUrl().length() - 1))
                        : feed_handler.formatURL(repo_type.getUrl()));

                switch (repo_type.getType()) {
                case Mercury.RepositoryTypes.BITBUCKET:
                    //Only add the token if the user requested it
                    if (repo_type.getAuthentication() == Mercury.AuthenticationTypes.TOKEN)
                        repo_url_string = repo_url_string + "?token=" + repo_type.getSSHKey();
                    break;
                }

                URL repo_url = new URL(repo_url_string);
                conn = (HttpURLConnection) repo_url.openConnection();

                //Check to see if the user enabled HTTP authentication
                if (repo_type.getAuthentication() == Mercury.AuthenticationTypes.HTTP) {
                    //Get their username and password
                    byte[] decrypted_info = (repo_type.getUsername() + ":" + repo_type.getPassword())
                            .getBytes();

                    //Add the header to the http request
                    conn.setRequestProperty("Authorization", "Basic " + Base64.encodeBytes(decrypted_info));
                }
                conn.connect();
                connected = true;
            } catch (ClientProtocolException e2) {
                AlertDialog.Builder alert = new AlertDialog.Builder(getBaseContext());
                alert.setMessage("There was a problem with the HTTP protocol");
                alert.setPositiveButton(android.R.string.ok, null);
                alert.show();

                //Do not allow the app to continue with loading
                connected = false;
            } catch (IOException e2) {
                AlertDialog.Builder alert = new AlertDialog.Builder(getBaseContext());
                alert.setMessage("Server did not respond with a valid HTTP response");
                alert.setPositiveButton(android.R.string.ok, null);
                alert.show();

                //Do not allow the app to continue with loading
                connected = false;
            } catch (NullPointerException e3) {

            } catch (Exception e) {

            }

            BufferedReader reader = null;

            //Create a new reader based on the information retrieved
            if (connected) {
                try {
                    reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                } catch (IllegalStateException e1) {
                    e1.printStackTrace();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            } else {
                list_handler.sendEmptyMessage(CANCELLED);
                return;
            }

            //Make sure both the feed handler and info loaded from the web are not null
            if (reader != null && feed_handler != null) {
                try {
                    Xml.parse(reader, feed_handler);
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (SAXException e) {
                    e.printStackTrace();
                }
            } else {
                list_handler.sendEmptyMessage(CANCELLED);
                return;
            }

            //Stored beans in the devices database
            ArrayList<Beans.ChangesetBean> stored_beans = null;

            if (prefs.getBoolean("caching", false)) {
                long last_insert = db_helper.getHighestID(DatabaseHelper.DB_TABLE_CHANGESETS, repo_id);

                if (last_insert >= 0) {
                    //Get all of the stored changesets
                    stored_beans = db_helper.getAllChangesets(repo_id, null);

                    String rev_id = "";

                    //Try to find the revision id of the bean that has the id of the last inserted value
                    for (Beans.ChangesetBean b : stored_beans) {
                        if (b.getID() == last_insert) {
                            rev_id = b.getRevisionID();
                            break;
                        }
                    }

                    //Trim the list starting from this revision
                    feed_handler.trimStartingFromRevision(rev_id);
                }
            }

            //Create a new bundle for the progress
            Bundle progress_bundle = new Bundle();

            //Retreive all the beans from the handler
            ArrayList<Beans.ChangesetBean> beans = feed_handler.getAllChangesets();
            int bean_count = beans.size();

            //Store the amount of changesets
            progress_bundle.putInt("max", bean_count);

            //Create a new message and store the bundle and what type of message it is
            Message msg = new Message();
            msg.setData(progress_bundle);
            msg.what = SETUP_COUNT;
            list_handler.sendMessage(msg);

            //Add each of the beans to the list
            for (int i = 0; i < bean_count; i++) {
                String commit_text = beans.get(i).getTitle();
                Date commit_date = new Date(beans.get(i).getUpdated());
                changesets_list.add(createChangeset(
                        (commit_text.length() > 30 ? commit_text.substring(0, 30) + "..." : commit_text),
                        beans.get(i).getRevisionID() + " - " + commit_date.toLocaleString()));

                //Store the current progress of the changeset loading
                progress_bundle.putInt("progress", i);

                //Reuse the old message and send an update progress message
                msg = new Message();
                msg.setData(progress_bundle);
                msg.what = UPDATE_PROGRESS;
                list_handler.sendMessage(msg);
            }

            //Get the current count of changesets and the shared preferences
            long changeset_count = db_helper.getChangesetCount(repo_id);

            if (prefs.getBoolean("caching", false)) {
                //Get all of the stored beans from the device if not already done
                if (stored_beans == null)
                    stored_beans = db_helper.getAllChangesets(repo_id, null);

                //Add all the changesets from the device
                for (Beans.ChangesetBean b : stored_beans) {
                    changesets_list.add(createChangeset(
                            (b.getTitle().length() > 30 ? (b.getTitle().substring(0, 30)) + "..."
                                    : b.getTitle()),
                            b.getRevisionID() + " - " + new Date(b.getUpdated()).toLocaleString()));
                }

                //Reverse the list so the oldest changesets are stored first
                Collections.reverse(beans);

                //Iterate through each bean and add it to the device's database
                for (Beans.ChangesetBean b : beans) {
                    db_helper.insert(b, repo_id);
                }

                //Get the amount of changesets allowed to be stored on the device
                int max_changes = Integer.parseInt(prefs.getString("max_changesets", "-1"));

                //Delete the oldest changesets if too many have been stored
                if (changeset_count > max_changes) {
                    db_helper.deleteNumChangesets(repo_id, (changeset_count - max_changes));
                }
            } else if (changeset_count > 0) {
                //Since the user does not have caching enabled, delete the changesets
                db_helper.deleteAllChangesets(repo_id);
            }

            //Update the tables to the newest revision
            if (!beans.isEmpty())
                db_helper.updateLastRev(repo_id, beans.get(0).getRevisionID());

            //Add all of the data to the changeset list
            changesets_data.addAll(beans);

            if (prefs.getBoolean("caching", false))
                changesets_data.addAll(stored_beans);

            //Clean up the sql connection
            db_helper.cleanup();
            db_helper = null;

            //Notify the handler that the loading of the list was successful
            list_handler.sendEmptyMessage(SUCCESSFUL);
        }
    };

    //Start the thread
    load_thread.start();
}

From source file:net.evecom.android.PublicOpinionLookActivity.java

/**
 * // w  w w  .  j  ava  2 s .c  o m
 */
private void formSubmit1() {
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Message msg_listData = new Message();
                String a = HttpUtil.BASE_URL + "teventAndroid/updateInfoAndroid";
                String b = "Id=" + Id + "&social.EVENTNM=" + ztEditText.getText().toString().trim()
                // +"&social.LATITUDE="+ShareUtil.getString(getApplicationContext(),"GPS",
                // "GPS_longitude", "0.0")
                // +"&social.LONGITUDE="+ShareUtil.getString(getApplicationContext(),"GPS",
                // "GPS_latitude", "0.0")
                        + "&social.OCCURADDR=" + fsddEditText.getText().toString().trim() + "&social.SOURCEWAY="
                        + sourceway + "&social.OCCURTIME=" + lysj + "&social.SOURCEPEOPLE="
                        + lyrEditText.getText().toString().trim() + "&social.PHONE="
                        + lxdhEditText.getText().toString().trim() + "&social.NEWS="
                        + xxnrEditText.getText().toString().trim() + "&uploadFile=";
                // +"&attachId_=";
                // System.out.println(furl);
                try {
                    sss = connServerForResultPost(a, b);
                    // sss = connServerForResult(furl);

                } catch (Exception e) {
                    msg_listData.what = MESSAGETYPE_02;
                }
                if (sss == null || "".equals(sss) || sss.contains("failure")) {
                    msg_listData.what = MESSAGETYPE_02;
                } else {
                    msg_listData.what = MESSAGETYPE_01;
                }
                handler2.sendMessage(msg_listData);
            } catch (Exception e) {
                if (null != e) {
                    e.printStackTrace();
                }
            }
        }
    }).start();
}

From source file:com.loftcat.ui.utils.slidingmenu.fragment.MiddleFragment.java

@Override
public void onHeaderRefresh(PullToRefreshView view) {
    puRefreshView = view;/*from w ww . j a va2s  .c  om*/
    if (list_id == 0) {
        statusesAPI.friendsTimeline(since_id, 0l, 20, 1, false, FEATURE.ALL, false, new RequestListener() {

            @Override
            public void onIOException(IOException arg0) {
                Log.d("RESULT", "arg0:    ||   " + arg0);

            }

            @Override
            public void onError(WeiboException arg0) {
                Log.d("RESULT", "arg0:    ||   " + arg0);

            }

            @Override
            public void onComplete(String arg0) {
                Message message = new Message();
                message.obj = arg0;
                message.what = 2;
                hanlder.sendMessage(message);
            }
        });

    } else {
        friendshipsAPI.groups_timeline(list_id, since_id, 0, 20, 1, 0, 0, new RequestListener() {

            @Override
            public void onIOException(IOException arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onError(WeiboException arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onComplete(String arg0) {
                Message message = new Message();
                message.obj = arg0;
                message.what = 2;
                hanlder.sendMessage(message);
            }
        });
    }

}

From source file:cn.xiaocool.android_etong.net.constant.request.MainRequest.java

public void UpdateShopAddress(final String id, final String address) {
    new Thread() {
        Message msg = new Message();

        @Override//from ww  w  .  j  a va  2 s .c om
        public void run() {
            String data = "&id=" + id + "&address=" + address;
            Log.e("data=", data);
            String result_data = NetUtil.getResponse(WebAddress.UPDATA_SHOP_ADDRESS, data);
            Log.e("result_data = ", result_data);
            try {
                JSONObject jsonObject = new JSONObject(result_data);
                msg.what = CommunalInterfaces.UPDATA_SHOP_ADDRESS;
                msg.obj = jsonObject;
            } catch (JSONException e) {
                e.printStackTrace();
            } finally {
                handler.sendMessage(msg);
            }
        }
    }.start();
}