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:ibp.plugin.nsd.NSDHelper.java

public void sendNotification(String type, String msg) {
    Bundle messageBundle = new Bundle();
    messageBundle.putString("type", type);
    messageBundle.putString("msg", msg);
    Message message = new Message();
    message.setData(messageBundle);/*from ww  w.j a  v a 2 s.  com*/
    mHandler.sendMessage(message);
}

From source file:com.javadog.cgeowear.WearService.java

@Override
public void onConnected(Bundle bundle) {
    Log.d(DEBUG_TAG, "Connected to Play Services");

    //Subscribe to location updates
    LocationServices.FusedLocationApi.requestLocationUpdates(apiClient, locationRequest, locationListener);

    //Get ID of connected Wear device and send it the initial cache info (in another thread)
    new Thread(new Runnable() {
        @Override/*  w ww.ja  v a 2  s .com*/
        public void run() {
            HashSet<String> connectedWearDevices = new HashSet<String>();
            NodeApi.GetConnectedNodesResult nodes = Wearable.NodeApi.getConnectedNodes(apiClient).await();
            for (Node node : nodes.getNodes()) {
                connectedWearDevices.add(node.getId());
            }

            Message m = new Message();
            try {
                wearInterface = new WearInterface(apiClient, connectedWearDevices.iterator().next());
                wearInterface.initTracking(cacheName, geocode, 0f, 0f, useWatchCompass, geocacheLocation);
                m.obj = MESSAGE_NAVIGATING_NOW;

            } catch (ConnectException e) {
                Log.e(DEBUG_TAG, "Couldn't send initial tracking data.");
                m.obj = MESSAGE_ERROR_COMMUNICATING;

            } catch (NoSuchElementException e) {
                Log.e(DEBUG_TAG, "No Wear devices connected. Killing service...");
                m.obj = MESSAGE_NO_WEAR_DEVICE;

            } finally {
                initThreadHandler.sendMessage(m);
            }
        }
    }).start();
}

From source file:net.evecom.androidecssp.activity.TaskResponseAddActivity.java

private void postdata(final HashMap<String, String> entity) {
    new Thread(new Runnable() {
        @Override/*from w w  w.java 2  s  .co  m*/
        public void run() {
            Message message = new Message();
            try {
                saveResult = connServerForResultPost("jfs/ecssp/mobile/taskresponseCtr/taskResponseAdd",
                        entity);
            } catch (ClientProtocolException e) {
                message.what = MESSAGETYPE_02;
                Log.e("mars", e.getMessage());
            } catch (IOException e) {
                message.what = MESSAGETYPE_02;
                Log.e("mars", e.getMessage());
            }
            if (saveResult.length() > 0) {
                message.what = MESSAGETYPE_01;
                String responseid = "";
                try {
                    TaskResponseInfo taskResponseInfo = getTaskResponseInfo(saveResult);
                    if (null != taskResponseInfo) {
                        responseid = taskResponseInfo.getId();
                    }
                } catch (JSONException e) {
                    Log.e("mars", e.getMessage());
                }
                HashMap<String, String> hashMap = new HashMap<String, String>();
                hashMap.put("taskresponseId", responseid);
                postImage(hashMap, fileList, "jfs/ecssp/mobile/taskresponseCtr/taskResponseFileSave");
            } else {
                message.what = MESSAGETYPE_02;
            }
            Log.v("mars", saveResult);
            saveHandler.sendMessage(message);
        }
    }).start();

}

From source file:com.c4mprod.utils.ImageManager.java

/**
 * /*from   w w  w.  j  ava 2  s.c o  m*/
 * @param listener
 *            call when download is finished
 * @param url
 *            url of the image to download
 * @param view
 *            image container (put in background if is not an ImageView)
 * @param flags
 * @param checkNewVersionDelay
 *            delay between two checks of the image in milliseconds
 * @param defaultImageId
 *            TODO
 * @param defaultDrawableId
 */
public void download(ImageDownloaderListener listener, final String url, View view, int flags,
        long checkNewVersionDelay, int defaultImageId) {
    if (mStopped || TextUtils.isEmpty(url)) {
        return;
    }
    // mListener = listener;

    // get image from cache
    Bitmap cachedBitmap = null;
    if ((flags & FLAG_GET_THUMBNAIL) != 0) {
        cachedBitmap = mImageLiveCache.get(url + THUMB_FOLDER);
    } else {
        cachedBitmap = mImageLiveCache.get(url);
    }

    ImageDownloadMessageData messageData = new ImageDownloadMessageData(url, view, defaultImageId);
    messageData.listerner = listener;
    DownloadedDrawable downloadedDrawable;
    downloadedDrawable = new DownloadedDrawable(messageData, mContext.getResources(),
            cachedBitmap != null ? cachedBitmap : getDefaultImage(defaultImageId));

    if (view != null) {
        if (view instanceof ImageView) {
            if ((flags & FLAG_IN_BACKGROUND) != 0) {
                view.setBackgroundDrawable(downloadedDrawable);
            } else {
                ((ImageView) view).setImageDrawable(downloadedDrawable);
            }

        } else if (view instanceof ImageButton) {
            if ((flags & FLAG_IN_BACKGROUND) != 0) {
                view.setBackgroundDrawable(downloadedDrawable);
            } else {
                ((ImageButton) view).setImageDrawable(downloadedDrawable);
            }
        } else {
            view.setBackgroundDrawable(downloadedDrawable);
        }
    }

    if (cachedBitmap != null) {
        // Log.d("test", "version form cache");
        Message respMessage = new Message();
        messageData.bitmap = cachedBitmap;
        messageData.flags = flags;
        respMessage.obj = messageData;
        mUiHandler.sendMessage(respMessage);
    } else {
        messageData.flags = flags;

        // check if available from sd card
        if (isSDCacheReadable()) {
            File extCacheDir = mContext.getExternalCacheDir();
            final File img = new File(extCacheDir, md5(url));
            final Long currentDate = Calendar.getInstance().getTimeInMillis();

            if (img.exists()) {

                Message msg = new Message();
                msg.obj = messageData;
                msg.what = MSG_LOAD_FROM_SD;
                mDowloadLooper.enqueueMessage(msg, true);
                // Log.d("test", "version form sdcard");
                if (img.lastModified() + checkNewVersionDelay < currentDate) {
                    final ImageDownloadMessageData test = messageData;
                    Thread thread = new Thread(new Runnable() {

                        @Override
                        public void run() {

                            Message msg = new Message();
                            msg.obj = test;
                            URL connexion;
                            try {

                                connexion = new URL(url);
                                URLConnection urlConnection;
                                urlConnection = connexion.openConnection();
                                urlConnection.connect();
                                String date = urlConnection.getHeaderField("Last-Modified");
                                if (img.lastModified() >= mDateFormater.parse(date).getTime()) {
                                    // Log.d("test", "version form sdcard after server check");
                                    return;
                                } else {
                                    // load from web
                                    // Log.d("test", "version form server");
                                    msg.what = MSG_DOWNLOAD;
                                    mDowloadLooper.enqueueMessage(msg, false);
                                }
                                urlConnection = null;
                            } catch (Exception e) {
                                return;
                            }

                        }
                    });
                    thread.start();

                }
            } else {
                Message msg = new Message();
                msg.obj = messageData;
                // load from web
                // Log.d("test", "version form server");
                msg.what = MSG_DOWNLOAD;
                mDowloadLooper.enqueueMessage(msg, false);
            }
        }

    }
}

From source file:com.hoteltrip.android.util.NumberPicker.java

public void onClick(View v) {
    validateInput(mText);/*from  www. ja v  a  2  s  .  c  om*/
    if (!mText.hasFocus())
        mText.requestFocus();

    // now perform the increment/decrement
    if (R.id.increment == v.getId()) {

        // custom made for hoteltrip
        if (getCurrent() == mEnd) {
            /*
             * Toast.makeText(getContext(), "Cannot exceed upper limit",
             * Toast.LENGTH_SHORT).show();
             */
            showDialog(Const.UPPER_LIMIT_REACHED_ID, mEnd);
            return;
        }

        changeCurrent(mCurrent + 1);

        if (currentRoomsRequired != null)
            currentRoomsRequired.currentSelectedValue = mCurrent;

        if (mHandlerFindHotelUIUpdate != null) {
            Message message = new Message();
            message.what = Const.INCREMENT;
            message.arg1 = mCurrent;
            mHandlerFindHotelUIUpdate.sendMessage(message);
        }

        if (currentRoomOccupancyRequired != null)
            currentRoomOccupancyRequired.currentSelectedValue = mCurrent;

        if (mHandlerRoomOccupanyDetailsUIUpdate != null)
            mHandlerRoomOccupanyDetailsUIUpdate.sendEmptyMessage(Const.INCREMENT);

        if (currentChildCount != null)
            currentChildCount.currentNumberOfChild = mCurrent;

        if (mHandlerChildCountUIUpdate != null) {
            Message msg = new Message();
            msg.arg1 = mPositionOfChildLayout;
            msg.what = Const.INCREMENT;
            mHandlerChildCountUIUpdate.sendMessage(msg);
        }

    } else if (R.id.decrement == v.getId()) {

        // custom made for hoteltrip
        if (getCurrent() == mStart) {
            /*
             * Toast.makeText(getContext(), "Cannot go lower",
             * Toast.LENGTH_SHORT).show();
             */
            showDialog(Const.LOWER_LIMIT_REACHED_ID, mStart);
            return;
        }

        changeCurrent(mCurrent - 1);

        if (currentRoomsRequired != null)
            currentRoomsRequired.currentSelectedValue = mCurrent;

        if (mHandlerFindHotelUIUpdate != null) {
            Message message = new Message();
            message.what = Const.DECREMENT;
            message.arg1 = mCurrent;
            mHandlerFindHotelUIUpdate.sendMessage(message);
        }

        if (currentRoomOccupancyRequired != null)
            currentRoomOccupancyRequired.currentSelectedValue = mCurrent;

        if (mHandlerRoomOccupanyDetailsUIUpdate != null)
            mHandlerRoomOccupanyDetailsUIUpdate.sendEmptyMessage(Const.DECREMENT);

        if (currentChildCount != null)
            currentChildCount.currentNumberOfChild = mCurrent;

        if (mHandlerChildCountUIUpdate != null) {
            Message msg = new Message();
            msg.arg1 = mPositionOfChildLayout;
            msg.what = Const.DECREMENT;
            mHandlerChildCountUIUpdate.sendMessage(msg);
        }
    }
}

From source file:com.example.main.BandWViewPagerActivity.java

private void getmArrays(String decode) {
    // TODO Auto-generated method stub
    try {/*from   w w w. j a  va  2  s  . c o m*/
        GlobalID globalID = (GlobalID) getApplication();
        JSONArray jsonArray = new JSONArray(decode);
        if (jsonArray.length() == 0) {
            return;
        } else {
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);

                BandWEntity entity = new BandWEntity(Boolean.valueOf(jsonObject.optString("list_type")),
                        jsonObject.optString("Id"), jsonObject.optString("Title"),
                        jsonObject.optString("Typeid"),
                        Html.fromHtml(jsonObject.optString("Detail")).toString(), jsonObject.optString("Pic"),
                        jsonObject.optString("Time"));

                if (!entity.getList_type()) {
                    String pic = entity.getPicName();
                    if (log)
                        Log.v(i + " pic: ", pic);
                    Bitmap bit = FuntionUtil
                            .downloadPic("http://" + globalID.getDBurl() + "/admin/images/" + pic);
                    if (bit != null) {
                        entity.setPic(bit);
                    } else {
                        Bitmap good = BitmapFactory.decodeResource(getResources(), R.drawable.weather_preview);
                        entity.setPic(good);
                    }
                }

                //               mArrays.add(entity);
                Message msg = new Message();
                msg.what = 1;
                msg.obj = entity;
                add_handler.sendMessage(msg);
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
        return;
    }
}

From source file:cm.aptoide.pt.Aptoide.java

private void proceed() {
    if (sPref.getInt("version", 0) < pkginfo.versionCode) {
        db.UpdateTables();/*  w w w .jav  a  2  s . c  om*/
        prefEdit.putBoolean("mode", true);
        prefEdit.putInt("version", pkginfo.versionCode);
        prefEdit.commit();
    }

    if (sPref.getString("myId", null) == null) {
        String rand_id = UUID.randomUUID().toString();
        prefEdit.putString("myId", rand_id);
        prefEdit.commit();
    }

    if (sPref.getInt("scW", 0) == 0 || sPref.getInt("scH", 0) == 0) {
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        prefEdit.putInt("scW", dm.widthPixels);
        prefEdit.putInt("scH", dm.heightPixels);
        prefEdit.commit();
    }

    if (sPref.getString("icdown", null) == null) {
        prefEdit.putString("icdown", "g3w");
        prefEdit.commit();
    }

    setContentView(R.layout.start);

    mProgress = (ProgressBar) findViewById(R.id.pbar);

    new Thread(new Runnable() {
        public void run() {

            Vector<ApkNode> apk_lst = db.getAll("abc");
            mProgress.setMax(apk_lst.size());
            PackageManager mPm;
            PackageInfo pkginfo;
            mPm = getPackageManager();

            keepScreenOn.acquire();

            for (ApkNode node : apk_lst) {
                if (node.status == 0) {
                    try {
                        pkginfo = mPm.getPackageInfo(node.apkid, 0);
                        String vers = pkginfo.versionName;
                        int verscode = pkginfo.versionCode;
                        db.insertInstalled(node.apkid, vers, verscode);
                    } catch (Exception e) {
                        //Not installed anywhere... does nothing
                    }
                } else {
                    try {
                        pkginfo = mPm.getPackageInfo(node.apkid, 0);
                        String vers = pkginfo.versionName;
                        int verscode = pkginfo.versionCode;
                        db.UpdateInstalled(node.apkid, vers, verscode);
                    } catch (Exception e) {
                        db.removeInstalled(node.apkid);
                    }
                }
                mProgressStatus++;
                // Update the progress bar
                mHandler.post(new Runnable() {
                    public void run() {
                        mProgress.setProgress(mProgressStatus);
                    }
                });
            }

            keepScreenOn.release();

            Message msg = new Message();
            msg.what = LOAD_TABS;
            startHandler.sendMessage(msg);

        }
    }).start();
}

From source file:com.cleanwiz.applock.ui.activity.SplashActivity.java

public void NewCheckVersion() {
    final String oldVersionString = getApplicationVersion();
    List<UpdateVersionManafer> versionManafers = updateVersionManagerService.getVersionManafers();
    boolean hasVersion = false;
    for (UpdateVersionManafer updateVersionManafer : versionManafers) {
        hasVersion = true;//from w w w.j  a  v  a 2  s .  com
        if (updateVersionManafer.getVersioncode() > Double.parseDouble(oldVersionString)) {
            if (SharedPreferenceUtil.readUpdateTipTime() == 0l) {
                downLoadFileUrl = updateVersionManafer.getUpdateurl();
                showUpdateDialog(updateVersionManafer.getIntro());
                updateVersionManafer.setLasttipdate(new Date().getTime());
            } else if (System.currentTimeMillis() - SharedPreferenceUtil.readUpdateTipTime() >= 1000 * 60 * 60
                    * 20) {
                downLoadFileUrl = updateVersionManafer.getUpdateurl();
                showUpdateDialog(updateVersionManafer.getIntro());
                updateVersionManafer.setLasttipdate(new Date().getTime());
            } else {
                SplashHandler handler = new SplashHandler();
                Message msg = new Message();
                msg.what = CHECKVERSION_EOOR;
                handler.sendMessageDelayed(msg, 1000);
            }
        } else {
            SplashHandler handler = new SplashHandler();
            Message msg = new Message();
            msg.what = CHECKVERSION_EOOR;
            handler.sendMessageDelayed(msg, 1000);
        }
        break;
    }
    if (!hasVersion) {
        SplashHandler handler = new SplashHandler();
        Message msg = new Message();
        msg.what = CHECKVERSION_EOOR;
        handler.sendMessageDelayed(msg, 1000);
    }
}

From source file:cn.com.zhenshiyin.crowd.net.AsyncHttpPost.java

@Override
public void run() {
    String ret = "";
    try {/*from  w ww  . j  a  va 2  s.  c  om*/
        request = new HttpPost(url);
        if (Constants.isGzip) {
            request.addHeader("Accept-Encoding", "gzip");
        } else {
            request.addHeader("Accept-Encoding", "default");
        }
        LogUtil.d(AsyncHttpPost.class.getName(), "AsyncHttpPost  request to url :" + url);

        if (parameter != null && parameter.size() > 0) {
            List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
            for (RequestParameter p : parameter) {
                list.add(new BasicNameValuePair(p.getName(), p.getValue()));
            }
            ((HttpPost) request).setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
        }
        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectTimeout);
        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, readTimeout);
        HttpResponse response = httpClient.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            InputStream is = response.getEntity().getContent();
            BufferedInputStream bis = new BufferedInputStream(is);
            bis.mark(2);
            // ??
            byte[] header = new byte[2];
            int result = bis.read(header);
            // reset??
            bis.reset();
            // ?GZIP?
            int headerData = getShort(header);
            // Gzip ? ? 0x1f8b
            if (result != -1 && headerData == 0x1f8b) {
                LogUtil.d("HttpTask", " use GZIPInputStream  ");
                is = new GZIPInputStream(bis);
            } else {
                LogUtil.d("HttpTask", " not use GZIPInputStream");
                is = bis;
            }
            InputStreamReader reader = new InputStreamReader(is, "utf-8");
            char[] data = new char[100];
            int readSize;
            StringBuffer sb = new StringBuffer();
            while ((readSize = reader.read(data)) > 0) {
                sb.append(data, 0, readSize);
            }
            ret = sb.toString();
            bis.close();
            reader.close();

        } else {
            RequestException exception = new RequestException(RequestException.IO_EXCEPTION,
                    "??,??" + statusCode);
            ret = ErrorUtil.errorJson("ERROR.HTTP.001", exception.getMessage());
        }

        LogUtil.d(AsyncHttpPost.class.getName(), "AsyncHttpPost  request to url :" + url + "  finished !");
    } catch (java.lang.IllegalArgumentException e) {
        RequestException exception = new RequestException(RequestException.IO_EXCEPTION,
                Constants.ERROR_MESSAGE);
        ret = ErrorUtil.errorJson("ERROR.HTTP.002", exception.getMessage());
        LogUtil.d(AsyncHttpGet.class.getName(),
                "AsyncHttpPost  request to url :" + url + "  onFail  " + e.getMessage());
    } catch (org.apache.http.conn.ConnectTimeoutException e) {
        RequestException exception = new RequestException(RequestException.SOCKET_TIMEOUT_EXCEPTION,
                Constants.ERROR_MESSAGE);
        ret = ErrorUtil.errorJson("ERROR.HTTP.003", exception.getMessage());
        LogUtil.d(AsyncHttpPost.class.getName(),
                "AsyncHttpPost  request to url :" + url + "  onFail  " + e.getMessage());
    } catch (java.net.SocketTimeoutException e) {
        RequestException exception = new RequestException(RequestException.SOCKET_TIMEOUT_EXCEPTION,
                Constants.ERROR_MESSAGE);
        ret = ErrorUtil.errorJson("ERROR.HTTP.004", exception.getMessage());
        LogUtil.d(AsyncHttpPost.class.getName(),
                "AsyncHttpPost  request to url :" + url + "  onFail  " + e.getMessage());
    } catch (UnsupportedEncodingException e) {
        RequestException exception = new RequestException(RequestException.UNSUPPORTED_ENCODEING_EXCEPTION,
                "?");
        ret = ErrorUtil.errorJson("ERROR.HTTP.005", exception.getMessage());
        LogUtil.d(AsyncHttpPost.class.getName(),
                "AsyncHttpPost  request to url :" + url + "  UnsupportedEncodingException  " + e.getMessage());
    } catch (org.apache.http.conn.HttpHostConnectException e) {
        RequestException exception = new RequestException(RequestException.CONNECT_EXCEPTION, "");
        ret = ErrorUtil.errorJson("ERROR.HTTP.006", exception.getMessage());
        LogUtil.d(AsyncHttpPost.class.getName(),
                "AsyncHttpPost  request to url :" + url + "  HttpHostConnectException  " + e.getMessage());
    } catch (ClientProtocolException e) {
        RequestException exception = new RequestException(RequestException.CLIENT_PROTOL_EXCEPTION,
                "??");
        ret = ErrorUtil.errorJson("ERROR.HTTP.007", exception.getMessage());
        e.printStackTrace();
        LogUtil.d(AsyncHttpPost.class.getName(),
                "AsyncHttpPost  request to url :" + url + "  ClientProtocolException " + e.getMessage());
    } catch (IOException e) {
        RequestException exception = new RequestException(RequestException.IO_EXCEPTION, "??");
        ret = ErrorUtil.errorJson("ERROR.HTTP.008", exception.getMessage());
        e.printStackTrace();
        LogUtil.d(AsyncHttpPost.class.getName(),
                "AsyncHttpPost  request to url :" + url + "  IOException  " + e.getMessage());
    } finally {
        if (!Constants.IS_STOP_REQUEST) {
            Message msg = new Message();
            msg.obj = ret;
            LogUtil.d("", ret);
            msg.getData().putSerializable("callback", callBack);
            resultHandler.sendMessage(msg);
        }
        //
        if (customLoadingDialog != null && customLoadingDialog.isShowing()) {
            customLoadingDialog.dismiss();
            customLoadingDialog = null;
        }
    }
    super.run();
}

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

public void updatausersex(final String sex) {
    new Thread() {
        Message msg = new Message();

        public void run() {
            String data = "&userid=" + user.getUserId() + "&sex=" + sex;
            Log.e("data is ", data);
            String result_data = NetUtil.getResponse(WebAddress.UPDATAUSERSEX, data);
            Log.e("successful", result_data);
            try {
                JSONObject obj = new JSONObject(result_data);
                msg.what = CommunalInterfaces.UPDATAUSERSEX;
                msg.obj = obj;/*from  w w w.j  a  va  2s .c o m*/
            } catch (JSONException e) {
                e.printStackTrace();
            } finally {
                handler.sendMessage(msg);
            }
        }
    }.start();
}