Application restart suddenly - android

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
}

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?

In Exoplayer,How to reload and resume playback automatically?

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

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();
}
}

Android: Seekbar progress error while playing Song?

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();
}

How can I make a view invisible after 3 seconds?

I am using a handler in the adapter file to make the view invisible after 3 sconds, but it does not update the view. Where is my problem and how can I fix it?
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
try {
Bundle bun = getIntent().getExtras();
if (!bun.isEmpty()) {
selecte_pos = bun.getInt("pos");
}
} catch (Exception e) {
}
Display display = getWindowManager().getDefaultDisplay();
width = display.getWidth();
height = display.getHeight();
System.out.println("full image activity");
ar = getIntent().getStringArrayListExtra("PhotoList");
System.out.println("full list size: " + ar.size());
imageLoader = new ImageLoader(this);
setContentView(R.layout.full_image_view_layout);
mPager = (ViewPager) findViewById(R.id.full_image_view_pager);
adapter = new MyPagerAdapter();
mPager.setAdapter(adapter);
mPager.setCurrentItem(selecte_pos);
}
class MyPagerAdapter extends PagerAdapter {
public int getCount() {
return ar.size();
}
Handler pagerHandler=new Handler(){
public void handleMessage(Message msg){
if(msg.what==1){
//if (istimer == true) {
System.out.println("page handler");
System.out.println("");
Toast.makeText(getApplicationContext(), "hi", 1).show();
shareLayout.setVisibility(View.INVISIBLE);
adapter.notifyDataSetChanged();
//}
}
}
};
#Override
public Object instantiateItem(ViewGroup container, final int position) {
System.out.println("view page clciking");
LayoutInflater layoutInflater = (LayoutInflater) container
.getContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View v = layoutInflater.inflate(R.layout.imageview, null);
try {
final ImageView imageView = (ImageView) v
.findViewById(R.id.full_pager_adapter_iv);
shareLayout = (LinearLayout) v.findViewById(R.id.buttonslayout);
shareLayout.setVisibility(View.VISIBLE);
imageLoader.DisplayImage(ar.get(position), imageView);
if (first) {
System.out.println("fisr condition");
first = false;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
pagerHandler.sendEmptyMessage(1);
//adapter.notifyDataSetChanged();
}
}, SPLASH_DISPLAY_LENGHT);
}
/**if(istimer1== true)
{
System.out.println("else part");
istimer1 = false;
shareLayout.setVisibility(View.VISIBLE);
adapter.notifyDataSetChanged();
}**/
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("img clicking");
if (shareLayout.getVisibility() == View.INVISIBLE) {
System.out.println("invisible");
istimer = false;
istimer1 = true;
shareLayout.setVisibility(View.VISIBLE);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
//istimer = true;
//istimer1 = false;
pagerHandler.sendEmptyMessage(1);
//adapter.notifyDataSetChanged();
}
}, SPLASH_DISPLAY_LENGHT);
adapter.notifyDataSetChanged();
}
if (shareLayout.getVisibility() == View.VISIBLE) {
System.out.println("visible");
istimer = true;
istimer1 = false;
shareLayout.setVisibility(View.INVISIBLE);
adapter.notifyDataSetChanged();
}
}
});
LinearLayout btnshare = (LinearLayout) v
.findViewById(R.id.btnshare);
btnshare.setTag(position);
btnshare.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int pos = (Integer) v.getTag();
String s = ar.get(pos);
// String s = bean.getImagePath();
File file = new File(s);
Intent sendMailIntent = new Intent(Intent.ACTION_SEND);
sendMailIntent.setType("image/jpeg");
sendMailIntent.putExtra(
android.content.Intent.EXTRA_TEXT, "");
sendMailIntent.putExtra(Intent.EXTRA_STREAM,
Uri.fromFile(file));
/* sendMailIntent.setType("image/*"); */
startActivity(Intent.createChooser(sendMailIntent, ""));
}
});
} catch (Exception e) {
}
((ViewPager) container).addView(v, 0);
return v;
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
((ViewPager) collection).removeView((View) view);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public int getItemPosition(Object object) {
// TODO Auto-generated method stub
return POSITION_NONE;
}
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
finish();
}
private Handler mTimerHandler = new Handler();
private void stopTimer() {
if (mTimer1 != null) {
mTimer1.cancel();
mTimer1.purge();
}
}
private void startTimer() {
mTimer1 = new Timer();
mTt1 = new TimerTask() {
public void run() {
mTimerHandler.post(new Runnable() {
public void run() {
System.out.println("timesatrs");
// TODO
if (shareLayout.getVisibility() == View.VISIBLE) {
System.out.println("time completed");
shareLayout.setVisibility(View.INVISIBLE);
}
}
});
}
};
mTimer1.schedule(mTt1, 6000);
}
}
getWindow().getDecorView().getRootView().postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
yourView.setVisibility(View.VISIBLE);
}
}, 5000);
// Call this when u initalise view in onCreate
You don't need to create a new handler every time, when you need to send message to handler which you already created. You can send delayed message like this pagerHandler.sendEmptyMessageDelayed(1, SPLASH_DISPLAY_LENGHT);
And are you sure, you are trying to update current shareLayout ?
Add the below coding in your class file.
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
view.setVisibility(View.GONE); }
}, 3000);
This will helps you in achieving what you want.

Categories

Resources