I code a simple music player. all works fine but when I click next button the max value of seekbar becomes the previous track's duration.though Player is working fine and music is being streamed fine but I am having trouble in setting the seekbar to work. I am assuming that seekbar is directly related to getting correct duration through getDuration. how can I solve this?
Here is my code:
public class PlayerActivity extends AppCompatActivity {
AppCompatButton playbtn, pausebtn, nxtbtn, prevbtn, fastfrwrdbtn, rewindbtn;
TextView txtStrt, txtStop, txtSnName;
SeekBar musicSeek;
BarVisualizer barVisualizer;
String sname;
static MediaPlayer mediaPlayer;
int position;
ArrayList mySongs, mySongUri, mySongAlbumArtUri;
ImageView imageView;
Thread updateSeek;
String currentTime;
AudioManager mAudioManager;
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onDestroy() {
if (barVisualizer != null) {
barVisualizer.release();
}
super.onDestroy();
}
int ii = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
getSupportActionBar().setTitle("Now Playing");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
playbtn = findViewById(R.id.playBtn);
nxtbtn = findViewById(R.id.nxtBtn);
prevbtn = findViewById(R.id.previousBtn);
fastfrwrdbtn = findViewById(R.id.forwardBtn);
rewindbtn = findViewById(R.id.rewaindBtn);
mAudioManager = null;
txtStrt = findViewById(R.id.txtstart);
txtStop = findViewById(R.id.txtend);
txtSnName = findViewById(R.id.txtsn);
musicSeek = findViewById(R.id.seekbar);
barVisualizer = findViewById(R.id.blast);
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
}
Intent i = getIntent();
Bundle bundle = i.getExtras();
mySongs = (ArrayList) bundle.getParcelableArrayList("songs");
mySongUri = (ArrayList) bundle.getParcelableArrayList("uri");
mySongAlbumArtUri = (ArrayList) bundle.getParcelableArrayList("uriArt");
String songName = i.getStringExtra("songName");
position = bundle.getInt("position", 0);
txtSnName.setSelected(true);
Uri uri = Uri.parse(mySongUri.get(position).toString());
getSupportActionBar().setTitle(songName);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
sname = mySongs.get(position).toString();
txtSnName.setText(sname);
imageView = findViewById(R.id.imageView);
//imageView.setImageURI(uriart);
mediaPlayer = MediaPlayer.create(getApplicationContext(), uri);
mediaPlayer.start();
String endTime = creatTime(mediaPlayer.getDuration());
txtStop.setText(endTime);
int audioSessionId = mediaPlayer.getAudioSessionId();
if (audioSessionId != -1) {
barVisualizer.setAudioSessionId(audioSessionId);
}
threading();
final Handler handler = new Handler();
final int delay = 1000;
handler.postDelayed(new Runnable() {
#Override
public void run() {
String currentTime = creatTime(mediaPlayer.getCurrentPosition());
txtStrt.setText(currentTime);
handler.postDelayed(this, delay);
}
}, delay);
setUpdateSeek();
nxt();
prev();
playbtn.setOnClickListener(v -> {
if (mediaPlayer.isPlaying()) {
playbtn.setBackgroundResource(R.drawable.ic_play_button);
mediaPlayer.pause();
} else {
playbtn.setBackgroundResource(R.drawable.ic_pause);
mediaPlayer.start();
}
});
fastfrwrdbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.seekTo(mediaPlayer.getCurrentPosition() + 10000);
}
}
});
rewindbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.seekTo(mediaPlayer.getCurrentPosition() - 10000);
}
}
});
countinue();
}
public void startAnimation(View view) {
ObjectAnimator animator = ObjectAnimator.ofFloat(imageView, "rotation", 0f, 360);
animator.setDuration(1000);
AnimatorSet animationSet = new AnimatorSet();
animationSet.playTogether(animator);
animationSet.start();
}
public void startAnimationBack(View view) {
ObjectAnimator animator = ObjectAnimator.ofFloat(imageView, "rotation", 360, 0f);
animator.setDuration(1000);
AnimatorSet animationSet = new AnimatorSet();
animationSet.playTogether(animator);
animationSet.start();
}
public String creatTime(int duration) {
String time = "";
int min = duration / 1000 / 60;
int sec = duration / 1000 % 60;
time += min + ":";
if (sec < 10) {
time += "0";
}
time += sec;
return time;
}
public void setUpdateSeek() {
updateSeek.start();
musicSeek.setMax(mediaPlayer.getDuration());
musicSeek.getProgressDrawable().setColorFilter(getResources().getColor(R.color.black), PorterDuff.Mode.MULTIPLY);
musicSeek.getThumb().setColorFilter(getResources().getColor(R.color.black), PorterDuff.Mode.SRC_IN);
musicSeek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser){
mediaPlayer.seekTo(position);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mediaPlayer.seekTo(seekBar.getProgress());
seekBar.setMax(mediaPlayer.getDuration());
}
});
}
#Override
public void onBackPressed() {
startActivity(new Intent(getApplicationContext(), MainActivity.class));
finish();
}
public void countinue() {
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
nxtbtn.performClick();
//musicSeek.setMax(mediaPlayer.getDuration());
}
});
}
public void nxt() {
nxtbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.stop();
mediaPlayer.release();
position = ((position + 1) % mySongs.size());
Uri u = Uri.parse(mySongUri.get(position).toString());
mediaPlayer = MediaPlayer.create(getApplicationContext(), u);
sname = mySongs.get(position).toString();
txtSnName.setText(sname);
String endTime1 = creatTime(mediaPlayer.getDuration());
txtStop.setText(endTime1);
playbtn.setBackgroundResource(R.drawable.ic_pause);
startAnimation(imageView);
int audioSessionId = mediaPlayer.getAudioSessionId();
if (audioSessionId != -1) {
barVisualizer.setAudioSessionId(audioSessionId);
}
musicSeek.setMax(mediaPlayer.getDuration());
mediaPlayer.start();
countinue();
}
});
}
public void prev() {
prevbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.stop();
mediaPlayer.release();
position = ((position + 1) < 0) ? (mySongs.size() - 1) : (position - 1);
Uri u = Uri.parse(mySongUri.get(position).toString());
mediaPlayer = MediaPlayer.create(getApplicationContext(), u);
int i = mediaPlayer.getDuration();
String c = Integer.toString(i);
Toast.makeText(PlayerActivity.this, c, Toast.LENGTH_SHORT).show();
musicSeek.setMax(i);
sname = mySongs.get(position).toString();
txtSnName.setText(sname);
String endTime12 = creatTime(mediaPlayer.getDuration());
txtStop.setText(endTime12);
playbtn.setBackgroundResource(R.drawable.ic_pause);
startAnimationBack(imageView);
int audioSessionId = mediaPlayer.getAudioSessionId();
if (audioSessionId != -1) {
barVisualizer.setAudioSessionId(audioSessionId);
}
musicSeek.setMax(mediaPlayer.getDuration());
mediaPlayer.start();
countinue();
}
});
}
public void threading() {
updateSeek = new Thread() {
#Override
public void run() {
int totalDuration = mediaPlayer.getDuration();
int currentPosition = 0;
while (currentPosition < totalDuration) {
try {
sleep(500);
currentPosition = mediaPlayer.getCurrentPosition();
musicSeek.setProgress(currentPosition);
} catch (InterruptedException | IllegalStateException e) {
e.printStackTrace();
}
}
}
};
}
}
can anyone please guide me to solve the issue?
Related
public class SongPlayerActivity extends AppCompatActivity implements MediaPlayer.OnCompletionListener {
static MediaPlayer mediaPlayer;
TextView songName, artistName, albumName, durationPlayed, totalDuration;
ImageView next, previous, songImage, shuffle, repeat;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
SeekBar seekBar;
FloatingActionButton floatingActionButton;
List<Song> songList = new ArrayList<>();
Handler handler = new Handler();
Thread playPauseThread, nextThread, previousThread;
private Uri uri;
private int position;
boolean shuffleBoolean, repeatBoolean;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_song_player);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
songList = getIntent().getParcelableArrayListExtra("songsList");
position = getIntent().getIntExtra("position", 0);
songImage = findViewById(R.id.album_cover);
songName = findViewById(R.id.music_name);
albumName = findViewById(R.id.album_name);
artistName = findViewById(R.id.artist_name);
seekBar = findViewById(R.id.seek_bar);
durationPlayed = findViewById(R.id.played_duration);
totalDuration = findViewById(R.id.music_duration);
repeat = findViewById(R.id.repeat);
shuffle = findViewById(R.id.shuffle);
floatingActionButton = findViewById(R.id.play_pause);
next = findViewById(R.id.next);
previous = findViewById(R.id.previous);
playMusic();
mediaPlayer.setOnCompletionListener(this);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (mediaPlayer != null && fromUser) {
mediaPlayer.seekTo(progress * 1000);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
SongPlayerActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
if (mediaPlayer != null) {
int currentPosition = mediaPlayer.getCurrentPosition() / 1000;
seekBar.setProgress(currentPosition);
durationPlayed.setText(durationConversion(currentPosition));
}
handler.postDelayed(this, 200);
}
});
if (sharedPreferences.getBoolean("playerShuffle", false)) {
shuffle.setImageResource(R.drawable.ic_baseline_shuffle_24);
shuffleBoolean = true;
}
else {
shuffle.setImageResource(R.drawable.ic_baseline_shuffle_off_24);
shuffleBoolean = false;
}
if (sharedPreferences.getBoolean("playerRepeat", false)) {
repeat.setImageResource(R.drawable.ic_baseline_repeat_24);
repeatBoolean = true;
}
else {
repeat.setImageResource(R.drawable.ic_baseline_repeat_24_off);
repeatBoolean = false;
}
shuffle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (sharedPreferences.getBoolean("playerShuffle", false)) {
editor = sharedPreferences.edit();
editor.putBoolean("playerShuffle", false);
editor.commit();
shuffleBoolean = false;
shuffle.setImageResource(R.drawable.ic_baseline_shuffle_off_24);
Toast.makeText(getApplicationContext(), R.string.shuffle_off, Toast.LENGTH_SHORT).show();
} else {
editor = sharedPreferences.edit();
editor.putBoolean("playerShuffle", true);
editor.commit();
shuffleBoolean = true;
shuffle.setImageResource(R.drawable.ic_baseline_shuffle_24);
Toast.makeText(getApplicationContext(), R.string.shuffle_on, Toast.LENGTH_SHORT).show();
}
}
});
repeat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (sharedPreferences.getBoolean("playerRepeat", false)) {
editor = sharedPreferences.edit();
editor.putBoolean("playerRepeat", false);
editor.commit();
repeatBoolean = false;
repeat.setImageResource(R.drawable.ic_baseline_repeat_24_off);
Toast.makeText(getApplicationContext(), R.string.repeat_off, Toast.LENGTH_LONG).show();
} else {
editor = sharedPreferences.edit();
editor.putBoolean("playerRepeat", true);
editor.commit();
repeatBoolean = true;
repeat.setImageResource(R.drawable.ic_baseline_repeat_24);
Toast.makeText(getApplicationContext(), R.string.repeat_on, Toast.LENGTH_LONG).show();
}
}
});
}
public String durationConversion(int songDuration) {
long s = songDuration % 60;
long m = (songDuration / 60) % 60;
long h = (songDuration / (60 * 60)) % 24;
return String.format("%02d:%02d:%02d", h, m, s);
}
void playPauseButton() {
playPauseThread = new Thread() {
#Override
public void run() {
super.run();
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
floatingActionButton.setImageResource(R.drawable.ic_baseline_play_arrow_24);
seekBar.setMax(mediaPlayer.getDuration() / 1000);
SongPlayerActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
if (mediaPlayer != null) {
int currentPosition = mediaPlayer.getCurrentPosition() / 1000;
seekBar.setProgress(currentPosition);
}
handler.postDelayed(this, 200);
}
});
} else {
mediaPlayer.start();
floatingActionButton.setImageResource(R.drawable.ic_baseline_pause_24);
seekBar.setMax(mediaPlayer.getDuration() / 1000);
SongPlayerActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
if (mediaPlayer != null) {
int currentPosition = mediaPlayer.getCurrentPosition() / 1000;
seekBar.setProgress(currentPosition);
}
handler.postDelayed(this, 200);
}
});
}
}
});
mediaPlayer.setOnCompletionListener(SongPlayerActivity.this);
}
};
playPauseThread.start();
}
private void nextButton() {
nextThread = new Thread() {
#Override
public void run() {
super.run();
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.release();
if(shuffleBoolean && !repeatBoolean)
position = random(songList.size()-1);
else if (!shuffleBoolean && !repeatBoolean)
position++;
if (position == songList.size())
position = 0;
mediaPlayer = MediaPlayer.create(getApplicationContext(), Uri.parse(songList.get(position).path));
metaDataRetriever(Uri.parse(songList.get(position).path));
seekBar.setMax(mediaPlayer.getDuration() / 1000);
SongPlayerActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
if (mediaPlayer != null) {
int currentPosition = mediaPlayer.getCurrentPosition() / 1000;
seekBar.setProgress(currentPosition);
}
handler.postDelayed(this, 200);
}
});
floatingActionButton.setImageResource(R.drawable.ic_baseline_pause_24);
mediaPlayer.setOnCompletionListener(SongPlayerActivity.this);
} else {
mediaPlayer.stop();
mediaPlayer.release();
if(shuffleBoolean && !repeatBoolean)
position = random(songList.size()-1);
else if (!shuffleBoolean && !repeatBoolean)
position++;
if (position == songList.size())
position = 0;
mediaPlayer = MediaPlayer.create(getApplicationContext(), Uri.parse(songList.get(position).path));
metaDataRetriever(Uri.parse(songList.get(position).path));
seekBar.setMax(mediaPlayer.getDuration() / 1000);
SongPlayerActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
if (mediaPlayer != null) {
int currentPosition = mediaPlayer.getCurrentPosition() / 1000;
seekBar.setProgress(currentPosition);
}
handler.postDelayed(this, 200);
}
});
floatingActionButton.setImageResource(R.drawable.ic_baseline_pause_24);
mediaPlayer.setOnCompletionListener(SongPlayerActivity.this);
}
mediaPlayer.start();
}
});
}
};
nextThread.start();
}
private void previousButton() {
previousThread = new Thread() {
#Override
public void run() {
super.run();
previous.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.release();
if(shuffleBoolean && !repeatBoolean)
position = random(songList.size()-1);
else if (!shuffleBoolean && !repeatBoolean)
position--;
if (position < 0)
position = 0;
mediaPlayer = MediaPlayer.create(getApplicationContext(), Uri.parse(songList.get(position).path));
metaDataRetriever(Uri.parse(songList.get(position).path));
seekBar.setMax(mediaPlayer.getDuration() / 1000);
SongPlayerActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
if (mediaPlayer != null) {
int currentPosition = mediaPlayer.getCurrentPosition() / 1000;
seekBar.setProgress(currentPosition);
}
handler.postDelayed(this, 200);
}
});
mediaPlayer.setOnCompletionListener(SongPlayerActivity.this);
floatingActionButton.setImageResource(R.drawable.ic_baseline_pause_24);
} else {
mediaPlayer.stop();
mediaPlayer.release();
if(shuffleBoolean && !repeatBoolean)
position = random(songList.size()-1);
else if (!shuffleBoolean && !repeatBoolean)
position--;
if (position < 0)
position = 0;
mediaPlayer = MediaPlayer.create(getApplicationContext(), Uri.parse(songList.get(position).path));
metaDataRetriever(Uri.parse(songList.get(position).path));
seekBar.setMax(mediaPlayer.getDuration() / 1000);
SongPlayerActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
if (mediaPlayer != null) {
int currentPosition = mediaPlayer.getCurrentPosition() / 1000;
seekBar.setProgress(currentPosition);
}
handler.postDelayed(this, 200);
}
});
mediaPlayer.setOnCompletionListener(SongPlayerActivity.this);
floatingActionButton.setImageResource(R.drawable.ic_baseline_pause_24);
}
mediaPlayer.start();
}
});
}
};
previousThread.start();
}
private int random(int i) {
Random random = new Random();
return random.nextInt(i+1);
}
public void metaDataRetriever(Uri uri) {
MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
mediaMetadataRetriever.setDataSource(uri.getPath());
byte[] bytes = mediaMetadataRetriever.getEmbeddedPicture();
final LinearLayout linearLayout = findViewById(R.id.linear_layout);
Bitmap bitmap;
if (bytes != null) {
bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
layoutAnimation(getApplicationContext(), songImage, bitmap);
Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {
#Override
public void onGenerated(#Nullable Palette palette) {
Palette.Swatch swatch = Objects.requireNonNull(palette).getDominantSwatch();
if (swatch != null) {
GradientDrawable gradientDrawable = new GradientDrawable(GradientDrawable.Orientation.BOTTOM_TOP, new int[]{0xff000000, swatch.getRgb()});
linearLayout.setBackground(gradientDrawable);
songName.setTextColor(swatch.getTitleTextColor());
albumName.setTextColor(swatch.getTitleTextColor());
artistName.setTextColor(swatch.getTitleTextColor());
durationPlayed.setTextColor(Color.WHITE);
totalDuration.setTextColor(Color.WHITE);
floatingActionButton.setImageResource(R.drawable.ic_baseline_pause_24);
floatingActionButton.getBackground().setTint(Color.WHITE);
next.setImageResource(R.drawable.ic_baseline_skip_next_white_24);
previous.setImageResource(R.drawable.ic_baseline_skip_previous_white_24);
seekBar.getThumb().setTint(Color.WHITE);
}
}
});
} else {
layoutAnimation(getApplicationContext(), songImage, null);
linearLayout.setBackgroundResource(R.drawable.gradient_brown);
songName.setTextColor(Color.DKGRAY);
albumName.setTextColor(Color.DKGRAY);
artistName.setTextColor(Color.DKGRAY);
floatingActionButton.setImageResource(R.drawable.ic_baseline_pause_24);
next.setImageResource(R.drawable.ic_baseline_skip_next_24);
previous.setImageResource(R.drawable.ic_baseline_skip_previous_24);
seekBar.getThumb().setTint(getResources().getColor(R.color.colorYellow));
durationPlayed.setTextColor(getResources().getColor(R.color.colorYellow));
totalDuration.setTextColor(getResources().getColor(R.color.colorYellow));
}
songName.setText(songList.get(position).songName);
albumName.setText(songList.get(position).albumName);
artistName.setText(songList.get(position).artistName);
totalDuration.setText(Song.durationConversion(songList.get(position).songDuration));
}
public void playMusic() {
if (songList != null) {
floatingActionButton.setImageResource(R.drawable.ic_baseline_pause_24);
uri = Uri.parse(songList.get(position).path);
}
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
}
mediaPlayer = MediaPlayer.create(getApplicationContext(), uri);
mediaPlayer.start();
metaDataRetriever(uri);
seekBar.setMax(mediaPlayer.getDuration() / 1000);
}
public void layoutAnimation(final Context context, final ImageView imageView, final Bitmap bitmap) {
final Animation animationIn = AnimationUtils.loadAnimation(context, android.R.anim.fade_in);
Animation animationOut = AnimationUtils.loadAnimation(context, android.R.anim.fade_out);
if (bitmap != null)
animationOut.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
Glide.with(context).load(bitmap).into(imageView);
animationIn.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
imageView.startAnimation(animationIn);
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
else
animationOut.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
Glide.with(context).load(R.drawable.album_cover).into(imageView);
animationIn.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
imageView.startAnimation(animationIn);
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
imageView.startAnimation(animationOut);
}
#Override
protected void onResume() {
super.onResume();
playPauseButton();
nextButton();
previousButton();
}
#Override
public void onCompletion(MediaPlayer mp) {
nextButton();
position++;
if(position >= songList.size())
position = 0;
if (mediaPlayer != null) {
mediaPlayer = MediaPlayer.create(getApplicationContext(), Uri.parse(songList.get(position).path));
seekBar.setMax(mediaPlayer.getDuration() / 1000);
metaDataRetriever(Uri.parse(songList.get(position).path));
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(this);
}
}
}
I have two problems here:
is that when the current playing music finish onCompletionListener() called which is call nextButton()
which checks if shuffleBoolean and repeatBoolean states are true or not, the problem here is that when shuffleBoolean and repeatBoolean are true the SongList keeps playing serially Regardless of shuffleBoolean and repeatBoolean states, but if i pressed next or previous buttons it checks for repeatBoolean and shuffleBoolean states and play next song correctly according to the states.
sometimes when i move seekBar to any position (seconds) in the bar, the songlist stops playing at the end of current playing song
my description maybe too long for the first problem but i meant to be clear and thanks in advance.
The solution is to call next.performClick() in onCompltition() and remove all the other lines.
I don't know the reason that the firs way don't work but i thought of it as i need to call onClickListener() without clicking the button.
I made simple picture matching game with four Activities After finishing you can play again.
The problem is most of the time the game stops and return to previous
The error:
2020-01-29 15:05:51.001 11438-11438/? E/AndroidRuntime: FATAL
EXCEPTION: main
Process: com.mk_kadish.playandlearn, PID: 11438
android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy#4f4586f is not valid; is your activity running?
at android.view.ViewRootImpl.setView(ViewRootImpl.java:798)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:356)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:93)
at android.app.Dialog.show(Dialog.java:329)
at androidx.appcompat.app.AlertDialog$Builder.show(AlertDialog.java:1007)
at com.mk_kadish.playandlearn.game1.game1_HomeActivity$4.onFinish(game1_HomeActivity.java:284)
at android.os.CountDownTimer$1.handleMessage(CountDownTimer.java:127)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
The Code of one of the files and the other repeats the same:
public class game1_HomeActivity extends AppCompatActivity {
private AllSharedPrefernces allSharedPrefernces;
View view1;
int position1;
private int height;
private int width;
private static final long START_TIME_IN_MILLIS = 120000;
private TextView mTextViewCountDown;
private TextView textViewPairs;
private Button mButtonStartPause;
private Button mButtonReset;
private CountDownTimer mCountDownTimer;
private Long pointsCounter;
private boolean mTimerRunning;
private long mTimeLeftInMillis = START_TIME_IN_MILLIS;
ArrayList<Game1KeyValue> allpairs;
boolean isMatch=false;
ImageAdapter imageAdapter2;
ImageView curView = null;
private int countPair = 0;
TextView tv6;
TextView myPoints;
TextView temPoints;
public int[] drawable;
int[] pos;
int maxnum=2;
int currentPos = -1;
MediaPlayer mediaPlayerno_ar;
MediaPlayer mediaPlayer_no;
MediaPlayer mediaPlayeryes;
MediaPlayer mediaPlayeryes_ar;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
allSharedPrefernces = new AllSharedPrefernces(this);
setContentView(R.layout.activity_game1__home);
drawable=new int[]
{
R.drawable.yes_ar,
R.drawable.no_ar,
R.drawable.no,
R.drawable.yes,
};
pos=TawleedRandom.walledArray(4);
allpairs = new ArrayList<>();
allpairs.add(new Game1KeyValue(R.drawable.yes,R.drawable.yes_ar));
allpairs.add(new Game1KeyValue(R.drawable.no ,R.drawable.no_ar));
temPoints=findViewById(R.id.l1g1_tempoints);
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
height = displayMetrics.heightPixels;
width = displayMetrics.widthPixels;
tv6 = findViewById(R.id.g2_tv4_pairsCount);
myPoints=findViewById(R.id.g2_tv6_Ponits);
pointsCounter=getPoints();
myPoints.setText(pointsCounter+"");
pointsCounter=0L;
tv6.setText(""+drawable.length /2);
mTextViewCountDown = findViewById(R.id.g1_tv2_text_view_countdown);
textViewPairs=findViewById(R.id.g1_tv2_pairsCount);
mButtonStartPause = findViewById(R.id.button_start_pause);
mButtonReset = findViewById(R.id.button_reset);
mButtonStartPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mTimerRunning) {
pauseTimer();
} else {
startTimer();
}
}
});
mButtonReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
playAgain(v);
}
});
updateCountDownText();
final ImageAdapter imageAdapter = new ImageAdapter(this,height,width,drawable.length);
GridView gridView = findViewById(R.id.gridView);
gridView.setNumColumns(2);
gridView.setEnabled(false);
RelativeLayout.LayoutParams parameter = (RelativeLayout.LayoutParams) gridView.getLayoutParams();
parameter.setMargins(width * 2 /7, parameter.topMargin, parameter.rightMargin, parameter.bottomMargin); // left, top, right, bottom
gridView.setLayoutParams(parameter);
gridView.setAdapter(imageAdapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (currentPos < 0) {
currentPos = position;
curView = (ImageView) view;
runSuitableMusika(drawable[pos[position]]);
((ImageView) view).setImageResource(drawable[pos[position]]);
view1 = view;
position1 = position;
} else
{
if (currentPos == position)
{
((ImageView) view).setImageResource(R.drawable.questionbg);
}
else
{
runSuitableMusika(drawable[pos[position]]);
for (Game1KeyValue d : allpairs) {
if ((d.key == drawable[pos[currentPos]]) || (d.value == drawable[pos[currentPos]])) {
if (d.key == drawable[pos[currentPos]]) {
if (d.value == drawable[pos[position]]) {
isMatch = true;
d.setUsed(1);
}
break;
} else {
if (d.value == drawable[pos[currentPos]]) {
if (d.key == drawable[pos[position]]) {
isMatch = true;
}
break;
}
}
}
}
((ImageView) view).setImageResource(drawable[pos[position]]);
view1 = view;
if (!isMatch) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
curView.setImageResource(R.drawable.questionbg);
((ImageView) view1).setImageResource(R.drawable.questionbg);
}
}, 600);
}
else if (isMatch) {
isMatch = false;
((ImageView) view).setImageResource(drawable[pos[position]]);
runSuitableMusika(drawable[pos[position]]);
countPair++;
pointsCounter=pointsCounter+1L;
temPoints.setText(pointsCounter+"");
textViewPairs.setText(countPair + "");
if(countPair != maxnum)
{
int curNum=drawable.length;
int[] newArray = new int[curNum-2];
int[] pos1=TawleedRandom.walledArray(curNum-2);
int k=0;
for(int i=0;i<curNum;i++)
{
if(i==position || i==currentPos)
{
}
else
{
newArray[pos1[k]] = drawable[pos[i]];
k++;
}
}
drawable=newArray;
pos=pos1;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
removeFromGrid();
}
}, 1000);
}
else
if (countPair == maxnum) {
try
{
Thread.sleep(500);
}
catch (InterruptedException e) {
e.printStackTrace();
}
passToNext(view);
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
currentPos = -1;
}
}
});
}
private void removeFromGrid()
{
GridView gridView = findViewById(R.id.gridView);
gridView.setAdapter(null);
imageAdapter2=new ImageAdapter(this,height,width,drawable.length);
gridView.setNumColumns(2);
gridView.setAdapter(imageAdapter2);
currentPos = -1;
}
private void startTimer() {
mCountDownTimer = new CountDownTimer(mTimeLeftInMillis, 1000) {
#Override
public void onTick(long millisUntilFinished) {
mTimeLeftInMillis = millisUntilFinished;
updateCountDownText();
}
#Override
public void onFinish() {
GridView gridView0 = findViewById(R.id.gridView);
gridView0.setVisibility(View.INVISIBLE);
Button btn2=findViewById(R.id.button_start_pause);
btn2.setVisibility(View.INVISIBLE);
AlertDialog.Builder builder = new AlertDialog.Builder(game1_HomeActivity.this);
builder.setCancelable(true);
builder.setTitle(" انتهت اللعبة ");
builder.setMessage("حظ أوفر المرة القادمة");
builder.setNegativeButton("الخروج من اللعبة", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialogInterface, int i) {
backToFirstMethod();
}
});
builder.setPositiveButton("العب مرة أخرى", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
});
builder.show();
}
}.start();
mTimerRunning = true;
mButtonStartPause.setText("إيقاف مؤقت");
mButtonReset.setVisibility(View.INVISIBLE);
GridView gridView = findViewById(R.id.gridView);
gridView.setNumColumns(2);
gridView.setEnabled(true);
}
private void pauseTimer() {
mCountDownTimer.cancel();
mTimerRunning = false;
mButtonStartPause.setText("استئناف");
mButtonReset.setVisibility(View.VISIBLE);
GridView gridView = findViewById(R.id.gridView);
gridView.setNumColumns(2);
gridView.setEnabled(false);
}
private void updateCountDownText() {
int minutes = (int) (mTimeLeftInMillis / 1000) / 60;
int seconds = (int) (mTimeLeftInMillis / 1000) % 60;
String timeLeftFormatted = String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds);
mTextViewCountDown.setText(timeLeftFormatted);
}
public void passToNext(View view)
{
allSharedPrefernces.writeTimer1(mTimeLeftInMillis);
allSharedPrefernces.saveDbPoints(getPoints());
allSharedPrefernces.storeTempPoints(2L);
startActivity(new Intent(this,game1_secondActivity.class));
finish();
}
public void playAgain(View view)
{
Intent intent = getIntent();
finish();
startActivity(intent);
}
public void backToFirstMethod()
{
startActivity(new Intent(this, indexActivity.class));
finish();
}
public Long getPoints()
{
SchoolDbHelper schoolDbHelper=new SchoolDbHelper(this);
SQLiteDatabase mydatabase=schoolDbHelper.getReadableDatabase();
Long c= schoolDbHelper.getCurrentPoints(11,mydatabase);
return c;
}
Your exceptions shows that you are calling activity that is destroyed or vice versa.
Make sure there is no activity or dialog that is called after destroying that activity.
For more information Check following link
Bad window token, you cannot show a dialog before an Activity is created or after it's hidden
you are trying to show the dialog for a context that no longer exists.
try using this in side your onFinish() method of startTimer()
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity().this);
Also check if activity is visible, like, e.g.
if (getActivity().hasWindowFocus()) {
// create & show dialog here
}
I"m streaming HLS video with EXOPlayer and it is working perfectly. However, If there is some changes with HLS streaming source video and then video playing stopped and keep showing loading circle.
My question is how could I force reload and resume playback for realtime when video stopped? Here is my code
public class TvPlay extends AppCompatActivity implements HlsSampleSource.EventListener, View.OnClickListener {
public static final int RENDERER_COUNT = 2;
public static final int TYPE_AUDIO = 1;
private ExoPlayer player;
private SurfaceView surface;
private Handler mainHandler;
private TrackRenderer videoRenderer;
private LinearLayout root;
public static final int TYPE_VIDEO = 0;
private View decorView;
private int uiImmersiveOptions;
private RelativeLayout loadingPanel;
private Runnable updatePlayer, hideControls;
//Implementing current time, total time and seekbar
private TextView txt_ct, txt_td;
private SeekBar seekBar;
private PlayerControl playerControl;
public enum ControlsMode {
FULLCONTORLS
}
private ControlsMode controlsState;
private ImageButton btn_play;
private ImageButton btn_pause;
private ImageButton btn_settings;
private String url;
{
updatePlayer = new Runnable() {
#Override
public void run() {
switch (player.getPlaybackState()) {
case ExoPlayer.STATE_BUFFERING:
loadingPanel.setVisibility(View.VISIBLE);
break;
case ExoPlayer.STATE_ENDED:
finish();
break;
case ExoPlayer.STATE_IDLE:
loadingPanel.setVisibility(View.GONE);
break;
case ExoPlayer.STATE_PREPARING:
loadingPanel.setVisibility(View.VISIBLE);
break;
case ExoPlayer.STATE_READY:
loadingPanel.setVisibility(View.GONE);
break;
default:
break;
}
String totDur = String.format("%02d.%02d.%02d",
TimeUnit.MILLISECONDS.toHours(player.getDuration()),
TimeUnit.MILLISECONDS.toMinutes(player.getDuration()) -
TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(player.getDuration())), // The change is in this line
TimeUnit.MILLISECONDS.toSeconds(player.getDuration()) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(player.getDuration())));
String curDur = String.format("%02d.%02d.%02d",
TimeUnit.MILLISECONDS.toHours(player.getCurrentPosition()),
TimeUnit.MILLISECONDS.toMinutes(player.getCurrentPosition()) -
TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(player.getCurrentPosition())), // The change is in this line
TimeUnit.MILLISECONDS.toSeconds(player.getCurrentPosition()) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(player.getCurrentPosition())));
txt_ct.setText(curDur);
txt_td.setText(totDur);
seekBar.setMax((int) player.getDuration());
seekBar.setProgress((int) player.getCurrentPosition());
mainHandler.postDelayed(updatePlayer, 200);
}
};
}
{
hideControls = new Runnable() {
#Override
public void run() {
hideAllControls();
}
};
}
private void hideAllControls() {
if (controlsState == ControlsMode.FULLCONTORLS) {
if (root.getVisibility() == View.VISIBLE) {
root.setVisibility(View.GONE);
}
}
decorView.setSystemUiVisibility(uiImmersiveOptions);
}
private void showControls() {
if (controlsState == ControlsMode.FULLCONTORLS) {
if (root.getVisibility() == View.GONE) {
root.setVisibility(View.VISIBLE);
}
}
mainHandler.removeCallbacks(hideControls);
mainHandler.postDelayed(hideControls, 5000);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
showControls();
break;
}
return super.onTouchEvent(event);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tvplay);
url=getIntent().getStringExtra("url");
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
uiImmersiveOptions = (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
);
decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(uiImmersiveOptions);
loadingPanel = (RelativeLayout) findViewById(R.id.loadingVPanel);
txt_ct = (TextView) findViewById(R.id.txt_currentTime);
txt_td = (TextView) findViewById(R.id.txt_totalDuration);
seekBar = (SeekBar) findViewById(R.id.seekbar);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
player.seekTo(seekBar.getProgress());
}
});
btn_play = (ImageButton) findViewById(R.id.btn_play);
btn_pause = (ImageButton) findViewById(R.id.btn_pause);
btn_settings = (ImageButton) findViewById(R.id.btn_settings);
btn_play.setOnClickListener(this);
btn_pause.setOnClickListener(this);
btn_settings.setOnClickListener(this);
root = (LinearLayout) findViewById(R.id.root);
root.setVisibility(View.VISIBLE);
surface = (SurfaceView) findViewById(R.id.surface_view);
mainHandler = new Handler();
execute();
}
#Override
public void onClick(View v) {
int i1 = v.getId();
if (i1 == R.id.btn_pause) {
if (playerControl.isPlaying()) {
playerControl.pause();
btn_pause.setVisibility(View.GONE);
btn_play.setVisibility(View.VISIBLE);
}
}
if (i1 == R.id.btn_play) {
if (!playerControl.isPlaying()) {
playerControl.start();
btn_pause.setVisibility(View.VISIBLE);
btn_play.setVisibility(View.GONE);
}
}
if (i1 == R.id.btn_settings) {
PopupMenu popup = new PopupMenu(TvPlay.this, v);
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
player.setSelectedTrack(0, (item.getItemId() - 1));
return false;
}
});
Menu menu = popup.getMenu();
menu.add(Menu.NONE, 0, 0, "Video Quality");
for (int i = 0; i < player.getTrackCount(0); i++) {
MediaFormat format = player.getTrackFormat(0, i);
if (MimeTypes.isVideo(format.mimeType)) {
if (format.adaptive) {
menu.add(1, (i + 1), (i + 1), "Auto");
} else {
menu.add(1, (i + 1), (i + 1), format.bitrate/1000 + " kbps");
}
}
}
menu.setGroupCheckable(1, true, true);
menu.findItem((player.getSelectedTrack(0) + 1)).setChecked(true);
popup.show();
}
}
private void execute() {
player = ExoPlayer.Factory.newInstance(RENDERER_COUNT);
playerControl = new PlayerControl(player);
if (player != null) {
HpLib_RendererBuilder hpLibRendererBuilder = getHpLibRendererBuilder();
hpLibRendererBuilder.buildRenderers(this);
loadingPanel.setVisibility(View.VISIBLE);
mainHandler.postDelayed(updatePlayer, 200);
mainHandler.postDelayed(hideControls, 3000);
controlsState = ControlsMode.FULLCONTORLS;
}
}
private HpLib_RendererBuilder getHpLibRendererBuilder() {
String userAgent = Util.getUserAgent(this, "AndroidLiveTV");
if(url.endsWith(".m3u8")){
return new HpLib_HlsHpLibRendererBuilder(this, userAgent, url);
}else{
return new HpLib_ExtractorHpLibRendererBuilder(this, userAgent, Uri.parse(url));
}
/*
switch (video_type[currentTrackIndex]) {
case "hls":
return new HpLib_HlsHpLibRendererBuilder(this, userAgent, video_url[currentTrackIndex]);
case "others":
return new HpLib_ExtractorHpLibRendererBuilder(this, userAgent, Uri.parse(video_url[currentTrackIndex]));
default:
throw new IllegalStateException("Unsupported type: " + video_url[currentTrackIndex]);
}
*/
}
Handler getMainHandler() {
return mainHandler;
}
void onRenderersError(Exception e) {
}
void onRenderers(TrackRenderer[] renderers, BandwidthMeter bandwidthMeter) {
for (int i = 0; i < renderers.length; i++) {
if (renderers[i] == null) {
renderers[i] = new DummyTrackRenderer();
}
}
// Complete preparation.
this.videoRenderer = renderers[TYPE_VIDEO];
pushSurface(false);
player.prepare(renderers);
player.setPlayWhenReady(true);
}
private void pushSurface(boolean blockForSurfacePush) {
if (videoRenderer == null) {
return;
}
if (blockForSurfacePush) {
player.blockingSendMessage(
videoRenderer, MediaCodecVideoTrackRenderer.MSG_SET_SURFACE, surface.getHolder().getSurface());
} else {
player.sendMessage(
videoRenderer, MediaCodecVideoTrackRenderer.MSG_SET_SURFACE, surface.getHolder().getSurface());
}
}
private void killPlayer() {
if (player != null) {
player.release();
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
killPlayer();
}
#Override
public void onLoadStarted(int sourceId, long length, int type, int trigger, Format format, long mediaStartTimeMs, long mediaEndTimeMs) {
}
#Override
public void onLoadCompleted(int sourceId, long bytesLoaded, int type, int trigger, Format format, long mediaStartTimeMs, long mediaEndTimeMs, long elapsedRealtimeMs, long loadDurationMs) {
}
#Override
public void onLoadCanceled(int sourceId, long bytesLoaded) {
}
#Override
public void onLoadError(int sourceId, IOException e) {
}
#Override
public void onUpstreamDiscarded(int sourceId, long mediaStartTimeMs, long mediaEndTimeMs) {
}
#Override
public void onDownstreamFormatChanged(int sourceId, Format format, int trigger, long mediaTimeMs) {
}
In my android application while I'm playing a music, the seekbar bar is staying still. The timer of the music is running fine & the music plays from the touched position of the seek bar.
But the problem is that the seekbar is still and not moving while touching on the seekbar .
Any one help me to find a solution for this .. Thank You ..
My Activity code is ....
public class Device_AudioPlayerActivity extends Activity implements Runnable,
OnClickListener, SeekBar.OnSeekBarChangeListener {
Button btnBack;
static Button btnPause;
private Handler mHandler;
Button btnNext;
static Button btnPlay;
static TextView textNowPlaying;
static TextView textAlbumArtist;
static TextView textComposer;
static LinearLayout linearLayoutPlayer;
SeekBar progressBar;
static Context context;
TextView textBufferDuration, textDuration;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//getActionBar().hide();
setContentView(R.layout.device_audio_player);
context = this;
progressBar=(SeekBar)findViewById(R.id.progressBar);
init();
progressBar.setMax(Device_SongService.mp.getDuration());
new Thread().start();
progressBar.setOnSeekBarChangeListener(this);
progressBar.setEnabled(true);
//-=--------------------------------------
}
private void init() {
getViews();
setListeners();
progressBar.getProgressDrawable().setColorFilter(getResources().getColor(R.color.white), Mode.SRC_IN);
Device_PlayerConstants.PROGRESSBAR_HANDLER = new Handler() {
#Override
public void handleMessage(Message msg) {
Integer i[] = (Integer[]) msg.obj;
textBufferDuration.setText(Device_UtilFunctions.getDuration(i[0]));
textDuration.setText(Device_UtilFunctions.getDuration(i[1]));
progressBar.setProgress(i[2]);
}
};
}
private void setListeners() {
btnBack.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Device_Controls.previousControl(getApplicationContext());
}
});
btnPause.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Device_Controls.pauseControl(getApplicationContext());
}
});
btnPlay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Device_Controls.playControl(getApplicationContext());
}
});
btnNext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Device_Controls.nextControl(getApplicationContext());
}
});
}
public static void changeUI() {
updateUI();
changeButton();
}
private void getViews() {
btnBack = (Button) findViewById(R.id.btnBack);
btnPause = (Button) findViewById(R.id.btnPause);
btnNext = (Button) findViewById(R.id.btnNext);
btnPlay = (Button) findViewById(R.id.btnPlay);
textNowPlaying = (TextView) findViewById(R.id.textNowPlaying);
linearLayoutPlayer = (LinearLayout) findViewById(R.id.linearLayoutPlayer);
textAlbumArtist = (TextView) findViewById(R.id.textAlbumArtist);
textComposer = (TextView) findViewById(R.id.textComposer);
progressBar = (SeekBar) findViewById(R.id.progressBar);
textBufferDuration = (TextView) findViewById(R.id.textBufferDuration);
textDuration = (TextView) findViewById(R.id.textDuration);
textNowPlaying.setSelected(true);
textAlbumArtist.setSelected(true);
}
#Override
protected void onResume() {
super.onResume();
boolean isServiceRunning = Device_UtilFunctions.isServiceRunning(Device_SongService.class.getName(), getApplicationContext());
if (isServiceRunning) {
updateUI();
}
changeButton();
}
public static void changeButton() {
if (Device_PlayerConstants.SONG_PAUSED) {
btnPause.setVisibility(View.GONE);
btnPlay.setVisibility(View.VISIBLE);
} else {
btnPause.setVisibility(View.VISIBLE);
btnPlay.setVisibility(View.GONE);
}
}
private static void updateUI() {
try {
String songName = Device_PlayerConstants.SONGS_LIST.get(Device_PlayerConstants.SONG_NUMBER).getTitle();
String artist = Device_PlayerConstants.SONGS_LIST.get(Device_PlayerConstants.SONG_NUMBER).getArtist();
String album = Device_PlayerConstants.SONGS_LIST.get(Device_PlayerConstants.SONG_NUMBER).getAlbum();
String composer = Device_PlayerConstants.SONGS_LIST.get(Device_PlayerConstants.SONG_NUMBER).getComposer();
textNowPlaying.setText(songName);
textAlbumArtist.setText(artist + " - " + album);
if (composer != null && composer.length() > 0) {
textComposer.setVisibility(View.VISIBLE);
textComposer.setText(composer);
} else {
textComposer.setVisibility(View.GONE);
}
} catch (Exception e) {
e.printStackTrace();
}
try {
long albumId = Device_PlayerConstants.SONGS_LIST.get(Device_PlayerConstants.SONG_NUMBER).getAlbumId();
Bitmap albumArt = Device_UtilFunctions.getAlbumart(context, albumId);
if (albumArt != null) {
linearLayoutPlayer.setBackgroundDrawable(new BitmapDrawable(albumArt));
} else {
linearLayoutPlayer.setBackgroundDrawable(new BitmapDrawable(Device_UtilFunctions.getDefaultAlbumArt(context)));
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onClick(View view) {
}
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
try {
if (Device_SongService.mp.isPlaying() || Device_SongService.mp != null) {
if (b)
Device_SongService.mp.seekTo(i);
} else if (Device_SongService.mp == null) {
Toast.makeText(getApplicationContext(), "Media is not running",
Toast.LENGTH_SHORT).show();
seekBar.setProgress(0);
}
} catch (Exception e) {
Log.e("seek bar", "" + e);
seekBar.setEnabled(false);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
#Override
public void run() {
int currentPosition = Device_SongService.mp.getCurrentPosition();
int total = Device_SongService.mp.getDuration();
while (Device_SongService.mp != null && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = Device_SongService.mp.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
progressBar.setProgress(currentPosition);
}
}
}
Have a look at this link.
Try using a thread in progress changed.
you have to use thread on onprogresschnaged....
#Override
public void onProgressChanged(SeekBar arg0, final int progress, boolean arg2) {
Thread thread = new Thread() {
#Override
public void run() {
try {
while(true) {
//here write your code
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
thread.start();
}
I have the problem with the seekbar thumb, although I have added every necessary codes for it to work. still the seekbar thumb doesn't play from the point dragged by the user. instead the thumb positioned itself back to the point it was last playing though. Any help will be appreciated.
plus = (ImageButton) findViewById(R.id.imageButton2);
minus = (ImageButton) findViewById(R.id.imageButton4);
player = MediaPlayer.create(this, R.raw.songnames);
player.setLooping(false);
im = (ImageButton) this.findViewById(R.id.imageButton3);
seekbar = (SeekBar) findViewById(R.id.mantraProgressBar);
seekbar.setVisibility(ProgressBar.VISIBLE);
seekbar.setProgress(0);
seekbar.setMax(player.getDuration());
new Thread(this).start();
im.setOnClickListener(this);
player.start();
im.setImageResource(R.drawable.pause_tran);
Toast.makeText(this, isPlaying, Toast.LENGTH_LONG).show();
plus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int cu = player.getCurrentPosition();
player.seekTo(cu - 5000);
}
});
minus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int cu = player.getCurrentPosition();
player.seekTo(cu + 5000);
}
});
}
#Override
public void onClick(View arg0) {
if (arg0.getId() == R.id.imageButton3) {
if (player.isPlaying()) {
player.pause();
Toast.makeText(this, notPlaying, Toast.LENGTH_LONG).show();
ImageButton img1 = (ImageButton) this.findViewById(R.id.imageButton3);
img1.setImageResource(R.drawable.play_tran);
} else {
player.start();
Toast.makeText(this, isPlaying, Toast.LENGTH_LONG).show();
ImageButton img1 = (ImageButton) this.findViewById(R.id.imageButton3);
img1.setImageResource(R.drawable.pause_tran);
}
}
}
#Override
public void run() {
int currentPosition = 0;
String s;
int total = player.getDuration();
while (player != null && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = player.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seekbar.setProgress(currentPosition);
}
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
player.seekTo(progress);
seekbar.setProgress(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
public class MainActivity extends AppCompatActivity {
private MyVideoView mVV;
private Handler mhandler;
private SeekBar seekbar;
private int duration;
private int backPositon = 0;
private int currentPosition;
private SharedPreferences sp;
private MediaController controller;
private TextView tv_curr;
private TextView tv_duration;
private Handler handler;
private boolean mExit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mVV = (MyVideoView) findViewById(R.id.vv);
seekbar = (SeekBar) findViewById(R.id.seekbar);
tv_curr = (TextView) findViewById(R.id.tv_currtime);
tv_duration = (TextView) findViewById(R.id.tv_duration);
//get duration of video
getDuration();
//video start
playVideo();
//get current time
getCurrentDuration();
//listener
initEvent();
}
private void initHanlder() {
handler=new Handler(){
#Override
public void handleMessage(Message msg) {
if (msg.what==0x123){
tv_curr.setText(timeFormat(mVV.getCurrentPosition()));
seekbar.setProgress(mVV.getCurrentPosition());
}
if(msg.what==0x133){
int changedProgress = msg.arg1;
tv_curr.setText(timeFormat(changedProgress));
mVV.seekTo(changedProgress);
seekbar.setProgress(changedProgress);
mVV.start();
}
}
};
new Thread(new Runnable() {
#Override
public void run() {
while (mVV.getCurrentPosition()<duration){
Message message = Message.obtain();
message.what=0x123;
handler.sendMessage(message);
SystemClock.sleep(1000);
if(mExit){
break;
}
}
}
}).start();
}
private void getDuration() {
mVV.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
duration = mVV.getDuration();
timeFormat(duration);
Log.d("TAG", "---duration" + timeFormat(duration));
seekbar.setMax(duration);
//TextView time
tv_duration.setText(timeFormat(duration));
//init handler
initHanlder();
}
});
}
private String timeFormat(int time) {
StringBuilder mFormatBuilder;
Formatter mFormatter;
mFormatBuilder = new StringBuilder();
mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());
int totalSeconds = time / 1000;
int seconds = totalSeconds % 60;
int minutes = (totalSeconds / 60) % 60;
int hours = totalSeconds / 3600;
mFormatBuilder.setLength(0);
if (hours > 0) {
return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
} else {
return mFormatter.format("%02d:%02d", minutes, seconds).toString();
}
}
private void playVideo() {
File file = new File(Environment.getExternalStorageDirectory(), "cgx_video/db.mp4");
if (!file.exists()) {
file.mkdir();
}
Log.d("TAG", file.toString());
mVV.setVideoPath(file.getPath());
mVV.start();
}
private void initEvent() {
seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
currentPosition=progress;
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
mVV.pause();
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
if(handler!=null){
Message message = Message.obtain();
message.what=0x133;
message.arg1=currentPosition;
handler.sendMessage(message);
}
}
});
}
#Override
protected void onPause() {
super.onPause();
Log.d("TAG", "---onPause");
mVV.pause();
backPositon = mVV.getCurrentPosition();
Log.d("TAG", "backPositon:" + backPositon);
}
#Override
protected void onStop() {
super.onStop();
Log.d("TAG", "---onStop");
}
#Override
protected void onResume() {
super.onResume();
Log.d("TAG", backPositon + "---backPositon");
mVV.seekTo(backPositon);
mVV.start();
}
#Override
protected void onDestroy() {
//in case of leak of memeroy
mExit=true;
super.onDestroy();
}
}