androidgoogle-castcastcompanionlibrary

Get media current position before disconnecting from cast


Is it possible to get current playing media from VideoCastManager before disconnecting from the cast?

I want to save the last progress of current media when the user manually disconnects from cast. I used VideoCastCosumer method onDisconnected() but it throws an exception. Not sure what kind of exception because my log only shows this:

System.err: at com.economist.newton.mobile.ui.activity.BaseCastActivity$1.onDisconnected (MyCastActivity.java:81)

This line contains the following line inside the onDisconnected() method:

try {
      if(castManager.getCurrentMediaPosition() > 30000){ //  <-here error occurs
              ...
      }
} catch (TransientNetworkDisconnectionException | NoConnectionException e) {
      e.printStackTrace();
}

If it any help, castManager variable is declared in onCreate():

castManager = VideoCastManager.getInstance();

Cast companion library: com.google.android.libraries.cast.companionlibrary:ccl:2.8.4


Solution

  • There are a couple of ways to do that. The one that I think would be the easiest is to have a component that implements ProgressWatcher (from CCL). In that listener, setProgress(int currentPosition, int duration) will be called every second and it will have the currentPosition of the stream as its first argument. You can cache this value (it won't be updated if your device gets disconnected) so that will provide you with a real-time information on the current position. So for example, if your activity implements this interface:

    public MyActivity extends AppCompatActivity implements ProgressWatcher {
       private int mCurrentStreamPosition;
    
       public onStart() {
           ....
           mCastManager.addProgressWatcher(this);
           ....
       }
    
       public onStop() {
           ....
           mCastManager.removeProgressWatcher(this);
           ....
       }
    
       public setProgress(int currentTime, int duration) {
           mCurrentStreamPosition = currentTime;
       }
    
       public int getCurrentStreamPosition() {
           return mCurrentStreamPosition;
       }
       ....
    }
    

    so whenever you want, you can then call getCurrentStreamPosition() (for example, you can call it in onDisconnected()) to get the last/current stream position. Note that depending on the structure of your app, you may decide to register/unregister your ProgressWatcher in onResume()/onPause() or onCreate()/onDestroy(). The important things is to make sure you unregister it to avoid leaking memory.