How to keep a Bluetooth connection when Sphero is synchronized and I use several Activities

1.3k views Asked by At

When I have synchronized with Sphero and I want to pass from one activity to another one, my synchronization is lost, and I have to do in the new activity this method in onCreate to get de synchronism again:

        **RobotProvider provider = RobotProvider.getDefaultProvider();
        mRobot = provider.findRobot(robot_id);
        provider.initiateConnection(robot_id);
        provider.control(mRobot);
        provider.connectControlledRobots();**

mRobot has the MAC address of Sphero. But it's not good for all times that I try it, I want to keep the bluetooth connection for all application, since I connect for the first time and being able to keep it without synchronize again.

I have seen the official Orbotix application for Sphero and I think is perfect, because syncronization is permanent. Could you help me in this way?

1

There are 1 answers

0
nodnarb On BEST ANSWER

At Orbotix, we generally use a central Activity and either show temporary activities over the top of it, or (more recently) we use a FragmentActivity that first shows a fragment that takes care of the connection (synchronization in your question). From there, we show different screens using different, custom fragments.

If you absolutely need to send a Robot object through to another Activity, you can add the robot id to the Intent and then obtain the robot object from RobotProvider in the new Activity. This also requires you to make sure you don't disconnect from Sphero based on the lifecycle of the original Activity.

In your original Activity:

    private void startNextActivity() {
        Intent nextActivity = new Intent(this, NextActivity.class);
        nextActivity.putExtra("robot.id", mRobot.getUniqueId());
        goingToNextActivity = true;
        startActivity(nextActivity);
    }

    @Override
    protected void onStop() {
        super.onStop();

        // don't disconnect if headed to "NextActivity"
        if (!goingToNextActivity) {
            RobotProvider.getDefaultProvider().disconnect(mRobot);
            mRobot = null;
        }
    }

In your new Activity:

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

        // get the robot object sent through to this Activity
        String robotId = getIntent().getStringExtra("robot.id");
        Robot robot = RobotProvider.getDefaultProvider().findRobot(robotId);
    }