Example usage for android.os Bundle setClassLoader

List of usage examples for android.os Bundle setClassLoader

Introduction

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

Prototype

@Override
public void setClassLoader(ClassLoader loader) 

Source Link

Document

Changes the ClassLoader this Bundle uses when instantiating objects.

Usage

From source file:com.dwdesign.tweetings.fragment.StatusFragment.java

@Override
public void onActivityCreated(final Bundle savedInstanceState) {
    mPreferences = getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
    final TweetingsApplication application = getApplication();
    mService = application.getServiceInterface();
    mLazyImageLoader = application.getImageLoaderWrapper();
    mImagesPreviewFragment = (ImagesPreviewFragment) Fragment.instantiate(getActivity(),
            ImagesPreviewFragment.class.getName());
    super.onActivityCreated(savedInstanceState);
    setRetainInstance(true);//from  w  w  w. ja  v  a 2  s .  c o m
    mLoadMoreAutomatically = mPreferences.getBoolean(PREFERENCE_KEY_LOAD_MORE_AUTOMATICALLY, true);
    final Bundle bundle = getArguments();
    if (bundle != null) {
        mAccountId = bundle.getLong(INTENT_KEY_ACCOUNT_ID);
        mStatusId = bundle.getLong(INTENT_KEY_STATUS_ID);
        bundle.setClassLoader(ParcelableStatus.class.getClassLoader());
        mStatus = bundle.getParcelable(INTENT_KEY_STATUS);
        mImagesPreviewFragment.setStatus(mStatus);
    }
    mInReplyToView.setOnClickListener(this);
    mFollowButton.setOnClickListener(this);
    mProfileView.setOnClickListener(this);
    mLocationView.setOnClickListener(this);
    mRetweetedStatusView.setOnClickListener(this);
    mMenuBar.setOnMenuItemClickListener(this);
    final FragmentManager fm = getFragmentManager();
    final FragmentTransaction ft = fm.beginTransaction();
    ft.replace(R.id.images_preview, mImagesPreviewFragment);
    ft.commit();
    //if (mStatus != null) {
    //displayStatus(mStatus);
    //} else {
    //getStatus(false);
    //}

}

From source file:android.app.FragmentState.java

/**
 * Create a new instance of a Fragment with the given class name.  This is
 * the same as calling its empty constructor.
 *
 * @param context The calling context being used to instantiate the fragment.
 * This is currently just used to get its ClassLoader.
 * @param fname The class name of the fragment to instantiate.
 * @param args Bundle of arguments to supply to the fragment, which it
 * can retrieve with {@link #getArguments()}.  May be null.
 * @return Returns a new fragment instance.
 * @throws InstantiationException If there is a failure in instantiating
 * the given fragment class.  This is a runtime exception; it is not
 * normally expected to happen./*from www.  j a v a 2  s. co m*/
 */
public static Fragment instantiate(Context context, String fname, Bundle args) {
    try {
        Class<?> clazz = sClassMap.get(fname);
        if (clazz == null) {
            // Class not found in the cache, see if it's real, and try to add it
            clazz = context.getClassLoader().loadClass(fname);
            sClassMap.put(fname, clazz);
        }
        Fragment f = (Fragment) clazz.newInstance();
        if (args != null) {
            args.setClassLoader(f.getClass().getClassLoader());
            f.mArguments = args;
        }
        return f;
    } catch (ClassNotFoundException e) {
        throw new InstantiationException("Unable to instantiate fragment " + fname
                + ": make sure class name exists, is public, and has an" + " empty constructor that is public",
                e);
    } catch (java.lang.InstantiationException e) {
        throw new InstantiationException("Unable to instantiate fragment " + fname
                + ": make sure class name exists, is public, and has an" + " empty constructor that is public",
                e);
    } catch (IllegalAccessException e) {
        throw new InstantiationException("Unable to instantiate fragment " + fname
                + ": make sure class name exists, is public, and has an" + " empty constructor that is public",
                e);
    }
}

From source file:notrace.daytongue.views.HorizontalListView.java

@Override
public Parcelable onSaveInstanceState() {
    Bundle bundle = new Bundle();

    // Add the parent state to the bundle
    bundle.putParcelable(BUNDLE_ID_PARENT_STATE, super.onSaveInstanceState());
    bundle.setClassLoader(getClass().getClassLoader());
    // Add our state to the bundle
    bundle.putInt(BUNDLE_ID_CURRENT_X, mCurrentX);

    return bundle;
}

From source file:android.app.FragmentState.java

/**
 * Create a new instance of a Fragment with the given class name.  This is
 * the same as calling its empty constructor.
 *
 * @param context The calling context being used to instantiate the fragment.
 * This is currently just used to get its ClassLoader.
 * @param fname The class name of the fragment to instantiate.
 * @param args Bundle of arguments to supply to the fragment, which it
 * can retrieve with {@link #getArguments()}.  May be null.
 * @return Returns a new fragment instance.
 * @throws InstantiationException If there is a failure in instantiating
 * the given fragment class.  This is a runtime exception; it is not
 * normally expected to happen./*from  w w  w  .ja va  2s  . c o  m*/
 */
public static Fragment instantiate(Context context, String fname, @Nullable Bundle args) {
    try {
        Class<?> clazz = sClassMap.get(fname);
        if (clazz == null) {
            // Class not found in the cache, see if it's real, and try to add it
            clazz = context.getClassLoader().loadClass(fname);
            if (!Fragment.class.isAssignableFrom(clazz)) {
                throw new InstantiationException(
                        "Trying to instantiate a class " + fname + " that is not a Fragment",
                        new ClassCastException());
            }
            sClassMap.put(fname, clazz);
        }
        Fragment f = (Fragment) clazz.newInstance();
        if (args != null) {
            args.setClassLoader(f.getClass().getClassLoader());
            f.mArguments = args;
        }
        return f;
    } catch (ClassNotFoundException e) {
        throw new InstantiationException("Unable to instantiate fragment " + fname
                + ": make sure class name exists, is public, and has an" + " empty constructor that is public",
                e);
    } catch (java.lang.InstantiationException e) {
        throw new InstantiationException("Unable to instantiate fragment " + fname
                + ": make sure class name exists, is public, and has an" + " empty constructor that is public",
                e);
    } catch (IllegalAccessException e) {
        throw new InstantiationException("Unable to instantiate fragment " + fname
                + ": make sure class name exists, is public, and has an" + " empty constructor that is public",
                e);
    }
}

From source file:org.lunci.dumbthing.fragment.MainDisplayFragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mAdapter = new DumbItemSimpleAdapter(getActivity(), R.layout.dumb_display_item_simple);
    mDetector = new GestureDetectorCompat(getActivity(), new GestureDetector.OnGestureListener() {
        private static final float ThresholdDistance = 50;
        private static final float ThresholdVelocity = 1000;

        @Override/*from  ww  w  .ja va  2s.c o  m*/
        public boolean onDown(MotionEvent e) {
            return false;
        }

        @Override
        public void onShowPress(MotionEvent e) {

        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            return false;
        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            return false;
        }

        @Override
        public void onLongPress(MotionEvent e) {

        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            if (e1 == null || e2 == null)
                return false;
            final float distanceX = e1.getRawX() - e2.getRawX();
            if (distanceX < -ThresholdDistance && velocityX > ThresholdVelocity) {
                return mViewHolder.showPrevious();
            } else if (distanceX > ThresholdDistance && velocityX < -ThresholdVelocity) {
                return mViewHolder.showNext();
            }
            return true;
        }
    });
    if (savedInstanceState != null) {
        savedInstanceState.setClassLoader(DumbModel.class.getClassLoader());
        final ArrayList<Parcelable> list = savedInstanceState.getParcelableArrayList(EXTRA_ITEMS);
        for (Parcelable p : list) {
            mAdapter.add((DumbModel) p);
        }
    }
}

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

private void handleDeviceListNotification(Bundle b) {
    mEmergencyDeviceList.clear();/*from  w  ww .jav a 2  s. com*/
    HashMap<String, IoTDevice> scannedDevices = new HashMap<>();
    if (b == null) {
        Log.w(TAG, "bundle data is null");
        //return; // ?  ?     .
    } else {
        b.setClassLoader(IoTDevice.class.getClassLoader());
        scannedDevices = (HashMap<String, IoTDevice>) b.getSerializable(IoTServiceCommand.KEY_DATA);
        if (scannedDevices == null) {
            scannedDevices = new HashMap<>();
        }
    }

    if (scannedDevices == null || scannedDevices.size() == 0) {
        Log.w(TAG, "empty device list");
        //return; // ?  ?     .
    }

    boolean changed = false;
    Iterator<String> iter = scannedDevices.keySet().iterator();
    Log.d(TAG, "IoTServiceCommand.GET_DEVICE_LIST added size = " + scannedDevices.size());
    while (iter.hasNext()) {
        String key = iter.next();
        IoTDevice bondedDevice = mBondedWithServerList.get(key);

        IoTDevice scannedDevice = scannedDevices.get(key);
        Log.d(TAG, "check " + key + " is exist or new...");
        // ? ?? ? ?? ? ?  ? ?.
        if (bondedDevice == null) {
            continue;
        }

        //            if (bondedDevice != null) {           // already exist
        if (scannedDevice.getUuids() == null || scannedDevice.getUuids().size() == 0) {
            Log.e(TAG, ">>> xx device name " + bondedDevice.getDeviceName() + " has no uuid advertisement");
            continue;
        }
        ArrayList<String> deviceUuids = bondedDevice.getUuids();
        if (deviceUuids == null || deviceUuids.size() == 0) {
            if (bondedDevice.getDeviceTypeId() == IoTDevice.DEVICE_TYPE_ID_BT) {
                bondedDevice.setAdRecordHashMap(scannedDevice.getAdRecordHashMap());
                bondedDevice.setUuids(scannedDevice.getUuids());
                bondedDevice.setUuidLen(scannedDevice.getUuidLen());
            }
            bondedDevice.setIsKnownDevice(isKnownScenarioDevice(bondedDevice.getDeviceTypeId(),
                    bondedDevice.getUuids(), bondedDevice.getUuidLen()));
            mBondedWithServerList.put(key, bondedDevice);
            changed = true;
        } else {
            if (!scannedDevice.getUuids().equals(deviceUuids)) {
                if (bondedDevice.getDeviceTypeId() == IoTDevice.DEVICE_TYPE_ID_BT) {
                    bondedDevice.setAdRecordHashMap(scannedDevice.getAdRecordHashMap());
                    bondedDevice.setUuids(scannedDevice.getUuids());
                    bondedDevice.setUuidLen(scannedDevice.getUuidLen());
                }
                bondedDevice.setIsKnownDevice(isKnownScenarioDevice(bondedDevice.getDeviceTypeId(),
                        bondedDevice.getUuids(), bondedDevice.getUuidLen()));
                mBondedWithServerList.put(key, bondedDevice);
                changed = true;
            }
        }
        // do nothing...
        // ? ?? ? ?? ? ?  ? ?.
        //            } else {
        //                ArrayList<String> uuids = DataParser.getUuids(scannedDevice.getAdRecordHashMap());
        //                if (uuids == null || uuids.size() == 0) {
        //                    Log.e(TAG, ">>> device name " + scannedDevice.getDeviceName() + " has no uuid advertisement");
        //                    continue;
        //                }
        //                scannedDevice.setUuids(uuids);
        //                scannedDevice.setUuidLen(DataParser.getUuidLength(scannedDevice.getAdRecordHashMap()));
        //                scannedDevice.setIsKnownDevice(isKnownScenarioDevice(scannedDevice.getDeviceTypeId(), scannedDevice.getUuids(), scannedDevice.getUuidLen()));
        //
        //                bondedDevice = scannedDevice;
        //                mBondedWithServerList.put(bondedDevice.getDeviceId(), bondedDevice);
        //                changed = true;
        //            }

        // ??  ?? .
        if (bondedDevice.isBondedWithServer() && isEmergencyCallDevice(bondedDevice.getDeviceTypeId(),
                bondedDevice.getUuids(), bondedDevice.getUuidLen())) {
            Log.d(TAG, "Emergency call device broadcast received : " + bondedDevice.getDeviceId());

            mEmergencyDeviceList.add(bondedDevice);
        }

        //   ? ?  ?? Notification  ?.
        if (bondedDevice.isBondedWithServer() && isKeepAliveDevice(bondedDevice)) {
            Log.d(TAG, "Smart sensor device found device ID = " + bondedDevice.getDeviceId());

            if (!mKeepAliveDeviceList.containsKey(bondedDevice.getDeviceId())) {
                // ? ? ?  3 .
                if (mKeepAliveDeviceList.size() >= MAX_KEEP_ALIVE_CONNECTED_DEVICE_SIZE) {
                    Log.d(TAG, "MAX_KEEP_ALIVE_CONNECTED_DEVICE_SIZE reached....");
                    // do nothing.
                } else {
                    mKeepAliveDeviceList.put(bondedDevice.getDeviceId(), bondedDevice);
                    Bundle extras = new Bundle();
                    IoTHandleData data = new IoTHandleData();
                    data.setDeviceId(bondedDevice.getDeviceId());
                    data.setDeviceTypeId(bondedDevice.getDeviceTypeId());
                    data.setIsKeepAliveDevice(true);

                    extras.putParcelable(IoTServiceCommand.KEY_DATA, data);
                    sendMessageToService(IoTServiceCommand.DEVICE_CONNECT, extras);
                }
            } else {
                Log.d(TAG, "This device already connected. and collecting data... ");
            }
        }
    }

    if (changed) {
        // save to preference.
        String json = mGson.toJson(mBondedWithServerList);
        if (json != null) {
            IoTServicePreference.setIoTDevicesList(mCtx, json);
        }
    }
    Log.d(TAG, "Current device size = " + mBondedWithServerList.size());
    if (mEmergencyDeviceList.size() > 0) {
        // ??  ?  
        long currTimeMs = System.currentTimeMillis();
        //if (currTimeMs - mLastEmergencyDeviceFoundTimeMs > 1 * 60 * 1000) {
        mIsEmergencyDataCollecting = true;

        //   ?  ?? ? .
        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);
        //            } else {
        //                Log.d(TAG, ">>> Already emergency device retrive.. before = " + (currTimeMs - mLastEmergencyDeviceFoundTimeMs));
        //                mIsEmergencyDataCollecting = false;
        //                mEmergencyDeviceList.clear();
        //            }
    }

    if (mForceRescanCallback == null) {
        return;
    }

    final IoTServiceStatusNotification responseCallback = mForceRescanCallback.get();
    if (responseCallback != null) {
        Bundle extras = new Bundle();
        ArrayList<IoTDevice> devicesList = null;
        // 2015.12.09
        // ?? ? BT  .
        // ? ?? ? ???  ?  .

        //if (mBondedWithServerList != null && mBondedWithServerList.size() > 0) {
        //    devicesList = new ArrayList<>(mBondedWithServerList.values());
        //} else {
        //    devicesList = new ArrayList<>();
        //}
        if (mKeepAliveDeviceList != null && mKeepAliveDeviceList.size() > 0) {
            devicesList = new ArrayList<>(mKeepAliveDeviceList.values());
        } else {
            devicesList = new ArrayList<>();
        }

        // 
        ArrayList<String> deviceIdList = new ArrayList<>();
        for (int i = 0; i < devicesList.size(); i++) {
            deviceIdList.add(devicesList.get(i).getDeviceId());
        }

        ArrayList<IoTDevice> scannedDevicesList = new ArrayList<>(scannedDevices.values());
        for (int i = 0; i < scannedDevicesList.size(); i++) {
            if (deviceIdList.contains(scannedDevicesList.get(i).getDeviceId())) {
                Log.d(TAG, "mForceRescanCallback device id " + scannedDevicesList.get(i).getDeviceId()
                        + " is already added.");
                continue;
            }
            devicesList.add(scannedDevicesList.get(i));
        }
        extras.putParcelableArrayList(IoTServiceCommand.KEY_DATA, devicesList);
        responseCallback.onResult(IoTServiceCommand.GET_DEVICE_LIST, mServiceStatus, mErrorCodes, extras);
    }
    mForceRescanCallback = null;
    // TODO : log
    if (BuildConfig.DEBUG) {
        iter = mBondedWithServerList.keySet().iterator();
        while (iter.hasNext()) {
            String key = iter.next();
            IoTDevice device = mBondedWithServerList.get(key);

            printScanDeviceInformation(device);
        }
    }

}

From source file:im.neon.activity.VectorRoomActivity.java

@SuppressLint("NewApi")
/**// w w  w.ja va2 s.c om
 * Send the medias defined in the intent.
 * They are listed, checked and sent when it is possible.
 */
private void sendMediasIntent(final Intent intent) {
    // sanity check
    if ((null == intent) && (null == mLatestTakePictureCameraUri)) {
        return;
    }

    ArrayList<SharedDataItem> sharedDataItems = new ArrayList<>();

    if (null != intent) {
        sharedDataItems = new ArrayList<>(SharedDataItem.listSharedDataItems(intent));
    } else if (null != mLatestTakePictureCameraUri) {
        sharedDataItems.add(new SharedDataItem(Uri.parse(mLatestTakePictureCameraUri)));
        mLatestTakePictureCameraUri = null;
    }

    // check the extras
    if (0 == sharedDataItems.size()) {
        Bundle bundle = intent.getExtras();

        // sanity checks
        if (null != bundle) {
            bundle.setClassLoader(SharedDataItem.class.getClassLoader());

            if (bundle.containsKey(Intent.EXTRA_STREAM)) {
                try {
                    Object streamUri = bundle.get(Intent.EXTRA_STREAM);

                    if (streamUri instanceof Uri) {
                        sharedDataItems.add(new SharedDataItem((Uri) streamUri));
                    } else if (streamUri instanceof List) {
                        List<Object> streams = (List<Object>) streamUri;

                        for (Object object : streams) {
                            if (object instanceof Uri) {
                                sharedDataItems.add(new SharedDataItem((Uri) object));
                            } else if (object instanceof SharedDataItem) {
                                sharedDataItems.add((SharedDataItem) object);
                            }
                        }
                    }
                } catch (Exception e) {
                    Log.e(LOG_TAG, "fail to extract the extra stream");
                }
            } else if (bundle.containsKey(Intent.EXTRA_TEXT)) {
                mEditText.setText(mEditText.getText() + bundle.getString(Intent.EXTRA_TEXT));

                mEditText.post(new Runnable() {
                    @Override
                    public void run() {
                        mEditText.setSelection(mEditText.getText().length());
                    }
                });
            }
        }
    }

    if (0 != sharedDataItems.size()) {
        mVectorRoomMediasSender.sendMedias(sharedDataItems);
    }
}

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

private void handleResponse(Bundle b) {
    int cmd = b.getInt(IoTServiceCommand.KEY_CMD, -1);
    switch (cmd) {
    case IoTServiceCommand.DEVICE_DISCONNECT_ALL: {
        Log.d(TAG, "DEVICE_DISCONNECT_ALL received.. Start retrieve... ");

        if (mIsEmergencyDataCollecting) {
            sendConnectToEmergencyDevice();
        } else {/*from   ww  w .j  a  v  a 2  s  . c o m*/
            mCurrentRetrieveIndex = 0;

            if (mServiceStatus == IoTServiceStatus.RUNNING) {
                sendConnectToDeviceMessage(mCurrentRetrieveIndex);
            } else {
                Intent intent = new Intent(IoTConstants.ACTION_IOT_DATA_SYNC_COMPLETED);
                LocalBroadcastManager.getInstance(mCtx).sendBroadcast(intent);
            }
        }
        break;
    }
    case IoTServiceCommand.REGISTER_SERVICE: {
        b.setClassLoader(IoTResultCodes.class.getClassLoader());
        IoTResultCodes resultCode = (IoTResultCodes) b.getSerializable(IoTServiceCommand.KEY_RESULT);
        if (resultCode != null && resultCode.equals(IoTResultCodes.SUCCESS)) {
            // success
            Log.d(TAG, ">> IoT Register service success...");
            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);
            }
        } else {
            Log.w(TAG, ">> IoT Register service failed code = " + resultCode);
            mErrorCodes = resultCode;
        }
        break;
    }
    case IoTServiceCommand.UNREGISTER_SERVICE: {
        b.setClassLoader(IoTResultCodes.class.getClassLoader());
        IoTResultCodes resultCode = (IoTResultCodes) b.getSerializable(IoTServiceCommand.KEY_RESULT);
        if (resultCode != null && resultCode.equals(IoTResultCodes.SUCCESS)) {
            // success
            Log.d(TAG, ">> IoT Register service success...");
        } else {
            Log.w(TAG, ">> IoT Register service failed code = " + resultCode);
        }
        break;
    }

    case IoTServiceCommand.DEVICE_CONNECT: {
        b.setClassLoader(IoTResultCodes.class.getClassLoader());
        IoTResultCodes resultCode = (IoTResultCodes) b.getSerializable(IoTServiceCommand.KEY_RESULT);
        if (resultCode != null && resultCode.equals(IoTResultCodes.SUCCESS)) {
            // success
            Log.d(TAG, ">> IoT DEVICE_CONNECT success...");
        } else {
            Log.w(TAG, ">> IoT DEVICE_CONNECT failed code = " + resultCode);
            String deviceId = b.getString(IoTServiceCommand.KEY_DEVICE_UUID);
            if (deviceId != null && mKeepAliveDeviceList.containsKey(deviceId)) {
                Log.d(TAG, "Keep alive device connection failed.");
                mKeepAliveDeviceList.remove(deviceId);
                return;
            }

            if (IoTResultCodes.DEVICE_CONNECTION_NOT_RESPOND.equals(resultCode)
                    && mConnectionRetryCount < MAX_CONNECTION_RETRY) {
                if (mServiceStatus != IoTServiceStatus.RUNNING) {
                    mCurrentRetrieveIndex = -1;
                    mCurrentRetrieveDevice = null;

                    if (mIsEmergencyDataCollecting) {
                        mEmergencyDeviceList.clear();
                        mIsEmergencyDataCollecting = false;

                        if (mIsWaitingForceDataSync) {
                            mIsWaitingForceDataSync = false;
                            Intent intent = new Intent(IoTConstants.ACTION_IOT_DATA_SYNC_COMPLETED);
                            LocalBroadcastManager.getInstance(mCtx).sendBroadcast(intent);
                        }
                    } else {
                        Intent intent = new Intent(IoTConstants.ACTION_IOT_DATA_SYNC_COMPLETED);
                        LocalBroadcastManager.getInstance(mCtx).sendBroadcast(intent);
                    }
                    break;
                }
                Log.d(TAG, "mConnectionRetryCount = " + mConnectionRetryCount);
                mConnectionRetryCount++;
                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_CONNECT, extras);
                break;
            }
            if (mIsEmergencyDataCollecting) {
                sendConnectToEmergencyDevice();
            } else {
                if (mCurrentRetrieveIndex + 1 < mBondedWithServerList.size()) {
                    mCurrentRetrieveIndex++;
                    sendConnectToDeviceMessage(mCurrentRetrieveIndex);
                } else {
                    Log.d(TAG, "Retrieving all devices.. completed");
                    mCurrentRetrieveIndex = -1;
                    mCurrentRetrieveDevice = null;

                    mHandler.removeMessages(HANDLER_RETRIEVE_IOT_DEVICES);
                    mHandler.sendEmptyMessageDelayed(HANDLER_RETRIEVE_IOT_DEVICES,
                            RETRIEVE_IOT_DEVICE_DATA_PERIOD);
                    sendCollectedDataToServer();
                }
            }
        }
        break;
    }

    case IoTServiceCommand.DEVICE_DISCONNECT: {
        b.setClassLoader(IoTResultCodes.class.getClassLoader());
        IoTResultCodes resultCode = (IoTResultCodes) b.getSerializable(IoTServiceCommand.KEY_RESULT);
        if (resultCode != null && resultCode.equals(IoTResultCodes.SUCCESS)) {
            // success
            Log.d(TAG, ">> IoT DEVICE_DISCONNECT success...");
        } else {
            Log.w(TAG, ">> IoT DEVICE_DISCONNECT failed code = " + resultCode);
            if (mIsEmergencyDataCollecting) {
                sendConnectToEmergencyDevice();
            } else {
                if (mCurrentRetrieveIndex + 1 < mBondedWithServerList.size()) {
                    mCurrentRetrieveIndex++;
                    sendConnectToDeviceMessage(mCurrentRetrieveIndex);
                } else {
                    mCurrentRetrieveIndex = -1;
                    mCurrentRetrieveDevice = null;

                    mHandler.removeMessages(HANDLER_RETRIEVE_IOT_DEVICES);
                    mHandler.sendEmptyMessageDelayed(HANDLER_RETRIEVE_IOT_DEVICES,
                            RETRIEVE_IOT_DEVICE_DATA_PERIOD);
                    sendCollectedDataToServer();
                }
            }
        }
        break;
    }

    case IoTServiceCommand.DEVICE_READ_DATA:
    case IoTServiceCommand.DEVICE_WRITE_DATA:
    case IoTServiceCommand.DEVICE_SET_NOTIFICATION: {
        b.setClassLoader(IoTResultCodes.class.getClassLoader());
        IoTResultCodes resultCode = (IoTResultCodes) b.getSerializable(IoTServiceCommand.KEY_RESULT);
        if (resultCode != null && resultCode.equals(IoTResultCodes.SUCCESS)) {
            // success
            Log.d(TAG, ">> IoT READ_WRITE_SET_NOTIFICATION success...");
        } else {
            Log.e(TAG, ">> IoT READ_WRITE_SET_NOTIFICATION failed code = " + resultCode);
            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;
    }
    default:
        Log.d(TAG, "unknown command..");
        break;
    }
}

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 ww  .jav  a  2s .  co  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:com.nbplus.iotapp.service.IoTService.java

public void handleMessage(Message msg) {
    if (msg == null) {
        return;//  ww w. ja v  a2 s. c  om
    }
    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;
    }

    }
}