gpt4 book ai didi

android - Exoplayer 2 Player 无法恢复播放

转载 作者:行者123 更新时间:2023-11-30 00:31:08 26 4
gpt4 key购买 nike

我的播放器 Activity 有问题,我无法恢复播放。这是代码。

     public class PlayerActivity extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener, ExoPlayer.EventListener {

public static boolean incomingCall;
//object of timer
private Timer mTimer_heartBeat;
//timer task
private TimerTask mTimerTask_heartBeat;
//actions in player
private String mStr_output;
//checking heart beat started
private boolean mBoolean_heartbeatStarted = false;
//exoplayer

public static SimpleExoPlayerView sExoPlayerView;
public static SimpleExoPlayer player;
private static DataSource.Factory mediaDataSourceFactory;
private static EventLogger eventLogger;
BandwidthMeter bandwidthMeter;
static Handler mainHandler;
static MediaSource[] mediaSources;

static String mediaUrl = "";
ListAdapterDrawer listAdapterDrawer;
DrawerLayout mDrawerLayout;
ListView lv_drawer_player;
NavigationView navigation_view;
SeekBar seekbar_player;
static TextView tv_start_player, tv_end_player;
RelativeLayout rl_infopanel_player;
LinearLayout ll_controlpanel_player;
Helper helper;
FrameLayout bg_black;
Handler seekHandler;
ImageView iv_arrow_player;
ProgressBar progressBar;
private final Handler mHandler = new Handler();
// Create a list to contain the PlaylistItems
// protected static List<PlaylistItem> sList_play = new ArrayList<>();
public static ArrayList<MediaList> fullChannelList = new ArrayList<MediaList>();
public static int playerPos;
private String imageLogo;
ImageView bg_image;
boolean isLiveChannel = false;
private boolean isplaying = false;
Intent intent;
public static boolean isInPlayer = false;
private boolean isresume = false;
static Bundle savedInstanceState;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.savedInstanceState = savedInstanceState;
Constants.resume = false;
intent = getIntent();
if (intent.getStringExtra("playType") != null) {
if (intent.getStringExtra("playType").equals("CHA")) {
setContentView(R.layout.drawer_player);
isLiveChannel = true;
}
} else {
isLiveChannel = false;
setContentView(R.layout.new_player_layout);
}
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
sExoPlayerView = (SimpleExoPlayerView) findViewById(R.id.playerView);
progressBar = (ProgressBar) findViewById(R.id.pb_player);
iv_arrow_player = (ImageView) findViewById(R.id.iv_arrow_player);
iv_arrow_player.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mDrawerLayout.openDrawer(Gravity.RIGHT);
}
});
bg_image = (ImageView) findViewById(R.id.bg_image);
bg_black = (FrameLayout) findViewById(R.id.bg_black);
progressBar.setVisibility(View.GONE);
permissions();

if (intent.getStringExtra("url") != null) {
mediaUrl = intent.getStringExtra("url");
Log.i("mediaUrl+-", mediaUrl);
imageLogo = intent.getStringExtra("logo");
}
helper = new Helper();
MediaController();
fullChannelList = Constants.fullChannelList;
if (intent.getStringExtra("playType") != null) {//for live channel
if (intent.getStringExtra("playType").equals("CHA")) {
if ((imageLogo != null) && (imageLogo.contains("fm"))) {
bg_black.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
bg_image.setVisibility(View.VISIBLE);
bg_black.setVisibility(View.VISIBLE);
Picasso.with(this).load(FirtTimeParsing.imageUrl + imageLogo).into(bg_image);
} else {
bg_image.setVisibility(View.GONE);
bg_black.setVisibility(View.INVISIBLE);
}
initPlayer();
drawerSetUp();
ll_controlpanel_player.setVisibility(View.GONE);
}
} else {

initPlayer();
bg_image.setVisibility(View.GONE);
bg_black.setVisibility(View.INVISIBLE);
iv_arrow_player.setVisibility(View.GONE);
}

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.setStatusBarColor(Color.TRANSPARENT);
}
}

private void permissions() {
//set run time permissions
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {
checkSelfPermission(Manifest.permission.READ_PHONE_STATE);
if (checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_PHONE_STATE)) {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, 0);
}
}
}
}

private void initPlayer() {
// sExoPlayerView.setControllerVisibilityListener((PlaybackControlView.VisibilityListener) sActivity_player);
mediaDataSourceFactory = buildDataSourceFactory(true);
mainHandler = new Handler();
bandwidthMeter = new DefaultBandwidthMeter();
TrackSelection.Factory videoTrackSelectionFactory =
new AdaptiveTrackSelection.Factory(bandwidthMeter);
MappingTrackSelector trackSelector =
new DefaultTrackSelector(videoTrackSelectionFactory);
eventLogger = new EventLogger(trackSelector);
// 2. Create a default LoadControl
LoadControl loadControl = new DefaultLoadControl();

// 3. Create the player
player = ExoPlayerFactory.newSimpleInstance(this, trackSelector, loadControl);
sExoPlayerView.setPlayer(player);
sExoPlayerView.setBackgroundColor(Color.parseColor("#000000"));

seekbar_player = (SeekBar) sExoPlayerView.findViewById(R.id.seekbar_player);
tv_end_player = (TextView) sExoPlayerView.findViewById(R.id.tv_end_player);
tv_start_player = (TextView) sExoPlayerView.findViewById(R.id.tv_start_player);
rl_infopanel_player = (RelativeLayout) sExoPlayerView.findViewById(R.id.rl_infopanel_player);
ll_controlpanel_player = (LinearLayout) sExoPlayerView.findViewById(R.id.ll_controlpanel_player);
seekbar_player.setOnSeekBarChangeListener(this);
player.addListener(this);
loadPlayer();
}

private DataSource.Factory buildDataSourceFactory(boolean useBandwidthMeter) {
return ((BaseApplication) getApplication())
.buildDataSourceFactory(useBandwidthMeter ? (DefaultBandwidthMeter) bandwidthMeter : null);
}

private void loadPlayer() {
if (!isInPlayer) {
isInPlayer = true;
sExoPlayerView.setVisibility(View.VISIBLE);
mediaSources = new MediaSource[1];
Uri myUri = Uri.parse(mediaUrl);
mediaSources[0] = new HlsMediaSource(myUri, mediaDataSourceFactory, mainHandler, eventLogger);
MediaSource mediaSource = mediaSources.length == 1 ? mediaSources[0]
: new ConcatenatingMediaSource(mediaSources);

boolean haveResumePosition = false;
player.prepare(mediaSource, !haveResumePosition, false);
sExoPlayerView.setPlayer(player);

player.setPlayWhenReady(true);
if (!isLiveChannel) {
player.seekTo((long) Constants.seekto);
updateProgressBar();
}

Log.d("Time==", "play time " + new Date());
}
}

private void drawerSetUp() {
listAdapterDrawer = new ListAdapterDrawer(this, fullChannelList);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer);
lv_drawer_player = (ListView) findViewById(R.id.lv_drawer_player);
navigation_view = (NavigationView) mDrawerLayout.findViewById(R.id.navigation_view);
lv_drawer_player.setAdapter(listAdapterDrawer);
lv_drawer_player.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (!mediaUrl.equals(fullChannelList.get(position).getMediaUrl())) {

playclick(position);
mDrawerLayout.closeDrawer(Gravity.END);
} else {
mDrawerLayout.closeDrawer(Gravity.END);
}
}
});
}

public void playclick(int position) {
isInPlayer = false;
mediaUrl = fullChannelList.get(position).getMediaUrl();
imageLogo = fullChannelList.get(position).getLogo();
playerPos = position;
player.stop();
player.clearVideoSurface();
initPlayer();
}

private Runnable mUpdateTimeTask = new Runnable() {
public void run() {

long totalDuration = 0;

//sometime -ve value getting
if (player.getDuration() > 0) {
totalDuration = player.getDuration();
}
long currentDuration = player.getCurrentPosition();

// Displaying Total Duration time
// Log.d("mUpdateTimeTask==", "totalDuration " + totalDuration);
tv_end_player.setText("" + helper.milliSecondsToTimer(totalDuration));
// Displaying time completed playing
tv_start_player.setText("" + helper.milliSecondsToTimer(currentDuration));

// Updating progress bar
int progress = (int) (helper.getProgressPercentage(currentDuration, totalDuration));
//Log.d("Progress", ""+progress);
seekbar_player.setProgress(progress);
sExoPlayerView.setControllerShowTimeoutMs(5000);
sExoPlayerView.showController();
// Running this thread after 100 milliseconds
mHandler.postDelayed(this, 100);
}
};

public void updateProgressBar() {
seekHandler = new Handler();
seekHandler.postDelayed(mUpdateTimeTask, 100);
}


@Override
public void onConfigurationChanged(Configuration newConfig) {
// Set fullscreen when the device is rotated to landscape
//satatus bar color setting
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.setStatusBarColor(Color.TRANSPARENT);
}
bg_black.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
// sJwPlayerView.setFullscreen(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE, true);
super.onConfigurationChanged(newConfig);
}

@Override
protected void onResume() {
//satatus bar color setting
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.setStatusBarColor(Color.TRANSPARENT);
}
// Let JW Player know that the app has returned from the background JWPlayerView.onResume();
// sJwPlayerView.onResume();

// InitialDataFromServer login = new InitialDataFromServer(PlayerActivity.this);
// Constants.playerPosition = 0;
// login.PlayRequest(Constants.mediaId, Constants.start_play);
// loadPlayer();
// isInPlayer = false;


super.onResume();

}

@Override
protected void onPause() {
isresume = true;
// Let JW Player know that the app is going to the background JWPlayerView.onPause();
if (Constants.isPlaying) {
// sJwPlayerView.stop();
Constants.isPlaying = false;
Constants.playerPosition = player.getCurrentPosition();
isplaying = false;
player.stop();
player.release();
}


// stopPlayer();
super.onPause();
}

@Override
protected void onStop() {
try {
player.stop();
player.release();
// stopPlayer();
super.onStop();
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}

@Override
public void onBackPressed() {
stopPlayer();
super.onBackPressed();
if (isdirect) {
InitialDataFromServer initialDataFromServer = new InitialDataFromServer(PlayerActivity.this);
initialDataFromServer.login();
}
}


@Override
public void onDestroy() {
// stopPlayer();
Constants.isPlayPressed = false;
player.stop();
player.release();
super.onDestroy();

}

@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

}

@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// remove message Handler from updating progress bar
seekHandler.removeCallbacks(mUpdateTimeTask);
}

@Override
public void onStopTrackingTouch(SeekBar seekBar) {
mHandler.removeCallbacks(mUpdateTimeTask);
long totalDuration = player.getDuration();
int currentPosition = helper.progressToTimer(seekBar.getProgress(), totalDuration);
Log.d("onStopTrackingTouch==", "currentPosition " + currentPosition);
// forward or backward to certain seconds
player.seekTo(currentPosition);

// update timer progress again
updateProgressBar();
}

@Override
public void onTimelineChanged(Timeline timeline, Object manifest) {

}

@Override
public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {

}

@Override
public void onLoadingChanged(boolean isLoading) {

}

@Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
if (playbackState == ExoPlayer.STATE_ENDED) {//for close this activity after finish movie
Log.d("onPlayerStateChanged==", "STATE_ENDED==");
Constants.playerPosition = 0;
InitialDataFromServer initialDataFromServer = new InitialDataFromServer(PlayerActivity.this);
initialDataFromServer.PlayRequest(Constants.mediaId, Constants.stop_play);
isplaying = false;
sExoPlayerView.hideController();
progressBar.setVisibility(View.GONE);
}
if (playbackState == ExoPlayer.STATE_BUFFERING) {
Log.d("onPlayerStateChanged==", "STATE_BUFFERING==");
progressBar.setVisibility(View.VISIBLE);
isplaying = false;
sExoPlayerView.setControllerShowTimeoutMs(5000);
sExoPlayerView.showController();
}
if (playbackState == ExoPlayer.STATE_READY) {
Log.d("onPlayerStateChanged==", "STATE_READY==");
progressBar.setVisibility(View.GONE);
isplaying = true;
if ((imageLogo != null) && (imageLogo.contains("fm"))) {
bg_black.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
bg_image.setVisibility(View.VISIBLE);
bg_black.setVisibility(View.VISIBLE);
Picasso.with(this).load(FirtTimeParsing.imageUrl + imageLogo).into(bg_image);
} else {
bg_image.setVisibility(View.GONE);
bg_black.setVisibility(View.GONE);
}
sExoPlayerView.setControllerShowTimeoutMs(5000);
sExoPlayerView.showController();
Log.i("Video_format++", String.valueOf(player.getRendererType(1)));
if (!isLiveChannel) {
setController();
heartbeat();
}
}
}

private void setController() {
sExoPlayerView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
sExoPlayerView.setControllerShowTimeoutMs(3000);
sExoPlayerView.showController();
ll_controlpanel_player.setVisibility(View.VISIBLE);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
ll_controlpanel_player.setVisibility(View.GONE);
}
}, 3000);
}
return true;
}
});
}

private void stopPlayer() {

if (player.isLoading() || isplaying) {
isplaying = false;
player.stop();
player.release();
Constants.playerPosition = player.getCurrentPosition();
Log.i("currentPosition", Constants.playerPosition + "");
if (!isLiveChannel) {
InitialDataFromServer initialDataFromServer = new InitialDataFromServer(PlayerActivity.this);
initialDataFromServer.PlayRequest(Constants.mediaId, Constants.stop_play);
if (isdirect) {
initialDataFromServer.login();
} else {
finish();
}
} else {
finish();
}
}
Constants.isPlayPressed = false;
isInPlayer = false;
if (mBoolean_heartbeatStarted) {
mTimer_heartBeat.cancel();
mTimerTask_heartBeat.cancel();
}

}

@Override
public void onPlayerError(com.google.android.exoplayer2.ExoPlaybackException error) {

}

@Override
public void onPositionDiscontinuity() {

}

String motion;
Float x1 = Float.valueOf(0), x2 = Float.valueOf(0), y1 = Float.valueOf(0), y2 = Float.valueOf(0), motionX = Float.valueOf(0), motionY = Float.valueOf(0);
String xdirection = "", ydirection = "", operation = null;
int mScrenHeight, mScreenWidth;

public void MediaController() {
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
// heartbeat();
mScrenHeight = displayMetrics.heightPixels;
mScreenWidth = displayMetrics.widthPixels;
Log.i("Display++", "Width: " + mScreenWidth + "\nHeight: " + mScrenHeight);
sExoPlayerView.setOnTouchListener(new View.OnTouchListener()

{
@Override
public boolean onTouch(View v, MotionEvent event) {
// Log.i("event++", event.toString());

switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
x1 = event.getX();
y1 = event.getY();
break;
case MotionEvent.ACTION_UP:
x2 = event.getX();
y2 = event.getY();
if ((x2 - x1) > 0) {
motionX = x2 - x1;
xdirection = "+";
} else {
motionX = x1 - x2;
xdirection = "-";
}
if ((y2 - y1) > 0) {
motionY = y2 - y1;
ydirection = "-";
} else {
motionY = y1 - y2;
ydirection = "+";
}
if (motionX < motionY) {
motion = "vertical";
if (x1 > (mScreenWidth / 2)) {
operation = "volumeControll";
} else {
operation = "brightnessControll";
}
xdirection = "";
} else {
operation = "playbackControll";
motion = "horizontal";
ydirection = "";
}
Log.i("drag++", operation + xdirection + ydirection);
if (operation.equalsIgnoreCase("volumeControll")) {

if (motionY > mScreenWidth / 5) {
if (ydirection.equalsIgnoreCase("+")) {
if (player.getVolume() < 1) {
player.setVolume((float) (player.getVolume() + 0.1));
}

} else {
if (player.getVolume() > 0) {
player.setVolume((float) (player.getVolume() - 0.1));
}
}
Log.i("drag++", "volume:" + player.getVolume());
}
} else if (operation.equalsIgnoreCase("brightnessControll")) {
if (motionY > mScrenHeight / 5) {
WindowManager.LayoutParams lp = getWindow().getAttributes();
Float brightness = lp.screenBrightness;
Log.i("drag++", "Brightness:" + getWindow().getAttributes().screenBrightness);
if (ydirection.equalsIgnoreCase("+")) {
if (lp.screenBrightness < 255) {
lp.screenBrightness = brightness + 15;
getWindow().setAttributes(lp);
}

} else {
if (lp.screenBrightness > 0) {
lp.screenBrightness = brightness - 15;
getWindow().setAttributes(lp);
}
}
}

} else if (operation.equalsIgnoreCase("playbackControll")) {

if (motionX > mScreenWidth / 10) {
if (xdirection.equalsIgnoreCase("+")) {

if (isLiveChannel) {
if (0 < playerPos) {
playclick(playerPos - 1);
} else {
playclick(fullChannelList.size() - 1);
}
} else {
if (player.getCurrentPosition() < (player.getDuration() - 10000)) {
player.seekTo(player.getCurrentPosition() + 10000);
} else {
player.seekTo(player.getDuration() - 1000);
}
}


} else {
if (isLiveChannel) {
if (playerPos < fullChannelList.size() - 1) {
playclick(playerPos + 1);
} else {
playclick(0);
}

} else {
if (player.getCurrentPosition() > 10000) {
player.seekTo(player.getCurrentPosition() - 10000);
} else {
player.seekTo(100);
}
}

}
}

}
break;
}

return true;
}
});
}

public void heartbeat() {
int delay = 30; // delay for 0.03 sec.
int period = 10000; // repeat every 10 sec.
mTimer_heartBeat = new Timer();
mTimerTask_heartBeat = new TimerTask() {
@Override
public void run() {
mBoolean_heartbeatStarted = true;
Log.d("heartbeat==", "heartbeat");
Constants.playerPosition = player.getCurrentPosition();
if (isplaying) {
InitialDataFromServer login = new InitialDataFromServer(PlayerActivity.this);
login.PlayRequest(Constants.mediaId, Constants.heartbeat);

}
}
};
mTimer_heartBeat.schedule(mTimerTask_heartBeat, delay, period); // 10000 is time in ms
}


}

播放器工作正常。但是当设备锁定和 Activity 恢复时,播放器没有恢复播放。请帮我解决这个问题。提前致谢。

最佳答案

尝试使用以下代码更改简历

@Override
protected void onResume() {
//satatus bar color setting
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.setStatusBarColor(Color.TRANSPARENT);
}
if (isresume) {
isresume=false;
player.stop();
player.clearVideoSurface();
isInPlayer = false;
seekto = Constants.playerPosition;
initPlayer();
loadPlayer();

} else {
loadPlayer();
}
super.onResume();

}

关于android - Exoplayer 2 Player 无法恢复播放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44322258/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com