Example usage for android.os Message getData

List of usage examples for android.os Message getData

Introduction

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

Prototype

public Bundle getData() 

Source Link

Document

Obtains a Bundle of arbitrary data associated with this event, lazily creating it if necessary.

Usage

From source file:org.videolan.vlc.gui.video.VideoPlayerActivity.java

private void handleVout(Message msg) {
    if (msg.getData().getInt("data") == 0 && !mEndReached) {
        /* Video track lost, open in audio mode */
        Log.i(TAG, "Video track lost, switching to audio");
        mSwitchingView = true;/*from   www.j a  va 2s.  c  o m*/
        //            finish();
        String title = this.getResources().getString(R.string.encountered_error_title);
        String message = this.getResources().getString(R.string.encountered_error_message);
        ShowNotifyDialog mDialog = new ShowNotifyDialog(VideoPlayerActivity.this, R.style.myDialogTheme, title,
                message);
        mDialog.setOnSureClick("", new ShowNotifyDialog.OnSureClick() {

            @Override
            public void onClick(View view) {
                // TODO Auto-generated method stub
                finish();
            }
        });
        mDialog.show();
    }
}

From source file:applab.search.client.SynchronizationManager.java

/**
 * Our two background processes (downloading and parsing) communicate with us through Android messaging on the UI
 * thread (so we can react by manipulating UI)
 *///  w w  w.j  a va2  s . c  o  m
void handleBackgroundThreadMessage(Message message) {
    switch (message.what) {
    case GlobalConstants.KEYWORD_DOWNLOAD_STARTING:
        // TODO: Can we do this on the UI thread before we offload the process into the background?
        // it would cleanup the code, allow us to easily thread in Global.SETUP_DIALOG when Storage is empty,
        // and avoid a few extra thread switches
        if (!this.launchedFromTimer) {
            ProgressDialogManager.displayProgressDialog(GlobalConstants.UPDATE_DIALOG, this.currentContext);
        }
        break;
    case GlobalConstants.CONNECTION_ERROR:
        ProgressDialogManager.tryDestroyProgressDialog();
        if (!this.launchedFromTimer) {
            showErrorDialog(R.string.connection_error_message);
        }
        break;
    case GlobalConstants.KEYWORD_DOWNLOAD_SUCCESS:
        // TODO: do we want to update the progress dialog here?
        // download complete, start parsing
        // NOTE: we do not dismiss the dialog, so that it shows until we receive
        // the Global.KEYWORD_PARSE_GOT_NODE_TOTAL signal
        break;
    case GlobalConstants.KEYWORD_DOWNLOAD_FAILURE:
        ProgressDialogManager.tryDestroyProgressDialog(); // Dialog may still be launched in background process
                                                          // as a side-effect
        if (!this.launchedFromTimer) {
            showErrorDialog(R.string.incomplete_keyword_response_error);
        }
        break;
    case GlobalConstants.KEYWORD_PARSE_GOT_NODE_TOTAL:
        int nodeCount = message.getData().getInt("nodeCount");
        if (!this.launchedFromTimer) {
            ProgressDialogManager.displayProgressDialog(GlobalConstants.PARSE_DIALOG, this.currentContext,
                    nodeCount);
        }
        break;
    case GlobalConstants.KEYWORD_PARSE_SUCCESS:
        ProgressDialogManager.tryDestroyProgressDialog();
        Toast updateToast = Toast.makeText(this.currentContext,
                this.currentContext.getString(R.string.refreshed), Toast.LENGTH_LONG);
        updateToast.show();
        // TODO: Decide whether to check for image updates here right after the keyword update and before
        // releasing the synchronization lock.
        // in the error case, this is updated on click of the error dialog "OK" button. On success
        // it should hit this path
        SynchronizationManager.completeSynchronization();
        break;
    case GlobalConstants.KEYWORD_PARSE_ERROR:
        ProgressDialogManager.tryDestroyProgressDialog();
        if (!this.launchedFromTimer) {
            showErrorDialog(R.string.keyword_parse_error);
        }
        break;
    case GlobalConstants.DISMISS_WAIT_DIALOG:
        ProgressDialogManager.tryDestroyProgressDialog();
        break;
    }

    if (this.completionCallback != null) {
        this.completionCallback.sendEmptyMessage(message.what);
    }
}

From source file:com.zld.ui.ZldNewActivity.java

/**
 * ?? : 2015417 ?://from   ww  w  . j a va2  s.  c  o m
 *
 * @param msg param
 * @throws IOException
 */
private void showExitInfo(Message msg) throws IOException {
    int x, y, width, height, nType;
    Log.e(TAG, "????");
    CarBitmapInfo exitCarBmpInfo = new CarBitmapInfo();
    detailsFragment.hidePopupWindow();
    if (msg.obj instanceof Bitmap) {
        resultBitmap = (Bitmap) msg.obj;
        Bundle bd = msg.getData();
        //         int billingType = bd.getInt("billingType");
        nType = bd.getInt("nType");
        String carPlate = bd.getString("carPlate");
        x = bd.getInt("xCoordinate");
        y = bd.getInt("yCoordinate");
        width = bd.getInt("carPlatewidth");
        height = bd.getInt("carPlateheight");
        exitCarBmpInfo.setCarPlate(carPlate);
        exitCarBmpInfo.setBitmap(resultBitmap);
        exitCarBmpInfo.setCarPlateheight(height);
        exitCarBmpInfo.setCarPlatewidth(width);
        exitCarBmpInfo.setxCoordinate(x);
        exitCarBmpInfo.setyCoordinate(y);
        exitCarBmpInfo.setNtype(nType);
        int resType = bd.getInt("resType");
        cameraExitIp = bd.getString("cameraIp");
        if (!carPlate.contains("")) {
            String param = SharedPreferencesUtils.getParam(getApplicationContext(), "zld_config", "carPlate",
                    null);
            long currentTimeMillis = System.currentTimeMillis();
            long param2 = SharedPreferencesUtils.getParam(getApplicationContext(), "zld_config", "current_time",
                    currentTimeMillis);
            Log.e(TAG, "" + param + "=" + currentTimeMillis);
            // ??null ??
            if (param != null && param2 != 0L && param2 != currentTimeMillis) {
                //?? ?-? ?? 1
                //? return ?
                long time = currentTimeMillis - param2;
                Log.e(TAG, "" + time);
                if (carPlate.equals(param) && (currentTimeMillis - param2) < 30 * 1000) {
                    Log.e(TAG, "" + carPlate);
                    return;
                }
            }
        }
        exitledinfo = selectIpOut.get(cameraExitIp);
        if (cameraipPassid.get(cameraExitIp) != null) {
            passid = cameraipPassid.get(cameraExitIp).getPassid();
        }
        exitFragment.refreshAllView(exitCarBmpInfo);
        if (resType == 8) {
            setDetailInCarState(ComeInCarState.EXIT_COME_IN_CAR_STATE);
            /*??,??*/
            beforeRefresh();
            //??
            if (!AppInfo.getInstance().getIsLocalServer(ZldNewActivity.this)) {//???
                                                                               // 
                boolean param = SharedPreferencesUtils.getParam(getApplicationContext(), "nettype", "isLocal",
                        false);
                Log.e("isLocal", "ZldNewActivity showExitInfo get isLocal " + param);
                if (param) {
                    //                  getLocalOrderDBManager();
                    if (listFragment != null && listFragment.orderListState != null) {
                        listFragment.orderListState.setState(OrderListState.AUTO_SEARCH_STATE);
                    }
                    //                  doAutoSearchTimeOut(resultBitmap,billingType, carPlate);
                    //                  return;
                }
            }
            hideSeal();
            /* ??,,*/
            hidePrepay();
            showCost();
            setDetailInCarState(ComeInCarState.EXIT_COME_IN_CAR_STATE);
            Log.e(TAG, "???" + detailsFragment.comeInCarState.getState());
            isExitComeinCar = true;
            /* ??? ?? ?*/
            FileUtil.writeSDFile("LOG",
                    "?>>>>>>>>>showExitInfo  " + exitCarBmpInfo.getCarPlate());
            //            HttpManager.UpLogs(ZldNewActivity.this,"?>>>>>>>>>showExitInfo  "+exitCarBmpInfo.getCarPlate());
            search(exitCarBmpInfo.getCarPlate());

        } else if (resType == 4) {
            /* ? */
            /*??takePhotoLinsternull?
               ??,????*/
            if (takePhotoLinster != null) {
                takePhotoLinster.setTakePhotoLinster(resultBitmap);
            }
        }
    }
}

From source file:com.nbplus.iotapp.service.IoTService.java

public void handleMessage(Message msg) {
    if (msg == null) {
        return;//from  w w  w  .j a  v a2 s  . c o m
    }
    Log.d(TAG, "handle message msg.what = " + msg.what);
    switch (msg.what) {
    // when using iot gateway
    case IoTServiceCommand.IOT_GATEWAY_CONNECTED: {
        Log.d(TAG, "IoTServiceCommand.IOT_GATEWAY_CONNECTED received...");
        mIoTGatewayWorkerMessengerRef = new WeakReference<>(msg.replyTo);
        // TODO : test handler
        if (mIoTGatewayWorkerMessengerRef != null) {
            try {
                Messenger workerMessenger = mIoTGatewayWorkerMessengerRef.get();
                if (workerMessenger != null) {
                    Message testMsg = new Message();
                    msg.what = IoTServiceCommand.IOT_GATEWAY_DISCONNECTED;
                    Log.d(TAG, "test IoTServiceCommand.IOT_GATEWAY_DISCONNECTED");
                    workerMessenger.send(testMsg);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        break;
    }
    case IoTServiceCommand.SCANNING_START: {
        Bundle extras = msg.getData();
        if (extras == null) {
            Log.w(TAG, "Scanning bundle data is not found !!!");
            return;
        }
        boolean isPeriodic = extras.getBoolean(IoTServiceCommand.KEY_DATA);
        Log.d(TAG, "IoTServiceCommand.SCANNING_START called. periodic = " + isPeriodic);
        if (mUseIoTGateway) {

        } else {
            if (mBluetoothLeService != null && mServiceStatus == IoTServiceStatus.RUNNING) {
                mIsBleScanPeriodic = isPeriodic;
                mBluetoothLeService.scanLeDevicePeriodically(true, isPeriodic);
            }
        }
        break;
    }
    case IoTServiceCommand.SCANNING_STOP: {
        Bundle extras = msg.getData();
        if (extras == null) {
            Log.w(TAG, "Scanning bundle data is not found !!!");
            return;
        }
        //boolean isPeriodic = extras.getBoolean(IoTServiceCommand.KEY_DATA);
        Log.d(TAG, "IoTServiceCommand.SCANNING_STOP called.");
        if (mUseIoTGateway) {

        } else {
            if (mBluetoothLeService != null && mServiceStatus == IoTServiceStatus.RUNNING) {
                mIsBleScanPeriodic = false;
                mBluetoothLeService.scanLeDevicePeriodically(false, false);
            }
        }
        break;
    }
    case HANDLER_MESSAGE_CONNECTIVITY_CHANGED:
        final boolean isConnected = NetworkUtils.isConnected(this);
        Log.d(TAG, "HANDLER_MESSAGE_CONNECTIVITY_CHANGED received isConnected = " + isConnected);
        if (mLastConnectionStatus == isConnected) {
            Log.d(TAG, "mLastConnectionStatus == isConnected do not anything.");
            return;
        }

        mLastConnectionStatus = isConnected;
        if (mLastConnectionStatus) {
            Log.d(TAG, "HANDLER_MESSAGE_CONNECTIVITY_CHANGED network is connected !!!");
            // TODO : re-connect
            if (mServiceStatus == IoTServiceStatus.STOPPED) {

            }
        } else {
            Log.d(TAG, "HANDLER_MESSAGE_CONNECTIVITY_CHANGED network is disconnected !!!");
        }
        break;
    case HANDLER_MESSAGE_BT_STATE_CHANGED:
        Log.d(TAG, "HANDLER_MESSAGE_CONNECTIVITY_CHANGED received !!!");
        final int state = msg.arg1;
        if ((mLastConnectionStatus && state == BluetoothAdapter.STATE_ON)
                || (!mLastConnectionStatus && state == BluetoothAdapter.STATE_OFF)) {
            return;
        }

        mLastConnectionStatus = (state == BluetoothAdapter.STATE_ON) ? true : false;
        if (mLastConnectionStatus) {
            Log.d(TAG, "HANDLER_MESSAGE_BT_STATE_CHANGED bluetooth is enabled !!!");

            if (mServiceStatus != IoTServiceStatus.RUNNING) {
                final Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
                if (!bindService(gattServiceIntent, mBluetoothServiceConnection, BIND_AUTO_CREATE)) {
                    Log.e(TAG, ">> bind BluetoothServiceConnection failed.... !!!");
                }
            }
        } else {
            Log.d(TAG, "HANDLER_MESSAGE_BT_STATE_CHANGED bluetooth is disabled !!!");
            mErrorCodes = IoTResultCodes.BLUETOOTH_NOT_ENABLED;
            unbindService(mBluetoothServiceConnection);

            mServiceStatus = IoTServiceStatus.STOPPED;
            mHandler.removeMessages(HANDLER_MESSAGE_CONNECTION_NOT_RESPOND);
            mConnectedDeviceList.clear();
            mRequestHandleMap.clear();

            sendServiceStatusNotification();
        }
        break;
    case IoTServiceCommand.REGISTER_SERVICE: {
        Bundle b = msg.getData();
        if (msg.replyTo == null || b == null) {
            Log.e(TAG, "Invalid register args...");
            break;
        }

        String msgId = b.getString(IoTServiceCommand.KEY_MSGID, "");
        if (!StringUtils.isEmptyString(msgId)) {
            Log.d(TAG, "msgId == " + msgId);
            String[] strArrays = msgId.split("_");
            if (strArrays.length == 2) {
                mRegisteredAppMessenger = new WeakReference<>(msg.replyTo);
                sendResultToApplication(msg.replyTo, msgId, null, msg.what, IoTResultCodes.SUCCESS);

                // ??  ??  ? ? .
                sendServiceStatusNotification();
            } else {
                Log.e(TAG, "Invalid register args...");
                sendResultToApplication(msg.replyTo, msgId, null, msg.what,
                        IoTResultCodes.INVALID_REQUEST_ARGUMENTS);
                break;
            }
        } else {
            Log.e(TAG, "Invalid register args...");
            sendResultToApplication(msg.replyTo, "", null, msg.what, IoTResultCodes.INVALID_REQUEST_ARGUMENTS);
            break;
        }

        break;
    }
    case IoTServiceCommand.UNREGISTER_SERVICE: {
        Bundle b = msg.getData();
        if (b == null) {
            Log.e(TAG, "Invalid register args...");
            break;
        }

        String msgId = b.getString(IoTServiceCommand.KEY_MSGID, "");
        if (!StringUtils.isEmptyString(msgId)) {
            String[] strArrays = msgId.split("_");
            if (strArrays.length == 2) {
                Messenger clientMessenger = (mRegisteredAppMessenger == null) ? null
                        : mRegisteredAppMessenger.get();
                if (clientMessenger != null) {
                    sendResultToApplication(clientMessenger, msgId, null, msg.what, IoTResultCodes.SUCCESS);
                    mRegisteredAppMessenger = null;
                } else {
                    //??
                }
            } else {
                Log.e(TAG, "Invalid register args...");
                break;
            }
        } else {
            Log.e(TAG, "Invalid un-register args...");
        }
        break;
    }

    case IoTServiceCommand.GET_DEVICE_LIST: {
        if (mUseIoTGateway) {
            // TODO
        } else {
            mBluetoothLeService.scanLeDevice(false);
            mBluetoothLeService.scanLeDevicePeriodically(true, mIsBleScanPeriodic);
        }
        break;
    }

    case IoTServiceCommand.DEVICE_DISCONNECT_ALL: {
        Bundle b = msg.getData();
        String msgId = b.getString(IoTServiceCommand.KEY_MSGID, "");
        b.setClassLoader(IoTHandleData.class.getClassLoader());
        IoTHandleData ioTHandleData = b.getParcelable(IoTServiceCommand.KEY_DATA);

        if (mConnectedDeviceList.size() > 0) {
            mIsDisconnectAllState = true;
            ioTHandleData.setMsgId(msgId);
            ioTHandleData.setRequestCommand(msg.what);

            String connectedDeviceId = mConnectedDeviceList.get(0);
            if (mUseIoTGateway) {
                // TODO

            } else {
                if (mBluetoothLeService != null) {
                    mBluetoothLeService.disconnect(connectedDeviceId);
                } else {
                    Messenger clientMessenger = (mRegisteredAppMessenger == null) ? null
                            : mRegisteredAppMessenger.get();
                    sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what,
                            IoTResultCodes.FAILED);
                }
            }
        } else {
            Messenger clientMessenger = (mRegisteredAppMessenger == null) ? null
                    : mRegisteredAppMessenger.get();
            sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what,
                    IoTResultCodes.SUCCESS);
        }
        break;
    }

    case IoTServiceCommand.DEVICE_CONNECT: {
        Bundle b = msg.getData();
        b.setClassLoader(IoTHandleData.class.getClassLoader());
        IoTHandleData ioTHandleData = b.getParcelable(IoTServiceCommand.KEY_DATA);
        String msgId = b.getString(IoTServiceCommand.KEY_MSGID, "");
        Messenger clientMessenger = (mRegisteredAppMessenger == null) ? null : mRegisteredAppMessenger.get();

        if (ioTHandleData == null) {
            sendResultToApplication(clientMessenger, msgId, null, msg.what, IoTResultCodes.FAILED);
            Log.w(TAG, "case READ_WRITE_SETNOTI : ioTHandleData is null");
            return;
        }

        if (mRequestHandleMap.get(ioTHandleData.getDeviceId()) != null) {
            Log.d(TAG, "Already previous command deviceid = " + ioTHandleData.getDeviceId() + ", command = "
                    + ioTHandleData.getRequestCommand());
            sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what,
                    IoTResultCodes.FAILED);
            return;
        }

        if (mUseIoTGateway) {
        } else {
            if (mBluetoothLeService == null) {
                sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what,
                        IoTResultCodes.FAILED);
                Log.w(TAG,
                        "case IoTServiceCommand.DEVICE_CONNECT : mBluetoothLeService or ioTHandleData is null");
                return;
            }
            if (ioTHandleData.getDeviceTypeId() != IoTDevice.DEVICE_TYPE_ID_BT) {
                sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what,
                        IoTResultCodes.FAILED);
                Log.w(TAG,
                        "case IoTServiceCommand.DEVICE_DISCONNECT : is not bt device... mUseIoTGateway == false");
                return;
            }

            if (ioTHandleData.isKeepAliveDevice()) {
                if (mKeepAliveConnectionDeviceList.contains(ioTHandleData.getDeviceId())) {
                    Log.d(TAG, "Keep alive device is already connected.. id = " + ioTHandleData.getDeviceId());
                    sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what,
                            IoTResultCodes.SUCCESS);

                    // send to IoT interface module
                    Message connectedMsg = new Message();
                    connectedMsg.what = IoTServiceCommand.DEVICE_CONNECTED;
                    Bundle extras = new Bundle();
                    extras.putString(IoTServiceCommand.KEY_DEVICE_UUID, ioTHandleData.getDeviceId());
                    connectedMsg.setData(extras);

                    sendNotificationToApplication(connectedMsg);
                    return;
                }
            }

            if (mBluetoothLeService.connect(ioTHandleData.getDeviceId())) {
                ioTHandleData.setMsgId(msgId);
                ioTHandleData.setRequestCommand(msg.what);

                mRequestHandleMap.put(ioTHandleData.getDeviceId(), ioTHandleData);
                sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what,
                        IoTResultCodes.SUCCESS);
                // ?... connect  ?  .
                Message notRespondMsg = new Message();
                notRespondMsg.what = HANDLER_MESSAGE_CONNECTION_NOT_RESPOND;
                Bundle extras = new Bundle();
                extras.putParcelable(IoTServiceCommand.KEY_DATA, ioTHandleData);
                notRespondMsg.setData(extras);
                mHandler.sendMessageDelayed(notRespondMsg, CONNECTION_NOT_RESPOND_WAIT_TIME);
            } else {
                Log.w(TAG, "mBluetoothLeService.connect() return false");
                sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what,
                        IoTResultCodes.FAILED);
            }
        }
        break;
    }

    case HANDLER_MESSAGE_CONNECTION_NOT_RESPOND: {
        Log.d(TAG, "HANDLER_MESSAGE_CONNECTION_NOT_RESPOND ...");
        Bundle b = msg.getData();
        b.setClassLoader(IoTHandleData.class.getClassLoader());
        IoTHandleData ioTHandleData = b.getParcelable(IoTServiceCommand.KEY_DATA);
        if (mBluetoothLeService != null) {
            mBluetoothLeService.disconnect(ioTHandleData.getDeviceId());
        }
        mRequestHandleMap.remove(ioTHandleData.getDeviceId());
        Messenger clientMessenger = (mRegisteredAppMessenger == null) ? null : mRegisteredAppMessenger.get();
        sendResultToApplication(clientMessenger, ioTHandleData.getMsgId(), ioTHandleData.getDeviceId(),
                IoTServiceCommand.DEVICE_CONNECT, IoTResultCodes.DEVICE_CONNECTION_NOT_RESPOND);
        break;
    }

    case IoTServiceCommand.DEVICE_DISCONNECT: {
        Bundle b = msg.getData();
        b.setClassLoader(IoTHandleData.class.getClassLoader());
        IoTHandleData ioTHandleData = b.getParcelable(IoTServiceCommand.KEY_DATA);
        String msgId = b.getString(IoTServiceCommand.KEY_MSGID, "");
        Messenger clientMessenger = (mRegisteredAppMessenger == null) ? null : mRegisteredAppMessenger.get();

        if (ioTHandleData == null) {
            sendResultToApplication(clientMessenger, msgId, null, msg.what, IoTResultCodes.FAILED);
            Log.w(TAG, "case READ_WRITE_SETNOTI : ioTHandleData is null");
            return;
        }

        if (mRequestHandleMap.get(ioTHandleData.getDeviceId()) != null) {
            Log.d(TAG, "Already previous command deviceid = " + ioTHandleData.getDeviceId() + ", command = "
                    + ioTHandleData.getRequestCommand());
            sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what,
                    IoTResultCodes.FAILED);
            return;
        }

        if (mUseIoTGateway) {
        } else {
            if (mBluetoothLeService == null) {
                sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what,
                        IoTResultCodes.FAILED);
                Log.w(TAG,
                        "case IoTServiceCommand.DEVICE_DISCONNECT : mBluetoothLeService or ioTHandleData is null");
                return;
            }
            if (ioTHandleData.getDeviceTypeId() != IoTDevice.DEVICE_TYPE_ID_BT) {
                sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what,
                        IoTResultCodes.FAILED);
                Log.w(TAG,
                        "case IoTServiceCommand.DEVICE_DISCONNECT : is not bt device... mUseIoTGateway == false");
                return;
            }

            if (mConnectedDeviceList.contains(ioTHandleData.getDeviceId())
                    || mKeepAliveConnectionDeviceList.contains(ioTHandleData.getDeviceId())) {
                ioTHandleData.setMsgId(msgId);
                ioTHandleData.setRequestCommand(msg.what);

                mRequestHandleMap.put(ioTHandleData.getDeviceId(), ioTHandleData);
                sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what,
                        IoTResultCodes.SUCCESS);
                mBluetoothLeService.disconnect(ioTHandleData.getDeviceId());
            } else {
                Log.w(TAG, "mConnectedDeviceList.contains(ioTHandleData.getDeviceId()) is false");
                sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what,
                        IoTResultCodes.FAILED);
            }
        }
        break;
    }

    case IoTServiceCommand.DEVICE_READ_DATA:
    case IoTServiceCommand.DEVICE_WRITE_DATA:
    case IoTServiceCommand.DEVICE_SET_NOTIFICATION: {
        Bundle b = msg.getData();
        b.setClassLoader(IoTHandleData.class.getClassLoader());
        IoTHandleData ioTHandleData = b.getParcelable(IoTServiceCommand.KEY_DATA);
        String msgId = b.getString(IoTServiceCommand.KEY_MSGID, "");
        Messenger clientMessenger = (mRegisteredAppMessenger == null) ? null : mRegisteredAppMessenger.get();

        if (ioTHandleData == null) {
            sendResultToApplication(clientMessenger, msgId, null, msg.what, IoTResultCodes.FAILED);
            Log.w(TAG, "case READ_WRITE_SETNOTI : ioTHandleData is null");
            return;
        }

        if (mRequestHandleMap.get(ioTHandleData.getDeviceId()) != null) {
            Log.d(TAG, "Already previous command deviceid = " + ioTHandleData.getDeviceId() + ", command = "
                    + ioTHandleData.getRequestCommand());
            sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what,
                    IoTResultCodes.FAILED);
            return;
        }

        if (mUseIoTGateway) {
        } else {
            if (mBluetoothLeService == null) {
                sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what,
                        IoTResultCodes.FAILED);
                Log.w(TAG, "case READ_WRITE_SETNOTI : ioTHandleData is null");
                return;
            }

            if (ioTHandleData.getDeviceTypeId() != IoTDevice.DEVICE_TYPE_ID_BT) {
                sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what,
                        IoTResultCodes.FAILED);
                Log.w(TAG, "case READ_WRITE_SETNOTI : is not bt device... mUseIoTGateway == false");
                return;
            }

            if (mConnectedDeviceList.contains(ioTHandleData.getDeviceId())
                    || mKeepAliveConnectionDeviceList.contains(ioTHandleData.getDeviceId())) {
                ioTHandleData.setMsgId(msgId);
                ioTHandleData.setRequestCommand(msg.what);

                boolean result = true;
                switch (msg.what) {
                case IoTServiceCommand.DEVICE_READ_DATA:
                    result = mBluetoothLeService.readCharacteristic(ioTHandleData.getDeviceId(),
                            ioTHandleData.getServiceUuid(), ioTHandleData.getCharacteristicUuid());
                    break;
                case IoTServiceCommand.DEVICE_WRITE_DATA:
                    result = mBluetoothLeService.writeRemoteCharacteristic(ioTHandleData.getDeviceId(),
                            ioTHandleData.getServiceUuid(), ioTHandleData.getCharacteristicUuid(),
                            ioTHandleData.getValue());
                    break;
                case IoTServiceCommand.DEVICE_SET_NOTIFICATION:
                    result = mBluetoothLeService.setCharacteristicNotification(ioTHandleData.getDeviceId(),
                            ioTHandleData.getServiceUuid(), ioTHandleData.getCharacteristicUuid(), true);
                    break;
                }

                if (result) {
                    mRequestHandleMap.put(ioTHandleData.getDeviceId(), ioTHandleData);
                    sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what,
                            IoTResultCodes.SUCCESS);
                } else {
                    sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what,
                            IoTResultCodes.FAILED);
                }
            } else {
                Log.w(TAG, "mConnectedDeviceList.contains(ioTHandleData.getDeviceId()) is false");
                sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what,
                        IoTResultCodes.FAILED);
            }
        }
        break;
    }

    }
}

From source file:com.linkbubble.ui.ContentView.java

private void onUrlLongClick(final WebView webView, final String urlAsString, final int type) {
    Resources resources = getResources();

    final ArrayList<String> longClickSelections = new ArrayList<String>();

    final String shareLabel = resources.getString(R.string.action_share);
    longClickSelections.add(shareLabel);

    String defaultBrowserLabel = Settings.get().getDefaultBrowserLabel();

    final String leftConsumeBubbleLabel = Settings.get().getConsumeBubbleLabel(BubbleAction.ConsumeLeft);
    if (leftConsumeBubbleLabel != null) {
        if (defaultBrowserLabel == null || defaultBrowserLabel.equals(leftConsumeBubbleLabel) == false) {
            longClickSelections.add(leftConsumeBubbleLabel);
        }/*  w w w.  j  a  v a 2s  .com*/
    }

    final String rightConsumeBubbleLabel = Settings.get().getConsumeBubbleLabel(BubbleAction.ConsumeRight);
    if (rightConsumeBubbleLabel != null) {
        if (defaultBrowserLabel == null || defaultBrowserLabel.equals(rightConsumeBubbleLabel) == false) {
            longClickSelections.add(rightConsumeBubbleLabel);
        }
    }

    // Long pressing for a link doesn't work reliably, re #279
    //final String copyLinkLabel = resources.getString(R.string.action_copy_to_clipboard);
    //longClickSelections.add(copyLinkLabel);

    Collections.sort(longClickSelections);

    final String openLinkInNewBubbleLabel = resources.getString(R.string.action_open_link_in_new_bubble);
    final String openImageInNewBubbleLabel = resources.getString(R.string.action_open_image_in_new_bubble);
    if (type == WebView.HitTestResult.IMAGE_TYPE || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
        longClickSelections.add(0, openImageInNewBubbleLabel);
    }
    if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
        longClickSelections.add(0, openLinkInNewBubbleLabel);
    }

    final String openInBrowserLabel = defaultBrowserLabel != null
            ? String.format(resources.getString(R.string.action_open_in_browser), defaultBrowserLabel)
            : null;
    if (openInBrowserLabel != null) {
        longClickSelections.add(1, openInBrowserLabel);
    }

    final String saveImageLabel = resources.getString(R.string.action_save_image);
    if (type == WebView.HitTestResult.IMAGE_TYPE || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
        longClickSelections.add(saveImageLabel);
    }

    ListView listView = new ListView(getContext());
    listView.setAdapter(new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1,
            longClickSelections.toArray(new String[0])));
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            CrashTracking.log("ContentView listView.setOnItemClickListener");
            String string = longClickSelections.get(position);
            if (string.equals(openLinkInNewBubbleLabel)
                    && type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
                Message msg = new Message();
                msg.setTarget(new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        Bundle b = msg.getData();
                        if (b != null && b.getString("url") != null) {
                            MainController.get().openUrl(b.getString("url"), System.currentTimeMillis(), false,
                                    Analytics.OPENED_URL_FROM_NEW_TAB);
                        }
                    }
                });
                webView.requestFocusNodeHref(msg);
            }
            if (string.equals(openLinkInNewBubbleLabel) || string.equals(openImageInNewBubbleLabel)) {
                MainController controller = MainController.get();
                if (null != controller) {
                    controller.openUrl(urlAsString, System.currentTimeMillis(), false,
                            Analytics.OPENED_URL_FROM_NEW_TAB);
                } else {
                    MainApplication.openLink(getContext(), urlAsString, Analytics.OPENED_URL_FROM_NEW_TAB);
                }
            } else if (openInBrowserLabel != null && string.equals(openInBrowserLabel)) {
                openInBrowser(urlAsString);
            } else if (string.equals(shareLabel)) {
                showSelectShareMethod(urlAsString, false);
            } else if (string.equals(saveImageLabel)) {
                saveImage(urlAsString);
            } else if (leftConsumeBubbleLabel != null && string.equals(leftConsumeBubbleLabel)) {
                MainApplication.handleBubbleAction(getContext(), BubbleAction.ConsumeLeft, urlAsString, -1);
            } else if (rightConsumeBubbleLabel != null && string.equals(rightConsumeBubbleLabel)) {
                MainApplication.handleBubbleAction(getContext(), BubbleAction.ConsumeRight, urlAsString, -1);
                //} else if (string.equals(copyLinkLabel)) {
                //    MainApplication.copyLinkToClipboard(getContext(), urlAsString, R.string.link_copied_to_clipboard);
            }

            if (mLongPressAlertDialog != null) {
                mLongPressAlertDialog.dismiss();
            }
        }
    });
    listView.setBackgroundColor(Settings.get().getThemedContentViewColor());

    mLongPressAlertDialog = new AlertDialog.Builder(getContext()).create();
    mLongPressAlertDialog.setView(listView);
    mLongPressAlertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
    mLongPressAlertDialog.show();
}

From source file:com.nbplus.iotlib.IoTInterface.java

private void handleServiceMessage(Message msg) {
    switch (msg.what) {
    case IoTServiceCommand.COMMAND_RESPONSE: {
        Bundle b = msg.getData();
        if (b == null) {
            Log.w(TAG, "bundle data is null");
            return;
        }//w w  w . jav a 2  s.c o m
        handleResponse(b);
        break;
    }

    // bt command ??   ?.
    // 3 ? ? ...
    case HANDLER_COMMAND_NOT_RESPOND: {
        Log.d(TAG, "HANDLER_COMMAND_NOT_RESPOND retry or next device..");
        if (mCommandRetryCount < MAX_CONNECTION_RETRY) {
            retryDeviceCommand();
        } else {
            mCurrentRetrieveIndex++;
            sendConnectToDeviceMessage(mCurrentRetrieveIndex);
        }
        break;
    }
    case IoTServiceCommand.SERVICE_STATUS_NOTIFICATION: {
        Log.d(TAG, "IoTServiceCommand.SERVICE_STATUS_NOTIFICATION");
        Bundle b = msg.getData();
        if (b == null) {
            Log.w(TAG, "bundle data is null");
            return;
        }
        b.setClassLoader(IoTServiceStatus.class.getClassLoader());
        IoTServiceStatus serviceStatus = (IoTServiceStatus) b
                .getSerializable(IoTServiceCommand.KEY_SERVICE_STATUS);
        if (mServiceStatus.equals(serviceStatus)) {
            Log.w(TAG, "same service status received.");
            return;
        }
        mServiceStatus = serviceStatus;

        Intent intent = new Intent(IoTConstants.ACTION_IOT_SERVICE_STATUS_CHANGED);
        intent.putExtra(IoTConstants.EXTRA_SERVICE_STATUS, (mServiceStatus == IoTServiceStatus.RUNNING));
        LocalBroadcastManager.getInstance(mCtx).sendBroadcast(intent);

        b.setClassLoader(IoTResultCodes.class.getClassLoader());
        mErrorCodes = (IoTResultCodes) b.getSerializable(IoTServiceCommand.KEY_SERVICE_STATUS_CODE);
        Log.d(TAG, "IoTServiceCommand.SERVICE_STATUS_NOTIFICATION : status = " + mServiceStatus + ", errCode = "
                + mErrorCodes);

        if (mServiceStatus == IoTServiceStatus.STOPPED) {
            Log.d(TAG, "initializeVariablesWhenStop() called");
            initializeVariablesWhenStop();
        } else if (mServiceStatus == IoTServiceStatus.RUNNING) {
            Log.d(TAG, "restart device scanning and retrives device data");
            if (mBondedWithServerList.size() > 0
                    && (mBondedEmergencyDeviceNumbers > 0 || mBondedKeepaliveDeviceNumbers > 0)) {
                Bundle extras = new Bundle();
                extras.putBoolean(IoTServiceCommand.KEY_DATA, true);
                sendMessageToService(IoTServiceCommand.SCANNING_START, extras);
            } else {
                Bundle extras = new Bundle();
                extras.putBoolean(IoTServiceCommand.KEY_DATA, false);
                sendMessageToService(IoTServiceCommand.SCANNING_STOP, extras);
            }
            // IoT ? ? .
            mHandler.removeMessages(HANDLER_RETRIEVE_IOT_DEVICES);
            mHandler.sendEmptyMessageDelayed(HANDLER_RETRIEVE_IOT_DEVICES, 10 * 1000);
        }
        break;
    }
    case IoTServiceCommand.DEVICE_LIST_NOTIFICATION: {
        Bundle b = msg.getData();
        handleDeviceListNotification(b);
        break;
    }

    case IoTServiceCommand.DEVICE_CONNECTED: {
        Bundle b = msg.getData();
        handleDeviceConnectedNotification(b);

        break;
    }

    case IoTServiceCommand.DEVICE_DISCONNECTED: {
        mHandler.removeMessages(HANDLER_WAIT_FOR_NOTIFY_DATA);
        Bundle b = msg.getData();
        handleDeviceDisconnectedNotification(b);

        break;
    }

    case IoTServiceCommand.DEVICE_WRITE_DATA_RESULT:
    case IoTServiceCommand.DEVICE_SET_NOTIFICATION_RESULT: {
        Log.d(TAG, "IoTServiceCommand.DEVICE_SET_NOTIFICATION_RESULT received");

        Bundle b = msg.getData();
        b.setClassLoader(IoTResultCodes.class.getClassLoader());
        IoTResultCodes resultCode = (IoTResultCodes) b.getSerializable(IoTServiceCommand.KEY_RESULT);
        if (IoTResultCodes.SUCCESS.equals(resultCode)) {
            // success set notifications.
            Log.d(TAG, "success set notification.. proceed next command");

            b.setClassLoader(IoTHandleData.class.getClassLoader());
            IoTHandleData resultData = b.getParcelable(IoTServiceCommand.KEY_DATA);
            if (resultData != null) {
                // xiaomi
                if (resultData.getCharacteristicUuid().equals(GattAttributes.MISCALE_CHARACTERISTIC_2A2F)) {
                    handleXiaomiScale(msg.what, resultData);
                } else if (resultData.getCharacteristicUuid().equals(GattAttributes.SMART_SENSOR)) {
                    handleSmartSensor(msg.what, resultData);
                } else if (resultData.getServiceUuid().equals(GattAttributes.GLUCOSE_SERVICE_UUID)) {
                    handleGlucoseMeasurement(msg.what, resultData);
                } else if (resultData.getServiceUuid().equals(GattAttributes.SMART_BAND_SERVICE_UUID)) {
                    handleSmartBand(msg.what, resultData);
                } else {
                    proceedDeviceCommand();
                }
            }
        } else {
            // fail set notifications.
            Log.d(TAG, "fail set notification.. disconnect device");
            mHandler.removeMessages(HANDLER_WAIT_FOR_NOTIFY_DATA);
            Message disconnMsg = new Message();
            disconnMsg.what = HANDLER_WAIT_FOR_NOTIFY_DATA;
            disconnMsg.arg1 = 1;
            mHandler.sendMessage(disconnMsg);
        }
        break;
    }

    case IoTServiceCommand.DEVICE_READ_DATA_RESULT:
    case IoTServiceCommand.DEVICE_NOTIFICATION_DATA: {
        // read ? notification ?  .
        //Log.d(TAG, "IoTServiceCommand.DEVICE_NOTIFICATION_DATA received");

        try {
            Bundle b = msg.getData();
            b.setClassLoader(IoTHandleData.class.getClassLoader());
            IoTHandleData resultData = b.getParcelable(IoTServiceCommand.KEY_DATA);
            if (resultData != null) {
                // xiaomi
                if (resultData.getCharacteristicUuid().equals(GattAttributes.MISCALE_CHARACTERISTIC_2A2F)) {
                    handleXiaomiScale(msg.what, resultData);
                } else if (resultData.getCharacteristicUuid().equals(GattAttributes.SMART_SENSOR)) {
                    handleSmartSensor(msg.what, resultData);
                } else if (resultData.getServiceUuid().equals(GattAttributes.GLUCOSE_SERVICE_UUID)) {
                    handleGlucoseMeasurement(msg.what, resultData);
                } else {
                    if (mIsEmergencyDataCollecting) {
                        handleSmartBand(msg.what, resultData);
                    } else {
                        // TODO : what???
                        proceedDeviceCommand();
                    }
                }
            }
        } catch (Exception e) {

        }
        break;
    }

    case HANDLER_RETRIEVE_IOT_DEVICES: {
        Log.d(TAG, "HANDLER_RETRIEVE_IOT_DEVICES received.. Clear all previous connection first..");
        if (mServiceStatus != IoTServiceStatus.RUNNING) {
            Intent intent = new Intent(IoTConstants.ACTION_IOT_DATA_SYNC_COMPLETED);
            LocalBroadcastManager.getInstance(mCtx).sendBroadcast(intent);
        } else {
            //   ?  ?? ? .
            Bundle extras = new Bundle();
            extras.putBoolean(IoTServiceCommand.KEY_DATA, false);
            sendMessageToService(IoTServiceCommand.SCANNING_STOP, extras);

            mHandler.removeMessages(HANDLER_RETRIEVE_IOT_DEVICES);
            sendMessageToService(IoTServiceCommand.DEVICE_DISCONNECT_ALL, null);
        }
        break;
    }

    case HANDLER_WAIT_FOR_NOTIFY_DATA: {
        mHandler.removeMessages(HANDLER_WAIT_FOR_NOTIFY_DATA);
        if (mCurrentRetrieveDevice == null || msg.arg1 == 0) {
            //  ? ?? ?? ... ?
            //  ?  .
            return;
        }
        Log.w(TAG, "I have no more scenario for this device = " + mCurrentRetrieveDevice.getDeviceName());
        Bundle extras = new Bundle();
        IoTHandleData data = new IoTHandleData();
        data.setDeviceId(mCurrentRetrieveDevice.getDeviceId());
        data.setDeviceTypeId(mCurrentRetrieveDevice.getDeviceTypeId());

        extras.putParcelable(IoTServiceCommand.KEY_DATA, data);
        sendMessageToService(IoTServiceCommand.DEVICE_DISCONNECT, extras);

        break;
    }

    case HANDLER_SEND_IOT_DEVICE_DATA_TASK_COMPLETED: {
        Log.d(TAG, "HANDLER_SEND_IOT_DEVICE_DATA_TASK_COMPLETED received... ");

        Intent intent = new Intent(IoTConstants.ACTION_IOT_DATA_SYNC_COMPLETED);
        LocalBroadcastManager.getInstance(mCtx).sendBroadcast(intent);

        BaseApiResult result = (BaseApiResult) msg.obj;
        if (BaseApiResult.RESULT_SUCCESS.equals(result.getResultCode())) {
            Log.d(TAG, "Send collected data to server success..");
        } else {
            Log.w(TAG, "Send collected data to server failed.. set unsent data");
            Bundle extras = msg.getData();
            if (extras != null) {
                IoTCollectedData data = extras.getParcelable("data");
                if (data == null) {
                    break;
                }

                mCollectedData.addAllIoTData(data.getIoTData());
                IoTServicePreference.setUnSentCollectedData(mCtx, mGson.toJson(mCollectedData));
            }
        }
        break;
    }

    default:
        break;
    }
}

From source file:org.harleydroid.HarleyDroidService.java

public void handleMessage(Message msg) {
    if (D)// www.j  a v  a 2s. c o  m
        Log.d(TAG, "handleMessage " + msg.what);

    switch (msg.what) {
    case MSG_NONE:
        mReconThread = null;
        mWantedState = msg.arg1;
        break;
    case MSG_CONNECTED:
        mHandler.obtainMessage(HarleyDroid.STATUS_CONNECTED, -1, -1).sendToTarget();
        HarleyDroidService.this.notify(R.string.notification_connected);
        J1850.resetCounters();
        mCurrentState = STATE_CONNECT;
        if (mLogging) {
            mLogger = new HarleyDroidLogger(HarleyDroidService.this, mMetric, mGPS, mLogRaw, mLogUnknown);
            mLogger.start();
            mHD.addHarleyDataDashboardListener(mLogger);
            mHD.addHarleyDataDiagnosticsListener(mLogger);
            mHD.addHarleyDataRawListener(mLogger);
        }
        break;
    case MSG_DISCONNECT:
        mHandler.obtainMessage(HarleyDroid.STATUS_NONE, -1, -1).sendToTarget();
        mWantedState = STATE_DISCONNECT;
        break;
    case MSG_DISCONNECTED:
        mHandler.obtainMessage(msg.arg1, -1, -1).sendToTarget();
        mCurrentState = STATE_DISCONNECT;
        mHD.savePersistentData();
        if (mAutoReconnect) {
            final int lastState = mWantedState;
            HarleyDroidService.this.notify(R.string.notification_autorecon);
            mHandler.obtainMessage(HarleyDroid.STATUS_AUTORECON, -1, -1).sendToTarget();

            doDisconnect();
            mReconThread = new Thread() {
                public void run() {
                    setName("HarleyDroidService: reconThread");
                    try {
                        Thread.sleep(mReconnectDelay * 1000);
                        //mServiceHandler.removeCallbacksAndMessages(null);
                        mServiceHandler.obtainMessage(MSG_NONE, lastState, -1).sendToTarget();
                        // try again to go to mWantedState
                    } catch (InterruptedException e) {
                    }
                }
            };
            mWantedState = STATE_WAIT_RECONNECT;
            mReconThread.start();
        } else {
            doDestroy();
            return;
        }
        break;
    case MSG_START_POLL:
        mWantedState = STATE_POLL;
        break;
    case MSG_STARTED_POLL:
        HarleyDroidService.this.notify(R.string.notification_polling);
        mCurrentState = STATE_POLL;
        break;
    case MSG_START_SEND:
        mWantedState = STATE_SEND;
        mSendType = msg.getData().getStringArray("type");
        mSendTA = msg.getData().getStringArray("ta");
        mSendSA = msg.getData().getStringArray("sa");
        mSendCommand = msg.getData().getStringArray("command");
        mSendExpect = msg.getData().getStringArray("expect");
        mSendTimeout = msg.getData().getIntArray("timeout");
        mSendDelay = msg.getData().getInt("delay");
        break;
    case MSG_STARTED_SEND:
        HarleyDroidService.this.notify(R.string.notification_diagnostics);
        mCurrentState = STATE_SEND;
        break;
    case MSG_SET_SEND:
        mInterface.setSendData(msg.getData().getStringArray("type"), msg.getData().getStringArray("ta"),
                msg.getData().getStringArray("sa"), msg.getData().getStringArray("command"),
                msg.getData().getStringArray("expect"), msg.getData().getIntArray("timeout"),
                msg.getData().getInt("delay"));
    }
    stateMachine();
}

From source file:com.nbplus.vbroadlauncher.RadioActivity.java

public void handleMessage(Message msg) {
    if (msg == null) {
        return;//w ww . j  a v  a2 s .  c o  m
    }
    switch (msg.what) {
    // ??  .
    case Constants.HANDLER_MESSAGE_GET_RADIO_CHANNEL_TASK:
        RadioChannelInfo data = (RadioChannelInfo) msg.obj;

        dismissProgressDialog();
        if (data != null && Constants.RESULT_OK.equals(data.getResultCode())) {
            mRadioChannelItems = data.getRadioChannelList();
            if (mRadioChannelItems == null) {
                mRadioChannelItems = new ArrayList<>();
            }
        } else {
            if (mRadioChannelItems == null) {
                mRadioChannelItems = new ArrayList<>();
            }

            if (data == null) {
                data = new RadioChannelInfo();
                data.setResultMessage(getString(R.string.server_connection_error));
            }

            Intent i = new Intent(this, MusicService.class);
            i.setAction(MusicService.ACTION_STOP);
            i.putExtra(MusicService.EXTRA_MUSIC_FORCE_STOP, true);
            startService(i);

            AlertDialog.Builder alert = new AlertDialog.Builder(this);
            alert.setPositiveButton(R.string.alert_ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    //finish();
                }
            });
            alert.setMessage(data.getResultMessage());
            try {
                alert.show();
            } catch (Exception e) {

            }
        }
        mIsExecuteGetRadioChannelTask = false;
        getRadioChannelTask = null;

        setupRadioChannelPager();
        break;
    // ?? ?  . ? ??  
    case Constants.HANDLER_MESSAGE_PLAY_RADIO_CHANNEL_TIMEOUT:
        Intent i = new Intent(this, MusicService.class);
        i.setAction(MusicService.ACTION_STOP);
        i.putExtra(MusicService.EXTRA_MUSIC_FORCE_STOP, true);
        startService(i);
        break;

    //   
    case HANDLER_MESSAGE_STREAM_MUSIC_VOLUME_CHANGE:
        int currentVolume = msg.arg1;
        if (currentVolume <= 0) {
            mSoundToggle.setBackgroundResource(R.drawable.ic_button_radio_sound_off);
        } else {
            mSoundToggle.setBackgroundResource(R.drawable.ic_button_radio_sound_on);
        }
        mSeekbar.setProgress(currentVolume);
        break;

    // ?
    case HANDLER_MESSAGE_MUSIC_SERVICE_ACTION:
        Bundle b = msg.getData();
        if (b == null) {
            Log.i(TAG, "HANDLER_MESSAGE_MUSIC_SERVICE_ACTION bundle is not found!!");
            return;
        }
        String action = b.getString(MusicService.EXTRA_ACTION);
        MusicService.State state = (MusicService.State) b.getSerializable(MusicService.EXTRA_PLAYING_STATUS);
        MusicRetriever.Item item = b.getParcelable(MusicService.EXTRA_MUSIC_ITEM);

        if (state == MusicService.State.Playing) {
            mPlayToggle.setBackgroundResource(R.drawable.ic_btn_radio_pause_selector);
            mRadioTitle.setText(item.getTitle());
        } else if (state == MusicService.State.Paused) {
            mPlayToggle.setBackgroundResource(R.drawable.ic_btn_radio_play_selector);
            mRadioTitle.setText(item.getTitle());
        } else if (state == MusicService.State.Stopped) {
            mPlayToggle.setBackgroundResource(R.drawable.ic_btn_radio_play_selector);
            b.remove(MusicService.EXTRA_MUSIC_ITEM);
            mRadioTitle.setText(R.string.activity_radio_default_title);
        } else {
            mRadioTitle.setText(R.string.activity_radio_default_title);
        }
        mCurrentPlayingStatus = b;
        for (int idx = 0; idx < mActivityInteractionListener.size(); idx++) {
            mActivityInteractionListener.get(idx).onPlayItemChanged(b);
        }

        if (!mIsExecuteGetRadioChannelTask) {
            mHandler.sendEmptyMessageDelayed(HANDLER_MESSAGE_HIDE_PROGRESS_DIALOG, 1500);
        }
        break;

    //  
    case HANDLER_MESSAGE_HIDE_PROGRESS_DIALOG:
        dismissProgressDialog();
        break;
    }
}

From source file:ti.modules.titanium.geolocation.GeolocationModule.java

@Override
public boolean handleMessage(final Message msg) {
    if (msg.what == MSG_LOOKUP) {
        AsyncTask<Object, Void, Integer> task = new AsyncTask<Object, Void, Integer>() {
            @Override// www . j a v a 2s.co m
            protected Integer doInBackground(Object... args) {
                try {
                    String url = (String) args[0];
                    String direction = (String) args[1];
                    KrollCallback callback = (KrollCallback) args[2];

                    if (DBG) {
                        Log.d(LCAT, "GEO URL: " + url);
                    }
                    HttpGet httpGet = new HttpGet(url);

                    HttpParams httpParams = new BasicHttpParams();
                    HttpConnectionParams.setConnectionTimeout(httpParams, 5000); // TODO use property
                    // HttpConnectionParams.setSoTimeout(httpParams, 15000);
                    // //TODO use property
                    HttpClient client = new DefaultHttpClient(httpParams);

                    ResponseHandler<String> responseHandler = new BasicResponseHandler();
                    client.getParams().setBooleanParameter("http.protocol.expect-continue", false);

                    String response = client.execute(httpGet, responseHandler);

                    if (DBG) {
                        Log.i(LCAT, "Received Geo: " + response);
                    }
                    KrollDict event = null;
                    if (response != null) {
                        try {
                            JSONObject r = new JSONObject(response);
                            if (r.getBoolean("success")) {
                                if (direction.equals("r")) {
                                    event = buildReverseResponse(r);
                                } else {
                                    event = buildForwardResponse(r);
                                }
                            } else {
                                event = new KrollDict();
                                KrollDict err = new KrollDict();
                                String errorCode = r.getString("errorcode");
                                err.put("message", "Unable to resolve message: Code (" + errorCode + ")");
                                err.put("code", errorCode);
                                event.put("error", err);
                            }
                        } catch (JSONException e) {
                            Log.e(LCAT, "Error converting geo response to JSONObject: " + e.getMessage(), e);
                        }
                    }

                    if (event != null) {
                        event.put("source", this);
                        callback.callAsync(event);
                    }
                } catch (Throwable t) {
                    Log.e(LCAT, "Error retrieving geocode information: " + t.getMessage(), t);
                }

                return -1;
            }

        };

        task.execute(msg.getData().getString("url"), msg.getData().getString("direction"), msg.obj);

        return true;
    }

    return super.handleMessage(msg);
}

From source file:it.alfonsovinti.cordova.plugins.bixolonprint.BixolonPrint.java

private void onMessageRead(Message msg) {
    Log.d(TAG, "BixolonPrint.onMessageRead_START: " + msg.arg1);

    switch (msg.arg1) {
    case BixolonPrinter.PROCESS_GET_STATUS:
        if (msg.arg2 == BixolonPrinter.STATUS_NORMAL) {
            try {
                //this.mConnectedDeviceStatus.put("status", "NO ERROR");
                this.mConnectedDeviceStatus.put("cover", "OPENED");
                this.mConnectedDeviceStatus.put("paper", "FILL");
            } catch (JSONException e) {
            }//from w  w  w .  j  a  va 2  s .  com
        } else {
            if ((msg.arg2 & BixolonPrinter.STATUS_COVER_OPEN) == BixolonPrinter.STATUS_COVER_OPEN) {
                try {
                    this.mConnectedDeviceStatus.put("cover", "OPENED");
                } catch (JSONException e) {
                }
            } else {
                try {
                    this.mConnectedDeviceStatus.put("cover", "CLOSED");
                } catch (JSONException e) {
                }
            }

            if ((msg.arg2
                    & BixolonPrinter.STATUS_PAPER_NOT_PRESENT) == BixolonPrinter.STATUS_PAPER_NOT_PRESENT) {
                try {
                    this.mConnectedDeviceStatus.put("paper", "EMPTY");
                } catch (JSONException e) {
                }
            } else {
                try {
                    this.mConnectedDeviceStatus.put("paper", "FILL");
                } catch (JSONException e) {
                }
            }
        }

        this.statusStep = STATUS_STEP_GET_BATTERY_STATUS;
        break;

    case BixolonPrinter.PROCESS_GET_BATTERY_STATUS:
        switch (msg.arg2) {
        case BixolonPrinter.STATUS_BATTERY_FULL:
            try {
                this.mConnectedDeviceStatus.put("battery", "FULL");
            } catch (JSONException e) {
            }
            break;
        case BixolonPrinter.STATUS_BATTERY_HIGH:
            try {
                this.mConnectedDeviceStatus.put("battery", "HIGH");
            } catch (JSONException e) {
            }
            break;
        case BixolonPrinter.STATUS_BATTERY_MIDDLE:
            try {
                this.mConnectedDeviceStatus.put("battery", "MIDDLE");
            } catch (JSONException e) {
            }
            break;
        case BixolonPrinter.STATUS_BATTERY_LOW:
            try {
                this.mConnectedDeviceStatus.put("battery", "LOW");
            } catch (JSONException e) {
            }
            break;
        }

        this.statusStep = STATUS_STEP_GET_PRINTER_ID_FIRMWARE_VERSION;
        break;

    case BixolonPrinter.PROCESS_GET_PRINTER_ID:
        Bundle data = msg.getData();
        switch (this.statusStep) {
        case STATUS_STEP_GET_PRINTER_ID_FIRMWARE_VERSION:
            try {
                this.mConnectedDeviceStatus.put("firmwareVersion",
                        data.getString(BixolonPrinter.KEY_STRING_PRINTER_ID));
            } catch (JSONException e) {
            }

            this.statusStep = STATUS_STEP_GET_PRINTER_ID_MANUFACTURER;
            break;

        case STATUS_STEP_GET_PRINTER_ID_MANUFACTURER:
            try {
                this.mConnectedDeviceStatus.put("manufacturer",
                        data.getString(BixolonPrinter.KEY_STRING_PRINTER_ID));
            } catch (JSONException e) {
            }

            this.statusStep = STATUS_STEP_GET_PRINTER_ID_PRINTER_MODEL;
            break;

        case STATUS_STEP_GET_PRINTER_ID_PRINTER_MODEL:
            try {
                this.mConnectedDeviceStatus.put("printerModel",
                        data.getString(BixolonPrinter.KEY_STRING_PRINTER_ID));
            } catch (JSONException e) {
            }

            this.statusStep = STATUS_STEP_GET_PRINTER_ID_CODE_PAGE;
            break;

        case STATUS_STEP_GET_PRINTER_ID_CODE_PAGE:
            try {
                this.mConnectedDeviceStatus.put("codePage",
                        data.getString(BixolonPrinter.KEY_STRING_PRINTER_ID));
            } catch (JSONException e) {
            }

            this.statusStep = STATUS_STEP_COMPLETE;
            break;
        case STATUS_STEP_GET_PRINTER_ID_MODEL_ID:
            try {
                this.mConnectedDeviceStatus.put("modelId",
                        data.getString(BixolonPrinter.KEY_STRING_PRINTER_ID));
            } catch (JSONException e) {
            }

            this.statusStep = STATUS_STEP_GET_PRINTER_ID_PRODUCT_SERIAL;
            break;
        case STATUS_STEP_GET_PRINTER_ID_PRODUCT_SERIAL:
            try {
                this.mConnectedDeviceStatus.put("productSerial",
                        data.getString(BixolonPrinter.KEY_STRING_PRINTER_ID));
            } catch (JSONException e) {
            }

            this.statusStep = STATUS_STEP_GET_PRINTER_ID_TYPE_ID;
            break;
        case STATUS_STEP_GET_PRINTER_ID_TYPE_ID:
            try {
                this.mConnectedDeviceStatus.put("typeId", data.getString(BixolonPrinter.KEY_STRING_PRINTER_ID));
            } catch (JSONException e) {
            }

            this.statusStep = STATUS_STEP_COMPLETE;
            break;
        }
        break;
    }

    Log.d(TAG, "BixolonPrint.onMessageRead_END");
    this.getStatus();
}