Example usage for android.os Message Message

List of usage examples for android.os Message Message

Introduction

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

Prototype

public Message() 

Source Link

Document

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

Usage

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

public void deletegoods(final String id) {
    new Thread() {
        Message msg = new Message();

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

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

/**
 * This download the release information for a specific movie.
 *
 * @param messageHandler The message handler that will receive the result.
 * @param movieId The movie Id to get the information for.
 *//*from w ww  . ja v a2  s  . com*/
public static void getReleasesForMovie(final Handler messageHandler, final int movieId) {
    if (!Preferences.isSet(Preferences.COUCHPOTATO_URL)) {
        return;
    }

    Thread thread = new Thread() {

        @Override
        public void run() {

            try {
                String result = makeApiCall(MESSAGE.RELEASE_FOR_MOVIE.toString().toLowerCase(),
                        "id=" + movieId);
                JSONObject jsonObject = new JSONObject(result);
                MovieReleases movieReleases = null;

                if (!jsonObject.isNull("message") && !"".equals(jsonObject.getString("message"))) {
                    sendUpdateMessageStatus(messageHandler, "CouchPotato : " + jsonObject.getString("message"));
                } else {
                    SimpleJSONMarshaller jsonMarshaller = new SimpleJSONMarshaller(MovieReleases.class);
                    movieReleases = (MovieReleases) jsonMarshaller.unMarshal(jsonObject);
                }

                Message message = new Message();
                message.setTarget(messageHandler);
                message.what = MESSAGE.RELEASE_FOR_MOVIE.hashCode();
                message.obj = movieReleases;
                message.sendToTarget();
            } catch (RuntimeException e) {
                Log.w(TAG, " " + e.getLocalizedMessage());
            } catch (Throwable e) {
                Log.w(TAG, " " + e.getLocalizedMessage());
            }
        }
    };

    thread.start();
}

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

private void handleServiceMessage(Message msg) {
    switch (msg.what) {
    case IoTServiceCommand.COMMAND_RESPONSE: {
        Bundle b = msg.getData();//ww w .  j  a va  2 s  .c o  m
        if (b == null) {
            Log.w(TAG, "bundle data is null");
            return;
        }
        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.android.launcher3.widget.DigitalAppWidgetProvider.java

public void getWeather(final String url) {
    Log.e("sai", "getWeather url = " + url);
    new Thread() {
        public void run() {
            String line = "";
            HttpGet request = new HttpGet(url);

            HttpParams params = new BasicHttpParams();
            HttpClient httpClient = new DefaultHttpClient(params);
            try {
                HttpResponse response = httpClient.execute(request);
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    String content = EntityUtils.toString(response.getEntity());
                    //Log.e("sai", "content = " + content);
                    line = setWeatherSituation(content);
                    Log.e("sai", "line = " + line);
                } else {
                    //Toast.makeText(mContext, "???!", Toast.LENGTH_LONG).show();
                }/*from w  ww . j  a v a 2 s.c  o  m*/

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                httpClient.getConnectionManager().shutdown();
            }
            Message message = new Message();
            message.what = 2;
            message.obj = line;
            myHandler.sendMessage(message);
        };
    }.start();
}

From source file:com.todoroo.astrid.taskrabbit.TaskRabbitActivity.java

@SuppressWarnings("nls")
protected void submitTaskRabbit() {

    if (!Preferences.isSet(TASK_RABBIT_TOKEN)) {
        loginTaskRabbit();//from ww  w .  ja  v  a  2s .  c om
    } else if (!supportsSelectedLocation()) {
        Message successMessage = new Message();
        successMessage.what = MESSAGE_CODE_LOCATION_FAILURE;
        handler.sendMessage(successMessage);
    } else {

        if (progressDialog == null)
            progressDialog = DialogUtilities.progressDialog(this, getString(R.string.DLG_please_wait));
        new Thread(new Runnable() {
            @Override
            public void run() {
                boolean success = false;

                String urlCall = "tasks/";
                if (taskRabbitTask.getTaskID() > 0)
                    urlCall += taskRabbitTask.getTaskID();
                urlCall += String.format("?client_id=%s&client_application=%s", TASK_RABBIT_CLIENT_ID,
                        TASK_RABBIT_CLIENT_APPLICATION_ID);
                Header authorization = new BasicHeader("Authorization",
                        "OAuth " + Preferences.getStringValue(TASK_RABBIT_TOKEN));
                Header contentType = new BasicHeader("Content-Type", "application/json");
                HttpEntity taskBody = getTaskBody();
                String response = null;
                try {
                    response = restClient.post(taskRabbitURL(urlCall), taskBody, contentType, authorization);
                    Log.e("The response", "The post response: " + response);
                    JSONObject taskResponse = new JSONObject(response);
                    if (taskResponse.has(TASK_RABBIT_ID)) {
                        taskRabbitTask.setRemoteTaskData(response);
                        taskRabbitTask.setTaskID(taskResponse.optString(TASK_RABBIT_ID));
                        Message successMessage = new Message();
                        successMessage.what = MESSAGE_CODE_SUCCESS;
                        handler.sendMessage(successMessage);
                        success = true;
                    }
                } catch (UnknownHostException e) {
                    Message failureMessage = new Message();
                    failureMessage.what = MESSAGE_CODE_INTERNET_FAILURE;
                    handler.sendMessage(failureMessage);
                } catch (Exception e) {
                    Message failureMessage = new Message();
                    failureMessage.what = MESSAGE_CODE_FAILURE;
                    handler.sendMessage(failureMessage);
                } finally {
                    StatisticsService.reportEvent(StatisticsConstants.TASK_RABBIT_POST, "success",
                            new Boolean(success).toString());
                    runOnUiThread(new Runnable() {
                        public void run() {
                            if (progressDialog != null) {
                                DialogUtilities.dismissDialog(TaskRabbitActivity.this, progressDialog);
                            }
                        }
                    });
                }
            }
        }).start();

    }
    try {
        taskRabbitTask.setLocalTaskData(serializeToJSON().toString());
    } catch (JSONException e) {
        e.printStackTrace();
    }

    //submit!
}

From source file:org.hfoss.posit.android.functionplugin.reminder.SetReminder.java

private void retrieveLocation() {
    // Build HTTP request
    StringBuilder builder = new StringBuilder();
    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(
            "http://maps.google." + "com/maps/api/geocode/json?address=" + addressURL + "&sensor=false");

    // Send HTTP request
    try {//from  w ww. j  av  a  2 s  . co m
        HttpResponse response = client.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();

        if (statusCode == 200) {
            // Read the returned content into a string
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
        } else {
            // Something is wrong, inform user of the error
            Log.e(TAG, "Failed to download file");
            Toast.makeText(getApplicationContext(), "Location retrieval failed. Please try again",
                    Toast.LENGTH_LONG).show();
            Message msg = new Message();
            msg.obj = "SHOW ADDRESS ENTER DIALOG";
            handler.sendMessage(msg);
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    // Create the JSONObject for parsing the string returned
    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject = new JSONObject(builder.toString());
    } catch (JSONException e) {
        e.printStackTrace();
    }

    // Parse the string returned into JSONObject
    try {
        addressArray = (JSONArray) jsonObject.get("results");
    } catch (JSONException e) {
        e.printStackTrace();
    }

    if (addressArray == null) {
        // Nothing returned, inform the user of the error
        Message msg = new Message();
        msg.obj = "SHOW ADDRESS ENTER DIALOG - FAILED";
        handler.sendMessage(msg);
    } else if (addressArray.length() == 0) {
        // No match found, inform the user of the error
        Message msg = new Message();
        msg.obj = "SHOW ADDRESS ENTER DIALOG - NO RESULTS";
        handler.sendMessage(msg);
    } else if (addressArray.length() == 1) {
        // Exact one result returned
        // Set the intent back to FindActivity
        Bundle bundle = new Bundle();
        Intent newIntent = new Intent();
        bundle.putString(Find.TIME, date);
        Double lng = new Double(0);
        Double lat = new Double(0);
        // Parse the JSONObject to get the longitude and latitude
        try {
            lng = addressArray.getJSONObject(0).getJSONObject("geometry").getJSONObject("location")
                    .getDouble("lng");
            lat = addressArray.getJSONObject(0).getJSONObject("geometry").getJSONObject("location")
                    .getDouble("lat");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        bundle.putDouble(Find.LONGITUDE, lng);
        bundle.putDouble(Find.LATITUDE, lat);
        bundle.putInt(Find.IS_ADHOC, REMINDER_SET);
        newIntent.putExtras(bundle);
        setResult(RESULT_OK, newIntent);
        finish();
    } else {
        // More than one results returned
        // Show Address Confirm Dialog for user confirmation
        Message msg = new Message();
        msg.obj = "SHOW ADDRESS CONFIRM DIALOG";
        handler.sendMessage(msg);
    }
}

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

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

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

From source file:com.xpg.gokit.activity.GokitControlActivity.java

@Override
public void didUnbindDevice(int error, String errorMessage, String did) {
    if (error == 0) {
        Message msg = new Message();
        msg.what = UNBIND_SUCCEED;/* w w w.  j  a  v a 2  s. c  om*/
        handler.sendMessage(msg);
        isUnbind = true;
        xpgWifiDevice.disconnect();
        finish();
    } else {
        Message msg = new Message();
        msg.what = UNBAND_FAIL;
        handler.sendMessage(msg);
    }
}

From source file:com.wheelphone.remotemini.WheelphoneRemoteMini.java

public void displayMessageInt2(int i1, int i2) {
    // We use a handler because this thread cannot change the UI
    Message message = new Message();
    message.obj = String.valueOf(i1) + ", " + String.valueOf(i2);
    Log.d(TAG, "x=" + i1 + ", y=" + i2 + "\n");
    targetX = i1;/* www  . j a v a2  s  .  c  o  m*/
    targetY = i2;
    FrontImageActivity
            .setTextTarget("Target detected at (" + String.valueOf(i1) + ", " + String.valueOf(i2) + ")");
    //mainActivityHandler.sendMessage(message);
    targetTimeout = 0;
    isFollowingTarget = 1;
}

From source file:com.esri.squadleader.view.SquadLeaderActivity.java

private void setupActivity() {
    try {//from  w  w w. ja  v  a  2 s  .com
        ArcGISRuntime.setClientId(getString(R.string.clientId));
    } catch (Throwable t) {
        Log.w(TAG, null, t);
    }
    ArcGISRuntime.License.setLicense(getString(R.string.licenseString));

    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(SquadLeaderActivity.this);
    try {
        usernamePreference = sp.getString(getString(R.string.pref_username), usernamePreference);
    } catch (Throwable t) {
        Log.d(TAG, "Couldn't get preference", t);
    }
    messageController = new MessageController(messagePortPreference, usernamePreference);
    chemLightController = new ChemLightController(messageController, usernamePreference);
    try {
        int wkid = Integer.parseInt(
                sp.getString(getString(R.string.pref_angularUnits), Integer.toString(AngularUnit.Code.DEGREE)));
        angularUnitPreference = (AngularUnit) AngularUnit.create(wkid);
    } catch (Throwable t) {
        Log.d(TAG, "Couldn't get preference", t);
    }
    try {
        messagePortPreference = Integer.parseInt(
                sp.getString(getString(R.string.pref_messagePort), Integer.toString(messagePortPreference)));
        changePort(messagePortPreference);
        messageController.startReceiving();
    } catch (Throwable t) {
        Log.d(TAG, "Couldn't get preference", t);
    }
    try {
        positionReportsPreference = sp.getBoolean(getString(R.string.pref_positionReports), false);
    } catch (Throwable t) {
        Log.d(TAG, "Couldn't get preference", t);
    }
    try {
        positionReportsPeriodPreference = Integer
                .parseInt(sp.getString(getString(R.string.pref_positionReportPeriod),
                        Integer.toString(positionReportsPeriodPreference)));
        if (0 >= positionReportsPeriodPreference) {
            positionReportsPeriodPreference = PositionReportController.DEFAULT_PERIOD;
            sp.edit().putString(getString(R.string.pref_positionReportPeriod),
                    Integer.toString(positionReportsPeriodPreference)).commit();
        }
    } catch (Throwable t) {
        Log.d(TAG, "Couldn't get preference", t);
    }
    try {
        vehicleTypePreference = sp.getString(getString(R.string.pref_vehicleType), vehicleTypePreference);
    } catch (Throwable t) {
        Log.d(TAG, "Couldn't get preference", t);
    }
    try {
        uniqueIdPreference = sp.getString(getString(R.string.pref_uniqueId), uniqueIdPreference);
        //Make sure this one gets set in case we just generated it
        sp.edit().putString(getString(R.string.pref_uniqueId), uniqueIdPreference).commit();
    } catch (Throwable t) {
        Log.d(TAG, "Couldn't get preference", t);
    }
    try {
        sicPreference = sp.getString(getString(R.string.pref_sic), sicPreference);
    } catch (Throwable t) {
        Log.d(TAG, "Couldn't get preference", t);
    }

    PreferenceManager.getDefaultSharedPreferences(getApplicationContext())
            .registerOnSharedPreferenceChangeListener(preferenceChangeListener);

    //        //TODO implement Geo URIs
    //        Uri intentData = getIntent().getData();
    //        if (null != intentData) {
    //            //intentData should be a Geo URI with a location to which we should navigate
    //        }

    activityBinding = (ActivitySquadLeaderBinding) DataBindingUtil.setContentView(this,
            R.layout.activity_squad_leader);
    mainBinding = activityBinding.main;
    clearDisplayStrings();

    adjustLayoutForOrientation(getResources().getConfiguration().orientation);

    final MapView mapView = (MapView) findViewById(R.id.map);

    mapView.setOnPanListener(new OnPanListener() {

        private static final long serialVersionUID = 0x58d30af8d168f63aL;

        @Override
        public void prePointerUp(float fromx, float fromy, float tox, float toy) {
        }

        @Override
        public void prePointerMove(float fromx, float fromy, float tox, float toy) {
            setFollowMe(false);
        }

        @Override
        public void postPointerUp(float fromx, float fromy, float tox, float toy) {
        }

        @Override
        public void postPointerMove(float fromx, float fromy, float tox, float toy) {
        }

    });

    mapController = new MapController(mapView, getAssets(), new LayerErrorListener(this), this);
    mapController.setOnSingleTapListener(defaultOnSingleTapListener);
    northArrowView = (NorthArrowView) findViewById(R.id.northArrowView);
    northArrowView.setMapController(mapController);
    northArrowView.startRotation();

    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
        try {
            instantiateMil2525CController();
        } catch (IOException e) {
            Log.e(TAG, "Could not instantiate advanced symbol controller", e);
        }
    }

    spotReportController = new SpotReportController(mapController, messageController);

    positionReportController = new PositionReportController(mapController.getLocationController(),
            messageController, usernamePreference, vehicleTypePreference, uniqueIdPreference, sicPreference);
    positionReportController.setPeriod(positionReportsPeriodPreference);
    positionReportController.setEnabled(positionReportsPreference);

    mapController.getLocationController().addListener(new LocationListener() {

        @Override
        public void onLocationChanged(final Location location) {
            if (null != location) {
                //Do this in a thread in case we need to calculate the speed
                new Thread() {
                    public void run() {
                        Message msg = new Message();
                        msg.obj = location;
                        locationChangeHandler.sendMessage(msg);
                    }
                }.start();
            }
        }

        @Override
        public void onStateChanged(LocationProviderState state) {

        }
    });

    if (null != mapController.getLastMapConfig()) {
        String viewshedElevationPath = mapController.getLastMapConfig().getViewshedElevationPath();
        if (null == viewshedElevationPath) {
            try {
                viewshedElevationPath = Utilities.readMapConfig(getApplicationContext(), getAssets())
                        .getViewshedElevationPath();
            } catch (Throwable t) {
                Log.e(TAG, "Couldn't set up viewshed", t);
            }
        }
        createViewshedController(viewshedElevationPath);
    }
    mapController.addMapConfigListener(new MapConfigListener() {

        @Override
        public void mapConfigRead(MapConfig mapConfig) {
            String viewshedElevationPath = mapConfig.getViewshedElevationPath();
            if (null == viewshedElevationPath) {
                try {
                    viewshedElevationPath = Utilities.readMapConfig(getApplicationContext(), getAssets())
                            .getViewshedElevationPath();
                } catch (Throwable t) {
                    Log.e(TAG, "Couldn't set up viewshed", t);
                }
            }
            createViewshedController(viewshedElevationPath);
        }
    });

    clockTimerTask = new TimerTask() {

        private final Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                try {
                    if (null != msg.obj) {
                        mainBinding.setDisplayTime(String.format(getString(R.string.display_time), msg.obj));
                    }
                } catch (Throwable t) {
                    Log.i(TAG, "Couldn't update time", t);
                }
            }
        };

        @Override
        public void run() {
            if (null != mapController) {
                Message msg = new Message();
                msg.obj = Utilities.DATE_FORMAT_MILITARY_ZULU.format(new Date());
                handler.sendMessage(msg);
            }
        }

    };
    clockTimer.schedule(clockTimerTask, 0, Utilities.ANIMATION_PERIOD_MS);

    ((RadioGroup) findViewById(R.id.radioGroup_chemLightButtons))
            .setOnCheckedChangeListener(chemLightCheckedChangeListener);

    final BottomSheetBehavior<View> featurePopupBehavior = BottomSheetBehavior
            .from(findViewById(R.id.featurePopup));
    bottomSheetBehavior_featurePopups = featurePopupBehavior;
    bottomSheetBehavior_featurePopups.setState(BottomSheetBehavior.STATE_HIDDEN);
    bottomSheetBehavior_featurePopups.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
        @Override
        public void onStateChanged(@NonNull View bottomSheet, int newState) {
            switch (newState) {
            case BottomSheetBehavior.STATE_COLLAPSED:
            case BottomSheetBehavior.STATE_HIDDEN:
                final View mainView = findViewById(R.id.main);
                final ViewGroup.LayoutParams layoutParams = mainView.getLayoutParams();
                if (layoutParams instanceof ViewGroup.MarginLayoutParams) {
                    Integer newBottomMargin = null;
                    switch (newState) {
                    case BottomSheetBehavior.STATE_COLLAPSED:
                        newBottomMargin = featurePopupBehavior.getPeekHeight();
                        break;

                    case BottomSheetBehavior.STATE_HIDDEN:
                        newBottomMargin = 0;
                        break;
                    }
                    if (null != newBottomMargin) {
                        ((ViewGroup.MarginLayoutParams) layoutParams).setMargins(0, 0, 0, newBottomMargin);
                        mainView.setLayoutParams(layoutParams);
                    }
                }
            }
        }

        @Override
        public void onSlide(@NonNull View bottomSheet, float slideOffset) {

        }
    });
    popupsGroup = (ViewGroup) findViewById(R.id.linearLayout_popups);
    bottomSheetHeading = (TextView) findViewById(R.id.bottomSheetHeading);
}