Skip to main content

Session handling

SmartLib requires only few calls to have a minimum implementation (nanoCDN discovery, CDN advanced features, player analytics...)

This sample code shows how:

  • initialize the lib
  • create a streaming session object
  • attach a player to enable analytics
  • start a streaming session
  • stop a streaming session (standard case and error case).

Launch screen

It is recommended to initialize SmartLib once, in the launch screen. Some background tasks has to be done before starting any streaming session.

public class LaunchScreenActivity extends Activity {
...

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

SmartLib.getInstance().init(this, ...);
}

...
}

Play content screen

The sample code is generic for any players, please use one of our specific guides to get more details.

public class SomePlayerActivity extends Activity {

// Your player object
private Object mPlayer;

// SmartLib StreamingSession
private StreamingSession mSession;

// It is recommended to use a different thread to start a session
private ExecutorService mExecutor = Executors.newSingleThreadExecutor();

...

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);

// Create the player
mPlayer = PlayerFactory.newInstance();

// Registering to player error events
mPlayer.setOnErrorEvent(this);

// Create a StreamingSession object
mSession = SmartLib.getInstance().createStreamingSession();

// Attach the player to the session
mSession.attachPlayer(mPlayer);

// Start the session in a different thread, getURL can make requests to the Broadpeak CDN, nanoCDN...
mExecutor.submit(() -> {
StreamingSessionResult result = mSession.getURL(...);

if (!result.isError()) {
mPlayer.playURL(result.getURL());
} else {
mSession.stopStreamingSession();

showNoSessionCreatedMessage();
}
});
}

@Override
public void onPlayerError(PlaybackException error) {
// If the playback has been canceled because of a player error
// (i.e. non-recoverable error), stop the streaming session
if (error.playbackCanceled) {
mSession.stopStreamingSession();

showPlayerTriggeredAnErrorMessage();
}
}

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

mExecutor.submit(() -> {
// Stop the streaming session and the playback
mSession.stopStreamingSession();
if (mPlayer != null) {
mPlayer.stop();
}
});
}

...
}