In Exoplayer,How to reload and resume playback automatically? - android

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) {
}

Related

seekbar.setMax() is not updating

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?

Application restart suddenly

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
}

when back to activity from click music notification when click to next music view not update

When I click music notification and run activity. When music change the content of textview changed, but view not update, but when I run an activity independently, everything works fine and view updated.
In musicService class:
PendingIntent contentPendingIntent = PendingIntent.getActivity
(this, 0, new Intent(this, MusicPlayer.class), 0);
builder.setContentTitle(mMedia.getTitleMedia())
.setContentText(mMedia.getSingerName())
.setContentIntent(contentPendingIntent)
.setSmallIcon(R.drawable.ic_notification)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.addAction(restartAction)
.addAction(playPauseAction)
.addAction(nextMusic)
.setDeleteIntent(MediaButtonReceiver.buildMediaButtonPendingIntent(getApplicationContext(), PlaybackStateCompat.ACTION_STOP));
and my activity class
public class MusicPlayer extends AppCompatActivity implements ServiceConnection, CacheListener, SeekBar.OnSeekBarChangeListener, Player.EventListener {
private SimpleExoPlayerView mPlayerView;
public PlayerService mPlayerService;
private boolean mBound;
//______________________________________________________________________________________________
VolleyRequestHelper volleyRequestHelper;
//______________________________________________________________________________________________
public static MusicPlayer instance;
public ImageView download;
TextView title;
TextView artist;
SeekBar progressBar;
ImageView circleImageView;
ImageView album_art_blurred;
PlayPauseButton mPlayPause;
public AppBarLayout appBarLayout;
private final VideoProgressUpdater updater = new VideoProgressUpdater();
public DownloadProgressView downloadProgressView;
//______________________________________________________________________________________________
TextView songElapsedTime;
TextView songDuration;
int positionOfMusic = 0;
public Media media;
boolean initAlbum = false;
boolean startService = false;
boolean checkChangeMediaDetails = true;
//______________________________________________________________________________________________
RecyclerView recyclerViewArtist;
SimilarSongsAdapter similarSongsAdapter;
public List<Media> similarSongsList = new ArrayList<>();
//______________________________________________________________________________________________
int songElapsed = 0;
int songDurationTime = 0;
int videoProgress = 0;
int mediaServiceRun = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_music_player);
instance = this;
volleyRequestHelper = VolleyRequestHelper.getInstance(getApplicationContext(), requestCompletedListener);
initView();
initRecyclerview();
Intent intent = getIntent();
mediaServiceRun = intent.getIntExtra("mediaServiceRun", 1);
if (mediaServiceRun == 1) {
Intent i = new Intent(this, PlayerService.class);
bindService(i, this, Context.BIND_AUTO_CREATE);
startService(i);
} else {
media = intent.getParcelableExtra("media");
switch (media.getCustomMediaType()) {
case "آهنگ آلبوم":
setMedia(media);
getAlbumTrack(media.getAlbumId());
break;
case "آلبوم":
initAlbum = true;
getAlbumTrack(media.getId());
break;
default:
setMedia(media);
Serach(media.getSingerName(), "1");
break;
}
selectMedia(media);
}
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
if (mBound) {
unbindService(this);
mBound = false;
}
}
#Override
protected void onResume() {
super.onResume();
updater.start();
}
#Override
public void onPause() {
super.onPause();
updater.stop();
}
//_________________________ServiceConnected_and_ServiceDisconnected_____________________________
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
PlayerService.MyBinder b = (PlayerService.MyBinder) iBinder;
mPlayerService = b.getService();
mPlayerView.setUseController(false);
mPlayerView.setPlayer(mPlayerService.getExoPlayer());
if (mediaServiceRun == 1) {
similarSongsList = mPlayerService.getOnlineList();
initView();
initRecyclerview();
musicChange(mPlayerService.getPlayingMedia());
} else {
mPlayerService.getExoPlayer().addListener(this);
mPlayerService.setPlayingMedia(positionOfMusic);
setMusicInService(media, mPlayerService.getPlayingMedia());
if (similarSongsList != null && similarSongsList.size() != 0) {
mPlayerService.setOnlineList(similarSongsList);
}
}
mBound = true;
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
mBound = false;
}
//______________________________________________________________________________________________
//_______________________________________setMediaInView_________________________________________
public void setMedia(Media mediaL) {
media = mediaL;
bluredImage(mediaL.getCover());
Picasso.with(this).load(mediaL.getCover()).into(circleImageView);
title.setText(mediaL.getTitleMedia());
artist.setText(mediaL.getSingerName());
checkCachedState(mediaL.getStreamUrl());
checkChangeMediaDetails = false;
}
public void bluredImage(String IMAGE_URL) {
Target target = new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
album_art_blurred.setImageBitmap(BlurImage.fastblur(bitmap, 1f, 50));
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
album_art_blurred.setImageResource(R.mipmap.ic_launcher);
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
};
album_art_blurred.setTag(target);
Picasso.with(this)
.load(IMAGE_URL)
.error(R.mipmap.ic_launcher)
.placeholder(R.mipmap.ic_launcher)
.into(target);
}
//______________________________________________________________________________________________
//______________________________________initView________________________________________________
public void initRecyclerview() {
recyclerViewArtist = (RecyclerView) findViewById(R.id.queue_recyclerview_horizontal);
recyclerViewArtist.setNestedScrollingEnabled(false);
recyclerViewArtist.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
LinearLayoutManager horizontalLayoutManagaertwo
= new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false);
recyclerViewArtist.setLayoutManager(horizontalLayoutManagaertwo);
similarSongsAdapter = new SimilarSongsAdapter(this, similarSongsList, recyclerViewArtist);
recyclerViewArtist.setAdapter(similarSongsAdapter);
}
public void initView() {
mPlayerView = (SimpleExoPlayerView) findViewById(R.id.simpleExoPlayerView);
appBarLayout = (AppBarLayout) findViewById(R.id.appbar);
downloadProgressView = (DownloadProgressView) findViewById(R.id.downloadProgressView);
downloadProgressView.setPercentageColor(Color.parseColor("#ffffff"));
downloadProgressView.setDownloadedSizeColor(Color.parseColor("#ffffff"));
downloadProgressView.setTotalSizeColor(Color.parseColor("#ffffff"));
songElapsedTime = (TextView) findViewById(R.id.song_elapsed_time);
songDuration = (TextView) findViewById(R.id.song_duration);
progressBar = (SeekBar) findViewById(R.id.song_progress);
progressBar.setOnSeekBarChangeListener(this);
circleImageView = (ImageView) findViewById(R.id.album_art);
album_art_blurred = (ImageView) findViewById(R.id.album_art_blurred);
title = (TextView) findViewById(R.id.song_title);
artist = (TextView) findViewById(R.id.song_artist);
mPlayPause = (PlayPauseButton) findViewById(R.id.playpause);
download = (ImageView) findViewById(R.id.download);
if (SornaDownloadManager.inQueue) {
if (SornaDownloadManager.checkDownloadId(media.getId())) {
download.setVisibility(View.GONE);
downloadProgressView.show(SornaDownloadManager.lastDownloadID,
new DownloadProgressView.DownloadStatusListener() {
#Override
public void downloadFailed(int reason) {
SornaDownloadManager.PullFromQueue(media.getId());
download.setVisibility(View.VISIBLE);
}
#Override
public void downloadSuccessful() {
SornaDownloadManager.PullFromQueue(media.getId());
download.setVisibility(View.VISIBLE);
}
#Override
public void downloadCancelled() {
SornaDownloadManager.PullFromQueue(media.getId());
download.setVisibility(View.VISIBLE);
}
});
}
}
}
//______________________________________________________________________________________________
//_________________________________Cache_and_UpdateProgressBar__________________________________
private void checkCachedState(String url) {
HttpProxyCacheServer proxy = TimberApp.getProxy(this);
boolean fullyCached = proxy.isCached(url);
if (fullyCached) {
progressBar.setSecondaryProgress(100);
}
proxy.registerCacheListener(this, url);
}
private void updateVideoProgress() {
if (mPlayerService != null)
try {
videoProgress = (int) (mPlayerService.getExoPlayer().getCurrentPosition() * 100 / mPlayerService.getExoPlayer().getDuration());
} catch (Exception e) {
}
progressBar.setProgress(videoProgress);
}
private final class VideoProgressUpdater extends Handler {
public void start() {
sendEmptyMessage(0);
}
public void stop() {
removeMessages(0);
}
#Override
public void handleMessage(Message msg) {
updateVideoProgress();
sendEmptyMessageDelayed(0, 500);
if (mPlayerService != null) {
try {
songElapsed = (int) mPlayerService.getExoPlayer().getCurrentPosition();
songDurationTime = (int) mPlayerService.getExoPlayer().getDuration();
} catch (Exception e) {
}
}
songElapsedTime.setText(millisecondsTOminutes.milliSecondsToTimer(songElapsed));
songDuration.setText(millisecondsTOminutes.milliSecondsToTimer(songDurationTime));
}
}
#Override
public void onCacheAvailable(File cacheFile, String url, int percentsAvailable) {
progressBar.setSecondaryProgress(percentsAvailable);
}
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
void seekVideo() {
int videoPosition = (int) (mPlayerService.getExoPlayer().getDuration() * progressBar.getProgress() / 100);
mPlayerService.getExoPlayer().seekTo(videoPosition);
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
seekVideo();
songElapsedTime.setText(millisecondsTOminutes.milliSecondsToTimer(mPlayerService.getExoPlayer().getCurrentPosition()) + "");
}
//______________________________________________________________________________________________
//____________________________________setButtonsFuction_________________________________________
public void setFunc(View v) {
switch (v.getId()) {
case R.id.playpause:
if (!mPlayPause.isPlayed()) {
setPlayButton(true);
if (!startService) {
setStopService();
setStartService();
onlinePlay(media.getId());
} else {
mPlayerService.playTrack();
}
} else {
setPlayButton(false);
mPlayerService.pauseTrack();
}
break;
case R.id.next:
mPlayerService.nextTrack();
//positionOfMusic = mPlayerService.getPlayingMedia();
break;
case R.id.previous:
mPlayerService.previousTrack();
//positionOfMusic = mPlayerService.getPlayingMedia();
break;
case R.id.download:
showPopup(media);
break;
case R.id.share:
share.shareTrack(media, this);
break;
}
}
public void showPopup(final Media media) {
View popupView = LayoutInflater.from(this).inflate(R.layout.popup_layout, null);
final PopupWindow popupWindow = new PopupWindow(popupView, WindowManager.LayoutParams.MATCH_PARENT
, WindowManager.LayoutParams.MATCH_PARENT);
popupWindow.setOutsideTouchable(false);
popupWindow.setFocusable(true);
popupWindow.showAtLocation(popupView, Gravity.CENTER, 1, 1);
Button dnlow = (Button) popupView.findViewById(R.id.dnlow);
Button dnhigh = (Button) popupView.findViewById(R.id.dnhigh);
if (media.getDownloadLinksList128().matches("noLink"))
dnlow.setVisibility(View.GONE);
if (media.getDownloadLinksList320().matches("noLink"))
dnhigh.setVisibility(View.GONE);
dnlow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SornaDownloadManager sornaDownloadManager = SornaDownloadManager.getInstance(getApplicationContext());
long downloadID = sornaDownloadManager.AddForDownload(media.getDownloadLinksList128(),
media.getTitleMedia() + "-" + media.getSingerName(), media.getId());
downloadProgressView.show(downloadID, new DownloadProgressView.DownloadStatusListener() {
#Override
public void downloadFailed(int reason) {
}
#Override
public void downloadSuccessful() {
SornaDownloadManager.PullFromQueue(media.getId());
download.setVisibility(View.VISIBLE);
}
#Override
public void downloadCancelled() {
SornaDownloadManager.PullFromQueue(media.getId());
download.setVisibility(View.VISIBLE);
}
});
popupWindow.dismiss();
}
});
dnhigh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SornaDownloadManager sornaDownloadManager = SornaDownloadManager.getInstance(getApplicationContext());
long downloadID = sornaDownloadManager.AddForDownload(media.getDownloadLinksList320(),
media.getTitleMedia() + "-" + media.getSingerName(), media.getId());
downloadProgressView.show(downloadID, new DownloadProgressView.DownloadStatusListener() {
#Override
public void downloadFailed(int reason) {
}
#Override
public void downloadSuccessful() {
SornaDownloadManager.PullFromQueue(media.getId());
download.setVisibility(View.VISIBLE);
}
#Override
public void downloadCancelled() {
SornaDownloadManager.PullFromQueue(media.getId());
download.setVisibility(View.VISIBLE);
}
});
popupWindow.dismiss();
}
});
popupWindow.showAsDropDown(popupView, 0, 0);
}
//______________________________________________________________________________________________
//__________________________________GetDataFromServer___________________________________________
public void Serach(String searchQuery, String page) {
updateData();
volleyRequestHelper.RequestFetchSearchMedia
(constantsURL.REQUEST_FETCH_SIMILAR_SONGS, searchQuery, page, false);
}
public void getAlbumTrack(String albumId) {
updateData();
volleyRequestHelper.RequestFetchAlbumTrack
(constantsURL.REQUEST_FETCH_ALBUM_TRACKS, albumId, false);
}
public void selectMedia(final Media media) {
if (!constants.refLogId.matches(""))
volleyRequestHelper.requestSetLog
(constantsURL.REQUEST_SET_LOG, "selectSearchResult", media.getId(), constants.refLogId, false);
}
public void onlinePlay(final String mediaid) {
volleyRequestHelper.requestSetLog
(constantsURL.REQUEST_SET_LOG, "onlinePlay", mediaid, constants.refLogId, false);
}
public void updateData() {
similarSongsAdapter.notifyDataSetChanged();
similarSongsAdapter.setLoaded();
}
public void parseJson(String response, List<Media> arrayList) {
try {
JsonParser parser = new JsonParser();
JsonElement json = parser.parse(response);
JSONObject jsonObject = new JSONObject(String.valueOf(json));
JSONArray arrey = jsonObject.getJSONArray("result");
if (!media.getCustomMediaType().matches("آلبوم"))
arrayList.add(media);
for (int i = 0; i < arrey.length(); i++) {
JSONObject j = arrey.getJSONObject(i);
Media mdia = new Media(j);
if (!media.getId().matches(mdia.getId()) && !mdia.getCustomMediaType().matches("آلبوم"))
arrayList.add(mdia);
}
} catch (Exception e) {
}
if (mPlayerService != null) {
mPlayerService.setOnlineList(similarSongsList);
}
}
private VolleyRequestHelper.OnRequestCompletedListener requestCompletedListener =
new VolleyRequestHelper.OnRequestCompletedListener() {
#Override
public void onRequestCompleted(String requestName, boolean status,
String response, String errorMessage) {
//homeView.hideProgress();
switch (requestName) {
case "SIMILAR_SONGS":
if (status) {
parseJson(response, similarSongsList);
updateData();
}
break;
case "ALBUM_TRACKS":
if (status) {
parseJson(response, similarSongsList);
updateData();
if (initAlbum) {
setMedia(similarSongsList.get(0));
}
}
break;
}
}
};
//_______________________________________EXOPLAYER______________________________________________
#Override
public void onTimelineChanged(Timeline timeline, Object manifest) {
}
#Override
public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
if (checkChangeMediaDetails) {
musicChange(mPlayerService.getPlayingMedia());
} else checkChangeMediaDetails = true;
}
#Override
public void onLoadingChanged(boolean isLoading) {
}
#Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
if ((playbackState == Player.STATE_READY) && playWhenReady) {
if (!mPlayPause.isPlayed()) {
setPlayButton(true);
}
} else if ((playbackState == Player.STATE_READY)) {
setPlayButton(false);
} else if (playbackState == Player.STATE_ENDED) {
}
}
#Override
public void onRepeatModeChanged(int repeatMode) {
}
#Override
public void onPlayerError(ExoPlaybackException error) {
}
#Override
public void onPositionDiscontinuity() {
}
#Override
public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {
}
//______________________________________________________________________________________________
public void setStartService() {
Intent intent = new Intent(this, PlayerService.class);
bindService(intent, this, Context.BIND_AUTO_CREATE);
startService(intent);
startService = true;
}
public void setStopService() {
Intent intentStop = new Intent(this, PlayerService.class);
stopService(intentStop);
}
public void setPlayButton(boolean playButton) {
mPlayPause.setPlayed(playButton);
mPlayPause.startAnimation();
}
public void setMusicInService(Media mMedia, int position) {
positionOfMusic = position;
if (mPlayerService != null) {
mPlayerService.setPlayMedia(mMedia, position);
} else {
setStartService();
setMedia(mMedia);
}
//positionOfMusic = position;
/*if (mPlayerService != null) {
mPlayerService.setMediaUri(mMedia.getStreamUrl());
mPlayerService.setMedia(mMedia);
mPlayerService.setPlayingMedia(position);
mPlayerService.preparePlayer();
} else {
positionOfMusic = position;
setStartService();
setMedia(mMedia);
}*/
}
public void musicChange(int newPosition) {
if (similarSongsList != null && similarSongsList.size() != 0) {
setMedia(similarSongsList.get(newPosition));
similarSongsAdapter.setPlayPosition(newPosition);
similarSongsAdapter.notifyDataSetChanged();
}
}
}
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder)
{
PlayerService.MyBinder b = (PlayerService.MyBinder) iBinder;
mPlayerService = b.getService();
mPlayerView.setUseController(false);
mPlayerView.setPlayer(mPlayerService.getExoPlayer());
if (mediaServiceRun == 1) {
similarSongsList = mPlayerService.getOnlineList();
initView();
initRecyclerview();
musicChange(mPlayerService.getPlayingMedia());
} else {
mPlayerService.getExoPlayer().addListener(this);
mPlayerService.setPlayingMedia(positionOfMusic);
setMusicInService(media, mPlayerService.getPlayingMedia());
if (similarSongsList != null && similarSongsList.size() != 0) {
mPlayerService.setOnlineList(similarSongsList);
}
}
mBound = true;
}

Cleveroad WaveInApp shows error after song completion

I'm trying to using Cleveroad WaveInApp in my Application
https://github.com/Cleveroad/WaveInApp everything is working fine as I want but when Song Completed it also stops mediaPlayer.setOnCompletionListener(which works fine when I removed this code).
When I try to change the song it crashes.
Error :-
java.lang.NullPointerException: Attempt to invoke interface method 'void com.cleveroad.audiovisualization.InnerAudioVisualization.stopRendering()' on a null object reference
at com.cleveroad.audiovisualization.DbmHandler.stopRendering(DbmHandler.java:61)
at com.cleveroad.audiovisualization.DbmHandler$2.onCalmedDown(DbmHandler.java:82)
at com.cleveroad.audiovisualization.GLAudioVisualizationView$1.onCalmedDown(GLAudioVisualizationView.java:49)
at com.cleveroad.audiovisualization.GLRenderer.onDrawFrame(GLRenderer.java:87)
at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1608)
at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1299)
MainContainer.class
public class MainContainer extends AppCompatActivity
implements
NavigationView.OnNavigationItemSelectedListener,
SeekBar.OnSeekBarChangeListener {
private static final String LOGTAG = "Friday";
public static final String isPlay = "isPlay";
public static final String NOTIFICATION_ACTION = "Notification_Action";
private static final String VOLUME_BUTTON = "android.media.VOLUME_CHANGED_ACTION";
SlidingUpPanelLayout slideLayout;
MusicService mService;
boolean mBound = false;
Timer t = new Timer();
SeekBar seekBar;
ImageView albumArt;
ImageView panelAlbumart;
TextView songname;
TextView singername;
TextView seekCurrentDuration;
TextView seekTotalDuration;
TextView panelSongname;
TextView panelSingername;
ImageView playBtn;
IntentFilter mIntentFilter;
RelativeLayout panelHead;
SeekBar volumeControl;
AudioManager audioManager;
AudioVisualization audioVisualization;
VisualizerDbmHandler vizualizerHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_container);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setVolumeControlStream(AudioManager.STREAM_MUSIC); //best practice to set volume control
DrawerLayout drawer = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ViewPager vp_pages = findViewById(R.id.vp_pages);
PagerAdapter pagerAdapter = new FragmentAdapter(getSupportFragmentManager());
vp_pages.setAdapter(pagerAdapter);
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(isPlay);
mIntentFilter.addAction(VOLUME_BUTTON);
mIntentFilter.addAction(NOTIFICATION_ACTION);
TabLayout tbl_pages = findViewById(R.id.tbl_pages);
tbl_pages.setupWithViewPager(vp_pages);
seekBar = findViewById(R.id.seek_bar_red);
seekBar.setOnSeekBarChangeListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_container, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onStart() {
super.onStart();
// Bind to LocalService
Intent intent = new Intent(this, MusicService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
#Override
protected void onStop() {
super.onStop();
unbindService(mConnection);
mBound = false;
}
// control Volume by Seekbar
private void volumeControl() {
volumeControl = findViewById(devil.jarvis.friday.R.id.volume_control);
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
if (audioManager != null) {
volumeControl.setMax(audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
volumeControl.setProgress(audioManager.getStreamVolume(AudioManager.STREAM_MUSIC));
}
volumeControl.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, i, 0);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
#Override
public void onResume() {
super.onResume();
registerReceiver(mReceiver, mIntentFilter);
init();
//todo add this when song is played
audioVisualization.onResume();
updateUI();
volumeControl();
}
#Override
public void onPause() {
audioVisualization.onPause();
unregisterReceiver(mReceiver);
super.onPause();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
private void init() {
albumArt = findViewById(R.id.musicArt);
panelAlbumart = findViewById(R.id.slidePanelArt);
songname = findViewById(R.id.song_name);
singername = findViewById(R.id.singer_name);
panelSingername = findViewById(R.id.singer_name_head);
panelSongname = findViewById(R.id.song_name_head);
seekCurrentDuration = findViewById(R.id.current_time);
seekTotalDuration = findViewById(R.id.song_duration);
playBtn = findViewById(R.id.play);
panelHead = findViewById(R.id.header);
slideLayout = findViewById(R.id.sliding_layout);
audioVisualization = findViewById(R.id.visualizer_view);
}
public void updateUI() {
//Update UI
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
if (mBound) {
try {
setupMusicUI(mService.getCurrentDuration(), mService.getDuration());
} catch (Exception e) {
//
}
}
}
}, 0, 1000);
}
private void setupMusicUI(int currentDuration, int duration) {
seekBar.setMax(duration);
seekBar.setProgress(currentDuration);
}
// code for update song details
private void updateTextInfo() {
if (mBound) {
int pos = mService.getPosition();
panelSongname.setText(arrayList.get(pos));
panelSingername.setText(artistName.get(pos));
songname.setText(arrayList.get(pos));
singername.setText(artistName.get(pos));
//update album art with text also
updateAlbumArt();
changePlayBtn();
startEqualiser();
// try{
// startEqualiser();
// }catch (Exception e){
// //
// }
}
}
private void setSeekbarTime(int position, int duration) {
int curr_time_seconds = (position / 1000) % 60;
int curr_time_minutes = (position / 1000) / 60;
int dur_time_seconds = (duration / 1000) % 60;
int dur_time_minutes = (duration / 1000) / 60;
String current_zero_minutes = "0";
String current_zero_seconds = "0";
String duration_zero_minues = "0";
String duration_zero_seconds = "0";
if (curr_time_minutes > 9)
current_zero_minutes = "";
if (curr_time_seconds > 9)
current_zero_seconds = "";
if (dur_time_minutes > 9)
duration_zero_minues = "";
if (dur_time_seconds > 9)
duration_zero_seconds = "";
seekCurrentDuration.setText(current_zero_minutes + curr_time_minutes + ":" + current_zero_seconds + curr_time_seconds);
seekTotalDuration.setText(duration_zero_minues + dur_time_minutes + ":" + duration_zero_seconds + dur_time_seconds);
}
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(VOLUME_BUTTON)) {
volumeControl();
}
if (intent.getAction().equals(isPlay)) {
boolean show = intent.getBooleanExtra("showPanel", false);
if (show) {
//show Panel here
slideLayout.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
updateTextInfo();
}
} else if (intent.getAction().equals(NOTIFICATION_ACTION)) {
int action = intent.getIntExtra("action", 0);
switch (action) {
case 1:
changePlayBtn();
break;
case 2:
updateTextInfo();
break;
case 3:
updateTextInfo();
break;
case 4:
audioVisualization.release();
break;
default:
break;
}
}
}
};
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
/**
* Defines callbacks for service binding, passed to bindService()
*/
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className,
IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
MusicService.LocalBinder binder = (MusicService.LocalBinder) service;
mService = binder.getService();
mBound = true;
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
public void playBtn(View view) {
if (mBound) {
mService.play();
changePlayBtn();
}
}
private void changePlayBtn() {
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying()) {
playBtn.setImageResource(R.drawable.ic_pause_button);
} else {
playBtn.setImageResource(R.drawable.ic_play_arrow);
}
}
}
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
setSeekbarTime(i, mediaPlayer.getDuration());
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mService.changeSeekTo(seekBar.getProgress());
}
public void previousBtn(View view) {
if (mBound) {
mService.previous();
updateTextInfo();
}
}
public void nextBtn(View view) {
if (mBound) {
mService.next();
updateTextInfo();
}
}
public void startEqualiser() {
try {
vizualizerHandler = VisualizerDbmHandler.Factory.newVisualizerHandler(getApplicationContext(), mediaPlayer);
audioVisualization.linkTo(vizualizerHandler);
} catch (Exception e) {
// TODO change it to snackbar message
Toast.makeText(mService, "Please Give Mic Permission", Toast.LENGTH_SHORT).show();
}
}
public void updateAlbumArt() {
Glide
.with(getApplicationContext())
.load(songThumb.get(musicPosition))
.placeholder(R.drawable.ic_default_icon)
.into(panelAlbumart);
Glide
.with(getApplicationContext())
.load(songThumb.get(musicPosition))
.placeholder(R.drawable.ic_default_icon)
.into(albumArt);
}
}
and this is my MusicService.class
public class MusicService extends MediaBrowserServiceCompat implements
MediaPlayer.OnCompletionListener,
AudioManager.OnAudioFocusChangeListener {
private static final String LOGTAG = "Friday";
public static int musicPosition;
public static MediaPlayer mediaPlayer;
Uri u;
// Binder given to clients
private final IBinder mBinder = new LocalBinder();
Notification status;
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null && intent.getExtras() != null && intent.getExtras().containsKey("pos")) {
musicPosition = intent.getIntExtra("pos", 0);
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.release();
}
if (arrayList != null) {
u = Uri.parse(songPath.get(musicPosition));
mediaPlayer = MediaPlayer.create(getApplicationContext(), u);
}
try {
playSong();
} catch (Exception e) {
next();
}
}
if (intent.getAction() != null) {
if (intent.getAction().equals(Constants.ACTION.PREV_ACTION)) {
previous();
} else if (intent.getAction().equals(Constants.ACTION.PLAY_ACTION)) {
play();
sendAction(1);
} else if (intent.getAction().equals(Constants.ACTION.NEXT_ACTION)) {
next();
}
}
return super.onStartCommand(intent, flags, startId);
}
private void playSong() {
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.start();
showNotification();
}
private void sendAction(int action){
/* 1 for play or pause
* 2 for next
* 3 for previous
*/
Intent intent = new Intent();
intent.setAction(MainContainer.NOTIFICATION_ACTION);
intent.putExtra("action",action);
sendBroadcast(intent);
}
public int getPosition() {
return musicPosition;
}
public int getCurrentDuration() {
return mediaPlayer.getCurrentPosition();
}
public int getDuration() {
return mediaPlayer.getDuration();
}
public void changeSeekTo(int progress) {
mediaPlayer.seekTo(progress);
}
/**
* Class used for the client Binder. Because we know this service always
* runs in the same process as its clients, we don't need to deal with IPC.
*/
public class LocalBinder extends Binder {
public MusicService getService() {
// Return this instance of LocalService so clients can call public methods
return MusicService.this;
}
}
public void next() {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
musicPosition = (musicPosition + 1) % songPath.size();
u = Uri.parse(songPath.get(musicPosition));
mediaPlayer = MediaPlayer.create(getApplicationContext(), u);
playSong();
sendAction(2);
}
}
public void previous() {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
musicPosition = (musicPosition - 1 < 0) ? songPath.size() - 1 : musicPosition - 1;
u = Uri.parse(songPath.get(musicPosition));
mediaPlayer = MediaPlayer.create(getApplicationContext(), u);
playSong();
sendAction(3);
}
}
public void play() {
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
showNotification();
} else {
mediaPlayer.start();
showNotification();
}
}
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
#Override
public void onAudioFocusChange(int i) {
mediaPlayer.stop();
}
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
sendAction(4);
next();
}
#Nullable
#Override
public BrowserRoot onGetRoot(#NonNull String clientPackageName, int clientUid, #Nullable Bundle rootHints) {
return null;
}
#Override
public void onLoadChildren(#NonNull String parentId, #NonNull Result<List<MediaBrowserCompat.MediaItem>> result) {
}
.
.
.
}
I don't know what happened.
Can anybody know about it.
There is already mediaPlayer.setOnCompleteListener inside VisualizerDbmHandler. So, for use it in other places you should use setInnerOnCompletionListener method to add own complete listener to VisualizerDbmHandler
Try do not recreate mediaPlayer but setup new source to it
**My conclusion is**: As you can see in source code of MediaPlayer - it will call onCompletion in cases that unhandled error appears). So, I think, because of recreating mediaPlayer in time, when you call startEqualizer ( recreate visualizerHandler and link it to visualizer view) inside the method linkTo - library call release to previous visualizerHandler and setup variable audioVisualizer to null, that provide you to calling stopRendering on null reference in case of onCompletion calling during to some error during reset/stop/release of MediaPlayer.

Audioplayer not sync with Fragments in ViewPager

I am trying to create a music player in ViewPager when the user swipes, the player should play the next song. The views are updating correctly but the song is not sync with them. For example, it's playing the second song in the first fragment. I tried a lot of things but I'm not able to find where is the issue. Please anyone give me a solution. Thanks in advance.
public class AudioActivity extends AppCompatActivity {
List<PlayerModel> audioList;
int position;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio);
audioList=getIntent().getParcelableArrayListExtra(getString(R.string.SONG_LIST));
position=getIntent().getIntExtra(getString(R.string.SONG_POSITION),0);
final ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
}
AudioActivity.ViewPagerAdapter adapter;
private void setupViewPager(ViewPager viewPager) {
adapter = new AudioActivity.ViewPagerAdapter(getSupportFragmentManager());
AudioPlayerAdapter audioPlayerAdapter=new AudioPlayerAdapter();
for(int i=0;i<audioList.size();i++) {
adapter.addFragment(audioPlayerAdapter.newInstance(audioList, i), AppConstants.AUDIO_PLAYER);
}
viewPager.setAdapter(adapter);
viewPager.setPageTransformer(true, new CubeInTransformer());
}
class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
public void setFragment(Fragment fragment, int position,String title) {
mFragmentList.set(position,fragment);
mFragmentTitleList.set(position,title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
My Fragment
public class AudioPlayerAdapter extends Fragment implements SeekBar.OnSeekBarChangeListener {
Button btnStart, btnStop, btnBind, btnUnbind, btnUpby1, btnUpby10;
TextView textStatus, textIntValue, textStrValue;
Messenger mService = null;
boolean mIsBound;
public static Handler messageHandler;
long duration, currSongPosition;
ImageView displayArt;
TextView playerName;
TextView totTime;
TextView fromTime;
List<PlayerModel> songList;
RecyclerView songRecyclerView;
ImageButton showList;
ImageButton playAudio;
ImageButton pauseAudio;
ImageButton stepForward;
ImageButton stepBackward;
ImageButton shuffleAudio;
ImageButton volumeAudio;
ImageButton repeatAudio;
int songPosition;
SeekBar songProgressBar;
SeekBar volumeSeekBar;
private Intent playIntent;
//binding
private boolean musicBound = false;
private float x1, x2;
static final int MIN_DISTANCE = 150;
//activity and playback pause flags
private boolean paused = false, playbackPaused = false;
private Handler mHandler = new Handler();
private int seekForwardTime = 5000; // 5000 milliseconds
private int seekBackwardTime = 5000; // 5000 milliseconds
private int currentSongIndex = 0;
private boolean isShuffle = false;
private boolean isRepeat = false;
public AudioPlayerAdapter newInstance(List<PlayerModel> playerList, int position) {
AudioPlayerAdapter fragment = new AudioPlayerAdapter();
Bundle b = new Bundle();
b.putParcelableArrayList(AppConstants.SONG_LIST, (ArrayList<? extends Parcelable>) playerList);
b.putInt(AppConstants.SONG_POSITION, position);
fragment.setArguments(b);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View view = inflater.inflate(R.layout.activity_music_player, container, false);
songList = getArguments().getParcelableArrayList(getString(R.string.SONG_LIST));
songPosition = getArguments().getInt(getString(R.string.SONG_POSITION), 0);
LogUtil.error("Song Position",songPosition+"-->"+songList.get(songPosition).getPlayerTitle());
FieldIntialization(view);
if (playIntent == null) {
playIntent = new Intent(getActivity(), MusicService.class);
playIntent.setAction(String.valueOf(MusicService.MSG_FOREGROUND));
playIntent.putParcelableArrayListExtra(getString(R.string.SONG_LIST), (ArrayList<? extends Parcelable>) songList);
playIntent.putExtra(getString(R.string.SONG_POSITION), songPosition);
getActivity().startService(playIntent);
}
DataInitialization(songPosition);
messageHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case MusicService.MSG_SET_INT_VALUE:
break;
case MusicService.MSG_PLAY:
LogUtil.error("Pause", "Pause");
playAudio.setImageResource(R.drawable.ic_pause_white_24dp);
break;
case MusicService.MSG_PAUSE:
LogUtil.error("Play", "Play");
playAudio.setImageResource(R.drawable.ic_play_white_24dp);
break;
case MusicService.MSG_NEXT:
songPosition = msg.getData().getInt(getString(R.string.SONG_POSITION));
LogUtil.error("SonPos", String.valueOf(songPosition));
updatePlayerView(songPosition);
break;
case MusicService.MSG_PREVIOUS:
songPosition = msg.getData().getInt(getString(R.string.SONG_POSITION));
LogUtil.error("SonPos", String.valueOf(songPosition));
updatePlayerView(songPosition);
break;
case MusicService.MSG_UPDATE_SEEKBAR:
duration = msg.getData().getLong(getString(R.string.SONG_DURATION));
currSongPosition = msg.getData().getLong(getString(R.string.SONG_CURR_DURATION));
break;
case MusicService.MSG_SHUFFLE_OFF:
Toast.makeText(getActivity(), "Shuffle Off", Toast.LENGTH_SHORT).show();
break;
case MusicService.MSG_SHUFFLE_ON:
Toast.makeText(getActivity(), "Shuffle On", Toast.LENGTH_SHORT).show();
break;
case MusicService.MSG_REPEAT_ON:
Toast.makeText(getActivity(), "Repeat On", Toast.LENGTH_SHORT).show();
break;
case MusicService.MSG_REPEAT_OFF:
Toast.makeText(getActivity(), "Repeat Off", Toast.LENGTH_SHORT).show();
break;
case MusicService.MSG_CLOSE:
getActivity().finish();
break;
case MusicService.MSG_STOP:
break;
default:
super.handleMessage(msg);
}
}
};
return view;
}
/* #Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
*//* outState.putString("textStatus", textStatus.getText().toString());
outState.putString("textIntValue", textIntValue.getText().toString());
outState.putString("textStrValue", textStrValue.getText().toString());*//*
}
private void restoreMe(Bundle state) {
if (state != null) {*//*
textStatus.setText(state.getString("textStatus"));
textIntValue.setText(state.getString("textIntValue"));
textStrValue.setText(state.getString("textStrValue"));*//*
}
}*/
public void stopService() {
getActivity().stopService(new Intent(getActivity(), MusicService.class));
}
private void sendMessageToService(int action) {
Intent startIntent = new Intent(getActivity(), MusicService.class);
startIntent.setAction(String.valueOf(action));
getActivity().startService(startIntent);
}
private void sendMessageToServiceWithData(int action, int currPosition) {
Intent startIntent = new Intent(getActivity(), MusicService.class);
startIntent.setAction(String.valueOf(action));
startIntent.putExtra(getString(R.string.SEEK_POSITION), currPosition);
getActivity().startService(startIntent);
}
private void FieldIntialization(View view) {
songProgressBar = (SeekBar) view.findViewById(R.id.seekBar);
volumeSeekBar = (SeekBar) view.findViewById(R.id.volumeSeekBar);
displayArt = (ImageView) view.findViewById(R.id.songImage);
playerName = (TextView) view.findViewById(R.id.songName);
totTime = (TextView) view.findViewById(R.id.endTime);
fromTime = (TextView) view.findViewById(R.id.startTime);
songRecyclerView = (RecyclerView) view.findViewById(R.id.songRecyclerView);
showList = (ImageButton) view.findViewById(R.id.showList);
stepForward = (ImageButton) view.findViewById(R.id.step_next);
stepBackward = (ImageButton) view.findViewById(R.id.step_prev);
shuffleAudio = (ImageButton) view.findViewById(R.id.shuffle);
repeatAudio = (ImageButton) view.findViewById(R.id.repeat);
playAudio = (ImageButton) view.findViewById(R.id.play_pause);
volumeAudio = (ImageButton) view.findViewById(R.id.speaker);
playAudio.setImageResource(R.drawable.ic_pause_white_24dp);
songRecyclerView.addItemDecoration(new MarginDecoration(getActivity()));
songRecyclerView.setHasFixedSize(true);
songRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(),
LinearLayoutManager.HORIZONTAL, false));
SongRecyclerAdapter songRecyclerAdapter = new SongRecyclerAdapter(songList,
getActivity()
);
if (songList.size() > 0) {
LinearLayout.LayoutParams lp =
new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
songRecyclerView.setLayoutParams(lp);
} else {
LinearLayout.LayoutParams lp =
new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
songRecyclerView.setLayoutParams(lp);
}
songRecyclerView.setAdapter(songRecyclerAdapter);
songRecyclerAdapter.setOnDataChangeListener(new onRefreshFavListener() {
#Override
public void onFavRefresh(int position) {
playIntent = new Intent(getActivity(), MusicService.class);
playIntent.setAction(String.valueOf(MusicService.MSG_FOREGROUND));
playIntent.putParcelableArrayListExtra(getString(R.string.SONG_LIST), (ArrayList<? extends Parcelable>) songList);
playIntent.putExtra(getString(R.string.SONG_POSITION), position);
getActivity().startService(playIntent);
updatePlayerView(position);
}
});
}
private void DataInitialization(final int position) {
showList.setBackgroundResource(R.drawable.ic_up_white_24dp);
showList.setTag(R.drawable.ic_up_white_24dp);
songRecyclerView.setVisibility(View.GONE);
LogUtil.error("Update",position+"-->"+songList.get(position));
updatePlayerView(position);
showList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if ((int) showList.getTag() == R.drawable.ic_up_white_24dp) {
showList.setBackgroundResource(R.drawable.ic_down_white_24dp);
showList.setTag(R.drawable.ic_down_white_24dp);
songRecyclerView.setVisibility(View.VISIBLE);
} else {
showList.setBackgroundResource(R.drawable.ic_up_white_24dp);
showList.setTag(R.drawable.ic_up_white_24dp);
songRecyclerView.setVisibility(View.GONE);
}
}
});
songProgressBar.setOnSeekBarChangeListener(this);
final AudioManager audioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
volumeSeekBar.setMax(audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
volumeSeekBar.setProgress(audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC));
volumeSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar arg0) {
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
}
#Override
public void onProgressChanged(SeekBar arg0, int progress, boolean arg2) {
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
progress, 0);
}
});
playAudio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
sendMessageToService(MusicService.MSG_CHECK_PLAYING_STATUS);
}
});
stepForward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMessageToService(MusicService.MSG_NEXT);
}
});
stepBackward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMessageToService(MusicService.MSG_PREVIOUS);
}
});
shuffleAudio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMessageToService(MusicService.MSG_SHUFFLE);
}
});
repeatAudio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMessageToService(MusicService.MSG_REPEAT);
}
});
}
public void updatePlayerView(int songIndex) {
playAudio.setImageResource(R.drawable.ic_pause_white_24dp);
LogUtil.error("Song List",songIndex+"-->"+songList.get(songIndex).getPlayerTitle());
playerName.setText(songList.get(songIndex).getPlayerTitle());
totTime.setText(Utility.convertDuration(Long.parseLong(songList.get(songIndex).getPlayerDuration())));
Cursor cursor = getActivity().getContentResolver().query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Audio.Albums._ID, MediaStore.Audio.Albums.ALBUM_ART},
MediaStore.Audio.Albums._ID + "=?",
new String[]{String.valueOf(songList.get(songIndex).getPlayerAlbumId())},
null);
cursor.moveToFirst();
displayArt.setScaleType(ImageView.ScaleType.FIT_XY);
displayArt.setImageBitmap(Constants.getDefaultAlbumArt(getActivity(), songList.get(songIndex).getPlayerAlbumId()));
songProgressBar.setProgress(0);
songProgressBar.setMax(100);
// Updating progress bar
updateProgressBar();
}
public void updateProgressBar() {
// mHandler.postDelayed(mUpdateTimeTask, 100);
}
/**
* Background Runnable thread
*/
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
sendMessageToService(MusicService.MSG_UPDATE_SEEKBAR);
// Displaying Total Duration time
totTime.setText("" + Utility.milliSecondsToTimer(duration));
// Displaying time completed playing
fromTime.setText("" + Utility.milliSecondsToTimer(currSongPosition));
// Updating progress bar
int progress = (int) (Utility.getProgressPercentage(currSongPosition, duration));
//Log.d("Progress", ""+progress);
songProgressBar.setProgress(progress);
// Running this thread after 100 milliseconds
mHandler.postDelayed(this, 100);
}
};
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
}
/**
* When user starts moving the progress handler
*/
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// remove message Handler from updating progress bar
// mHandler.removeCallbacks(mUpdateTimeTask);
}
/**
* When user stops moving the progress hanlder
*/
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// mHandler.removeCallbacks(mUpdateTimeTask);
int currentPosition = Utility.progressToTimer(seekBar.getProgress(), (int) duration);
sendMessageToServiceWithData(MusicService.MSG_SEEK, currentPosition);
// update timer progress again
updateProgressBar();
}
}

Categories

Resources