我正在努力寻找一种方法来创建一个线程来监控Exoplayer应用中的playbackPosition。
在下面的代码中,我需要一个简单的任务,就是在每1000ms后通过覆盖 onIsPlayingChanged 函数。但我理解这种情况只发生一次,如果应用程序状态发生变化,然而,为了使这种情况持续发生,我认为我应该创建一个线程。请告诉我如何才能实现这一点。如你所见,注释的代码是我试过的,但肯定不对。
private class PlaybackStateListener implements Player.EventListener{
@Override
public void onIsPlayingChanged(boolean isPlaying) {
//TODO: Add handler to poll the playback position continuously.
/* if(isPlaying){
HandlerCompat.
postDelayed(new Runnable() {
@Override
public void run() {
long positionParam = playbackPosition;
}
});
}*/
if (isPlaying) {
Log.d(TAG, "Playing position is " + playbackPosition);
} else {
// Not playing because playback is paused, ended, suppressed, or the player
// is buffering, stopped or failed. Check player.getPlaybackState,
// player.getPlayWhenReady, player.getPlaybackError and
// player.getPlaybackSuppressionReason for details.
}
}
下面这段代码可以用来解决这样的问题,使用处理程序postDelayed方法。
final Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//My code
}
handler.postDelayed(new Runnable() {
@Override
public void run() {
playbackPosition = player.getCurrentPosition();
send(playbackPosition); //Function to update position
handler.postDelayed(this, 1000); //1000ms frequency of updates.
}
}, 1000);
}