Example usage for android.content Intent getBooleanExtra

List of usage examples for android.content Intent getBooleanExtra

Introduction

In this page you can find the example usage for android.content Intent getBooleanExtra.

Prototype

public boolean getBooleanExtra(String name, boolean defaultValue) 

Source Link

Document

Retrieve extended data from the intent.

Usage

From source file:com.money.manager.ex.home.MainActivity.java

private void handleIntent() {
    Intent intent = getIntent();
    if (intent == null)
        return;/*from ww w  .  ja  v a 2 s .co  m*/

    // Open a db file
    if (intent.getData() != null) {
        String pathFile = getIntent().getData().getEncodedPath();
        // decode
        try {
            String filePath = URLDecoder.decode(pathFile, "UTF-8"); // decode file path
            Timber.d("Path intent file to open: %s", filePath);

            // Open this database.
            DatabaseMetadata db = DatabaseMetadataFactory.getInstance(filePath);
            changeDatabase(db);
            return;
        } catch (Exception e) {
            Timber.e(e, "opening database from intent");
        }
    }

    boolean skipRemoteCheck = intent.getBooleanExtra(EXTRA_SKIP_REMOTE_CHECK, false);
    this.dbUpdateCheckDone = skipRemoteCheck;
}

From source file:com.android.calendar.AllInOneActivity.java

private long parseViewAction(final Intent intent) {
    long timeMillis = -1;
    Uri data = intent.getData();/*  w w  w  . j  a  v  a 2s  .c o  m*/
    if (data != null && data.isHierarchical()) {
        List<String> path = data.getPathSegments();
        if (path.size() == 2 && path.get(0).equals("events")) {
            try {
                mViewEventId = Long.valueOf(data.getLastPathSegment());
                if (mViewEventId != -1) {
                    mIntentEventStartMillis = intent.getLongExtra(EXTRA_EVENT_BEGIN_TIME, 0);
                    mIntentEventEndMillis = intent.getLongExtra(EXTRA_EVENT_END_TIME, 0);
                    mIntentAttendeeResponse = intent.getIntExtra(ATTENDEE_STATUS,
                            Attendees.ATTENDEE_STATUS_NONE);
                    mIntentAllDay = intent.getBooleanExtra(EXTRA_EVENT_ALL_DAY, false);
                    timeMillis = mIntentEventStartMillis;
                }
            } catch (NumberFormatException e) {
                // Ignore if mViewEventId can't be parsed
            }
        }
    }
    return timeMillis;
}

From source file:com.tct.email.activity.setup.EmailPreferenceActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    final Intent i = getIntent();
    if (savedInstanceState == null) {
        // If we are not restarting from a previous instance, we need to
        // figure out the initial prefs to show.  (Otherwise, we want to
        // continue showing whatever the user last selected.)
        if (INTENT_ACCOUNT_MANAGER_ENTRY == null) {
            INTENT_ACCOUNT_MANAGER_ENTRY = getString(R.string.intent_account_manager_entry);
        }/*  w w w. ja v a 2s .  c  o m*/
        if (INTENT_ACCOUNT_MANAGER_ENTRY.equals(i.getAction())) {
            // This case occurs if we're changing account settings from Settings -> Accounts.
            // We get an account object in the intent, but it's not actually useful to us since
            // it's always just the first account of that type. The user can't specify which
            // account they wish to view from within the settings UI, so just dump them at the
            // main screen.
            // android.accounts.Account acct = i.getParcelableExtra("account");
        } else if (i.hasExtra(EditSettingsExtras.EXTRA_FOLDER)) {
            throw new IllegalArgumentException("EXTRA_FOLDER is no longer supported");
        } else {
            // Otherwise, we're called from within the Email app and look for our extras
            final long accountId = IntentUtilities.getAccountIdFromIntent(i);
            if (accountId != -1) {
                final Bundle args = AccountSettingsFragment.buildArguments(accountId);
                startPreferencePanel(AccountSettingsFragment.class.getName(), args, 0, null, null, 0);
                // TS: jin.dong 2015-08-07 EMAIL BUGFIX_989528 ADD_S
                finish();
                return;
                // TS: jin.dong 2015-08-07 EMAIL BUGFIX_989528 ADD_E
            }
        }
    }
    mShowDebugMenu = i.getBooleanExtra(EXTRA_ENABLE_DEBUG, false);

    final ActionBar actionBar = getActionBar();
    if (actionBar != null) {
        actionBar.setDisplayOptions(ActionBar.DISPLAY_HOME_AS_UP, ActionBar.DISPLAY_HOME_AS_UP);
    }
    ListView listView = getListView();
    if (listView != null) {
        listView.setDivider(new ColorDrawable(Color.GRAY));
        listView.setDividerHeight(1);
    }
    mFeedbackUri = Utils.getValidUri(getString(R.string.email_feedback_uri));
}

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

/**
 * Called when an activity called by this activity returns a result. This method was initially
 * added to handle the result of choosing a GPX file for the LocationSimulator.
 *///  w  ww  .  j a v a 2 s .c o m
@Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
    switch (requestCode) {
    case REQUEST_CHOOSER:
        if (resultCode == RESULT_OK) {
            final Uri uri = data.getData();
            File file = new File(FileUtils.getPath(this, uri));
            mapController.getLocationController().setGpxFile(file, true);
            try {
                mapController.getLocationController().setMode(LocationMode.SIMULATOR, true);
                mapController.getLocationController().start();
            } catch (Exception e) {
                Log.d(TAG, "Could not start simulator", e);
            }
        }
        break;
    case SETTINGS_ACTIVITY:
        if (null != data && data.getBooleanExtra(getString(R.string.pref_resetApp), false)) {
            try {
                mapController.reset();
            } catch (Throwable t) {
                Log.e(TAG, "Could not reset map", t);
            }
        }
        break;
    case SPOT_REPORT_ACTIVITY:
        if (null != data && null != data.getExtras()) {
            final SpotReport spotReport = (SpotReport) data.getExtras()
                    .get(getPackageName() + "." + SpotReportActivity.SPOT_REPORT_EXTRA_NAME);
            if (null != spotReport) {
                new Thread() {

                    @Override
                    public void run() {
                        String mgrs = (String) data.getExtras()
                                .get(getPackageName() + "." + SpotReportActivity.MGRS_EXTRA_NAME);
                        if (null != mgrs) {
                            Point pt = mapController.mgrsToPoint(mgrs);
                            if (null != pt) {
                                spotReport.setLocationX(pt.getX());
                                spotReport.setLocationY(pt.getY());
                                if (null != getSpatialReference()) {
                                    spotReport.setLocationWkid(getSpatialReference().getID());
                                }
                            }
                        }
                        try {
                            spotReportController.sendSpotReport(spotReport, usernamePreference);
                        } catch (Exception e) {
                            Log.e(TAG, "Could not send spot report", e);
                            //TODO notify user?
                        }
                    }
                }.start();
            }
        }
        break;
    case ADD_LAYER_FROM_FILE:
        addLayerDialogFragment.onActivityResult(requestCode, resultCode, data);
        break;
    default:
        super.onActivityResult(requestCode, resultCode, data);
    }
}

From source file:ch.teamuit.android.soundplusplus.LibraryActivity.java

/**
 * Creates a context menu for an adapter row.
 *
 * @param menu The menu to create./*from   w w w. j  av a  2 s  .  c  o  m*/
 * @param rowData Data for the adapter row.
 */
public void onCreateContextMenu(ContextMenu menu, Intent rowData) {
    if (rowData.getLongExtra(LibraryAdapter.DATA_ID, LibraryAdapter.INVALID_ID) == LibraryAdapter.HEADER_ID) {
        menu.setHeaderTitle(getString(R.string.all_songs));
        menu.add(0, CTX_MENU_PLAY_ALL, 0, R.string.play_all).setIntent(rowData);
        menu.add(0, CTX_MENU_ENQUEUE_ALL, 0, R.string.enqueue_all).setIntent(rowData);
        menu.addSubMenu(0, CTX_MENU_ADD_TO_PLAYLIST, 0, R.string.add_to_playlist).getItem().setIntent(rowData);
    } else {
        int type = rowData.getIntExtra(LibraryAdapter.DATA_TYPE, MediaUtils.TYPE_INVALID);

        menu.setHeaderTitle(rowData.getStringExtra(LibraryAdapter.DATA_TITLE));

        if (FileUtils.canDispatchIntent(rowData))
            menu.add(0, CTX_MENU_OPEN_EXTERNAL, 0, R.string.open).setIntent(rowData);
        menu.add(0, CTX_MENU_PLAY, 0, R.string.play).setIntent(rowData);
        if (type <= MediaUtils.TYPE_SONG) {
            menu.add(0, CTX_MENU_PLAY_ALL, 0, R.string.play_all).setIntent(rowData);
        }
        menu.add(0, CTX_MENU_ENQUEUE_AS_NEXT, 0, R.string.enqueue_as_next).setIntent(rowData);
        menu.add(0, CTX_MENU_ENQUEUE, 0, R.string.enqueue).setIntent(rowData);
        if (type == MediaUtils.TYPE_PLAYLIST) {
            menu.add(0, CTX_MENU_RENAME_PLAYLIST, 0, R.string.rename).setIntent(rowData);
        } else if (rowData.getBooleanExtra(LibraryAdapter.DATA_EXPANDABLE, false)) {
            menu.add(0, CTX_MENU_EXPAND, 0, R.string.expand).setIntent(rowData);
        }
        if (type == MediaUtils.TYPE_ALBUM || type == MediaUtils.TYPE_SONG)
            menu.add(0, CTX_MENU_MORE_FROM_ARTIST, 0, R.string.more_from_artist).setIntent(rowData);
        if (type == MediaUtils.TYPE_SONG)
            menu.add(0, CTX_MENU_MORE_FROM_ALBUM, 0, R.string.more_from_album).setIntent(rowData);
        menu.addSubMenu(0, CTX_MENU_ADD_TO_PLAYLIST, 0, R.string.add_to_playlist).getItem().setIntent(rowData);
        menu.add(0, CTX_MENU_DELETE, 0, R.string.delete).setIntent(rowData);
    }
}

From source file:com.devbrackets.android.playlistcore.service.PlaylistServiceCore.java

/**
 * Handles the intents posted by the {@link BasePlaylistManager} through
 * the <code>invoke*</code> methods.
 *//* ww  w. ja  v a 2  s. c  o  m*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent == null || intent.getAction() == null) {
        return getServiceContinuationMethod();
    }

    //This is a workaround for an issue on the Samsung Galaxy S3 (4.4.2) where the onStartCommand will occasionally get called before onCreate
    if (!onCreateCalled) {
        Log.d(TAG, "Starting Samsung workaround");
        workaroundIntent = intent;
        onCreate();
        return getServiceContinuationMethod();
    }

    if (RemoteActions.ACTION_START_SERVICE.equals(intent.getAction())) {
        seekToPosition = intent.getLongExtra(RemoteActions.ACTION_EXTRA_SEEK_POSITION, -1);
        immediatelyPause = intent.getBooleanExtra(RemoteActions.ACTION_EXTRA_START_PAUSED, false);

        startItemPlayback();
    } else {
        handleRemoteAction(intent.getAction(), intent.getExtras());
    }

    return getServiceContinuationMethod();
}

From source file:com.mobicage.rogerthat.plugins.messaging.MessagingPlugin.java

public MessagingPlugin(final ConfigurationProvider pConfigProvider, final MainService pMainService,
        final DatabaseManager pDatabaseManager, final BrandingMgr brandingMgr) {
    T.UI();/*w  w  w.j  a v a2  s .c o  m*/
    mConfigProvider = pConfigProvider;
    mMainService = pMainService;
    mStore = new MessageStore(pDatabaseManager, pMainService);
    mBrandingMgr = brandingMgr;
    mMessageHistory = new MessageHistory(mMainService, mStore);
    mAlertMgr = new AlertManager(pMainService, mStore);
    mMyEmail = mMainService.getIdentityStore().getIdentity().getEmail();

    mMainService.addHighPriorityIntent(MessagingPlugin.MESSAGE_PROCESSED_INTENT);
    mMainService.addHighPriorityIntent(MessagingPlugin.MESSAGE_LOCKED_INTENT);
    mMainService.addHighPriorityIntent(MessagingPlugin.NEW_MESSAGE_QUEUED_TO_BACKLOG_INTENT);
    mMainService.addHighPriorityIntent(MessagingPlugin.NEW_MESSAGE_RECEIVED_INTENT);
    mMainService.addHighPriorityIntent(MessagingPlugin.THREAD_DELETED_INTENT);
    mMainService.addHighPriorityIntent(MessagingPlugin.MESSAGE_JSMFR_ERROR);
    mMainService.addHighPriorityIntent(MessagingPlugin.MESSAGE_SUBMIT_PHOTO_UPLOAD);
    mMainService.addHighPriorityIntent(BrandingMgr.ATTACHMENT_AVAILABLE_INTENT);

    mMainService.postOnBIZZHandler(new SafeRunnable() {
        @Override
        protected void safeRun() throws Exception {
            transferQueueLoad();
        }
    });

    mBroadcastReceiver = new SafeBroadcastReceiver() {
        @Override
        public String[] onSafeReceive(Context context, Intent intent) {
            T.UI();

            final String action = intent.getAction();
            if (HttpCommunicator.INTENT_HTTP_START_OUTGOING_CALLS.equals(action)) {
                boolean filterOnWifiOnly = !intent
                        .getBooleanExtra(HttpCommunicator.INTENT_HTTP_START_OUTGOING_CALLS_WIFI, false);
                if (mTransferQueue.size() > 0) {
                    if (filterOnWifiOnly) {
                        showTransferPendingNotification(
                                mMainService.getString(R.string.transfer_uploading_notification));
                    } else {
                        SharedPreferences options = PreferenceManager.getDefaultSharedPreferences(mMainService);
                        boolean wifiOnlySettingEnabled = options
                                .getBoolean(MainService.PREFERENCE_UPLOAD_PHOTO_WIFI, false);
                        if (!mMainService.getNetworkConnectivityManager().isConnected()) {
                            showTransferPendingNotification(
                                    mMainService.getString(R.string.transfer_pending_notification_no_network));
                        } else if (wifiOnlySettingEnabled
                                && !mMainService.getNetworkConnectivityManager().isWifiConnected()) {
                            showTransferPendingNotification(
                                    mMainService.getString(R.string.transfer_pending_notification_no_wifi));
                        }
                    }

                }

            } else {
                L.d("Error - received unexpected intent in MessagingPlugin: action=" + action);
            }
            return null;
        }
    };

    final IntentFilter filter = new IntentFilter();
    filter.addAction(HttpCommunicator.INTENT_HTTP_START_OUTGOING_CALLS);
    mMainService.registerReceiver(mBroadcastReceiver, filter);
}

From source file:com.geekandroid.sdk.sample.JPushReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    Bundle bundle = intent.getExtras();/*from  w  w w . j a v  a 2s  .  c  om*/
    Log.d(TAG, "[JPushReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));

    if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
        String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
        Log.d(TAG, "[JPushReceiver] Registration Id : " + regId);
        //send the Registration Id to your server...

    } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
        Log.d(TAG, "[JPushReceiver] ???: "
                + bundle.getString(JPushInterface.EXTRA_MESSAGE));
        processCustomMessage(context, bundle);

    } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
        Log.d(TAG, "[JPushReceiver] ??");
        int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
        Log.d(TAG, "[JPushReceiver] ??ID: " + notifactionId);

    } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
        Log.d(TAG, "[JPushReceiver] ");
        JPushImpl.getInstance().clearAllNotifications();

        //Activity
        Intent i = new Intent(context, JPushOpenActivity.class);
        i.putExtras(bundle);
        //i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(i);

    } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
        Log.d(TAG, "[JPushReceiver] RICH PUSH CALLBACK: "
                + bundle.getString(JPushInterface.EXTRA_EXTRA));
        //? JPushInterface.EXTRA_EXTRA ??Activity ..

    } else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
        boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
        Log.w(TAG, "[JPushReceiver]" + intent.getAction() + " connected state change to " + connected);
    } else {
        Log.d(TAG, "[JPushReceiver] Unhandled intent - " + intent.getAction());
    }
}

From source file:ch.blinkenlights.android.vanilla.LibraryActivity.java

/**
 * Creates a context menu for an adapter row.
 *
 * @param menu The menu to create.//from ww  w  .j a v a  2 s  .  co m
 * @param rowData Data for the adapter row.
 */
public void onCreateContextMenu(ContextMenu menu, Intent rowData) {
    if (rowData.getLongExtra(LibraryAdapter.DATA_ID, LibraryAdapter.INVALID_ID) == LibraryAdapter.HEADER_ID) {
        menu.setHeaderTitle(getString(R.string.all_songs));
        menu.add(0, CTX_MENU_PLAY_ALL, 0, R.string.play_all).setIntent(rowData);
        menu.add(0, CTX_MENU_ENQUEUE_ALL, 0, R.string.enqueue_all).setIntent(rowData);
        menu.addSubMenu(0, CTX_MENU_ADD_TO_PLAYLIST, 0, R.string.add_to_playlist).getItem().setIntent(rowData);
    } else {
        int type = rowData.getIntExtra(LibraryAdapter.DATA_TYPE, MediaUtils.TYPE_INVALID);

        menu.setHeaderTitle(rowData.getStringExtra(LibraryAdapter.DATA_TITLE));

        if (FileUtils.canDispatchIntent(rowData))
            menu.add(0, CTX_MENU_OPEN_EXTERNAL, 0, R.string.open).setIntent(rowData);
        menu.add(0, CTX_MENU_PLAY, 0, R.string.play).setIntent(rowData);
        if (type <= MediaUtils.TYPE_SONG) {
            menu.add(0, CTX_MENU_PLAY_ALL, 0, R.string.play_all).setIntent(rowData);
        }
        menu.add(0, CTX_MENU_ENQUEUE_AS_NEXT, 0, R.string.enqueue_as_next).setIntent(rowData);
        menu.add(0, CTX_MENU_ENQUEUE, 0, R.string.enqueue).setIntent(rowData);
        if (type == MediaUtils.TYPE_PLAYLIST) {
            menu.add(0, CTX_MENU_RENAME_PLAYLIST, 0, R.string.rename).setIntent(rowData);
        } else if (rowData.getBooleanExtra(LibraryAdapter.DATA_EXPANDABLE, false)) {
            menu.add(0, CTX_MENU_EXPAND, 0, R.string.expand).setIntent(rowData);
        }
        if (type == MediaUtils.TYPE_ALBUM || type == MediaUtils.TYPE_SONG)
            menu.add(0, CTX_MENU_MORE_FROM_ARTIST, 0, R.string.more_from_artist).setIntent(rowData);
        if (type == MediaUtils.TYPE_SONG) {
            menu.add(0, CTX_MENU_MORE_FROM_ALBUM, 0, R.string.more_from_album).setIntent(rowData);
            if (PluginUtils.checkPlugins(this))
                menu.add(0, CTX_MENU_PLUGINS, 1, R.string.plugins).setIntent(rowData); // last in order
        }
        menu.addSubMenu(0, CTX_MENU_ADD_TO_PLAYLIST, 0, R.string.add_to_playlist).getItem().setIntent(rowData);
        menu.add(0, CTX_MENU_DELETE, 0, R.string.delete).setIntent(rowData);
    }
}

From source file:com.digi.android.wva.VehicleInfoService.java

/**
 * Take the Intent that was used to call startService (i.e. the
 * intent used to give a command to the service) and the command
 * that it had as an extra and act on it accordingly.
  *//  w w w. j  a  v  a  2 s  .  co  m
  * <p>This method is protected, rather than private, due to a bug between JaCoCo and
  * the Android build tools which causes the instrumented bytecode to be invalid when this
  * method is private:
  * http://stackoverflow.com/questions/17603192/dalvik-transformation-using-wrong-invoke-opcode
  * </p>
 *
 * @param intent the intent used to call startService
 * @param command the command that the intent had as an extra
 */
protected synchronized void parseIntent(Intent intent, int command) {
    boolean isConnect = false;
    final WvaApplication app = (WvaApplication) getApplication();
    if (app == null) {
        // Based on Android sources, this would only happen if the service is
        // not attached to an application... In this case, we can't know what
        // is a valid thing to do here.
        Log.e(TAG, "getApplication() returned null!");
        return;
    }
    switch (command) {
    case CMD_APPCREATE:
        Log.i(TAG, "startService - CMD_APPCREATE");
        isConnected = false;
        break;
    case CMD_CONNECT:
        Log.i(TAG, "startService - CMD_CONNECT");
        isConnect = true;
        break;
    case CMD_DISCONNECT:
        Log.i(TAG, "startService - CMD_DISCONNECT");
        isConnected = false;
        if (mDevice != null) {
            mDevice.disconnectEventChannel(true);
            mDevice = null;
            app.setDevice(null);
        } else {
            Log.d(TAG, "Got CMD_DISCONNECT but mDevice is null");
        }
        break;
    default:
        Log.i(TAG, "startService - unknown command " + command);
        isConnected = false;
    }

    if (isConnect) {
        String ip = intent.getStringExtra(INTENT_IP);
        String username = intent.getStringExtra(INTENT_AUTH_USER);
        String password = intent.getStringExtra(INTENT_AUTH_PASS);
        boolean useHttps = intent.getBooleanExtra(INTENT_HTTPS, true);
        if (TextUtils.isEmpty(ip)) {
            Log.e(TAG, "startService given connect command with empty IP!");
            isConnected = false;
        } else {
            final int port = Integer.valueOf(
                    PreferenceManager.getDefaultSharedPreferences(this).getString("pref_device_port", "5000"));
            connectIp = ip;
            isConnected = false;

            boolean autoSubscribe = PreferenceManager.getDefaultSharedPreferences(this)
                    .getBoolean("pref_auto_subscribe", false);
            final int autosub = autoSubscribe ? Integer.valueOf(PreferenceManager
                    .getDefaultSharedPreferences(this).getString("pref_default_interval", "-1")) : -1;

            Log.i(TAG, "Initiating connection to " + connectIp);

            // Structuring the code like this allows us to
            // inject Device instances for testing. Otherwise,
            // it would become difficult to unit-test
            // VehicleInfoService.

            mDevice = app.getDevice();
            if (mDevice == null) {
                mDevice = new WVA(connectIp);

                // Set up authentication and HTTP(S) configuration.
                // The demo app assumes default HTTP and HTTPS ports.
                mDevice.useBasicAuth(username, password).useSecureHttp(useHttps).setHttpPort(80)
                        .setHttpsPort(443);

                app.setDevice(mDevice);
            }

            mDevice.fetchVehicleDataEndpoints(new WvaCallback<Set<String>>() {
                @Override
                public void onResponse(Throwable error, Set<String> endpoints) {
                    Log.d(TAG, "initVehicleData onResponse...");
                    if (error != null) {
                        Log.e(TAG, "Got error starting Vehicle", error);
                        // Stop WVA inner threads (TCPReceiver, MessageHandler)
                        synchronized (VehicleInfoService.this) {
                            mDevice.disconnectEventChannel();
                            mDevice = null;
                            app.setDevice(null);
                        }
                        String err = error.getMessage();
                        if (TextUtils.isEmpty(err)) {
                            Throwable cause = error.getCause();
                            if (cause != null)
                                err = cause.getMessage();
                            else
                                err = error.toString();
                        }
                        MessageCourier.sendError(err);
                        return;
                    }

                    // Sort the endpoints set
                    final List<String> sortedEndpoints = VehicleEndpointComparator.asSortedList(endpoints);

                    Log.d(TAG, "Beginning endpoint handling");

                    // First, add them all to the adapter.
                    for (String e : sortedEndpoints) {
                        // To improve performance, we add the endpoint to the endpoints list here,
                        // but do not notify it that the data set has changed. We then notify only
                        // after adding all endpoints.
                        EndpointsAdapter.getInstance().add(new EndpointConfiguration(e), false);
                    }

                    // Update the endpoints adapter.
                    mHandler.postAtFrontOfQueue(new Runnable() {
                        @Override
                        public void run() {
                            Log.d("VIS", "Updating endpoints adapter");
                            EndpointsAdapter.getInstance().notifyDataSetChanged();
                        }
                    });

                    // Handle subscribing/unsubscribing on a separate thread.
                    if (autosub > 0) {
                        Runnable doSubscriptions = new Runnable() {
                            @Override
                            public void run() {
                                for (String e : sortedEndpoints) {
                                    // Add a bit of sleep between subscribing
                                    // to each endpoint, so as not to overload
                                    // the main thread as it tries to keep up.
                                    // This is happening as soon as the
                                    // DashboardActivity is launched, after all.
                                    try {
                                        Thread.sleep(25);
                                    } catch (InterruptedException ignored) {
                                    }

                                    if (app.getDevice() == null) {
                                        // User backed out of DashboardActivity
                                        // We should stop these subscriptions...
                                        Log.d(TAG, "app.getDevice() returned null. "
                                                + "Stopping subscriptions...");
                                        app.clearDevice();
                                        return;
                                    }

                                    final String ep = e;

                                    boolean isPressurePro = false;
                                    for (String s : VehicleEndpointComparator.PRESSURE_PRO_PREFIXES) {
                                        if (ep.startsWith(s)) {
                                            isPressurePro = true;
                                            break;
                                        }
                                    }

                                    if (!isPressurePro) {
                                        // (Try to) subscribe to the endpoint
                                        app.subscribeToEndpointFromService(e, autosub, new WvaCallback<Void>() {
                                            @Override
                                            public void onResponse(Throwable error, Void response) {
                                                String msg;
                                                if (error != null) {
                                                    msg = "Failed to subscribe to " + ep;
                                                    Log.e(TAG, "Failed to subscribe to " + ep, error);
                                                    final LogEvent evt = new LogEvent(msg, null);
                                                    mHandler.post(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            LogAdapter.getInstance().add(evt);
                                                        }
                                                    });
                                                }
                                            }
                                        });
                                    }
                                }
                            }
                        };

                        // Do subscriptions on this thread when running unit tests,
                        // but on a separate thread when actually being used. This allows
                        // us to test the code in the runnable.
                        if (app.isTesting()) {
                            doSubscriptions.run();
                        } else {
                            new Thread(doSubscriptions).start();
                        }
                    }
                }
            });

            if (mDevice == null)
                return;

            // Ensure that the correct state listener is used.
            mDevice.setEventChannelStateListener(makeStateListener());
            mDevice.connectEventChannel(port);

            if (mDevice == null)
                return;

            // Android Studio warns that getApplicationContext() might
            // return null. So we will check for null in the callbacks.
            final Context toastContext = getApplicationContext();

            JSONObject portJson = new JSONObject();
            try {
                portJson.put("port", port);
                portJson.put("enable", "on");
            } catch (JSONException e) {
                e.printStackTrace();
                return;
            }

            mDevice.configure("ws_events", portJson, new WvaCallback<Void>() {
                @Override
                public void onResponse(Throwable error, Void response) {
                    if (error == null) {
                        Log.d(TAG, "Successfully configured port.");
                    } else {
                        Log.d(TAG, "Failed to configure port", error);
                        if (toastContext != null) {
                            Toast.makeText(toastContext, "Failed to set port to " + port, Toast.LENGTH_SHORT)
                                    .show();
                        }
                    }
                }
            });
        }
    }
}