Audioplayer not sync with Fragments in ViewPager - android

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

Related

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
}

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

Fragment loads network data which was wrong in the first time

When my first to get the data from the first tab of fragment,it was something wrong.And through the web page to open it ,these data is normal.
public class OnlineAllInsuranceFragment extends Fragment implements OnListViewListener {
private ScrollListView MainView;
private BasicAdapter2 Adapter;
private Integer Step=10;
private Integer Start=0;
private Integer End=Step;
private Handler handler,handler2;
private DataTable dTable;
public static String SelectCode="";
private static final int OVER = 1;
private String polnum;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_online_insurance,container,false);
handler2 = new Handler();
new Thread(new Runnable() {
public void run() {
Looper.prepare();
handler2.post(runSetList);
Looper.loop();
}
}).start();
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
this.MainView=(ScrollListView)getView().findViewById(R.id.contractlistView1);
this.MainView.setPullLoadEnable(true);
this.MainView.setXListViewListener(this);
}
private void SetList(){
Start=0;
End=3;
this.dTable = new DataTable(getActivity(),"newcontract");
this.dTable.Load("AgentCode="+OnlineAllInsuranceFragment.SelectCode+"&Start=0&End="+Step);
if(dTable.GetRowCount()>0){
this.MainView.setVisibility(0);
this.StartData(this.dTable.GetList(),R.layout.userlistitem4);
}else{
this.MainView.setVisibility(8);
TextView NullView=(TextView) getView().findViewById(R.id.listViewNull1);
NullView.setVisibility(0);
NullView.setHeight(50);
}
}
private void StartData(ArrayList<Map<String, Object>> List, int Resource) {
this.Adapter = new BasicAdapter2(getActivity(), List, Resource,
new String[] { "Provider", "ProdName", "NoType", "ContractNo",
"AcceptTime", "ContractStatus", "Premium", "Gain",
"ReceivedPremium", "Name" },
new int[] {R.id.contractitem_label_Provider,
R.id.contractitem_label_ProdName,
R.id.contract_label_cno,
R.id.contractitem_label_contractNo,
R.id.contractitem_label_acceptTime,
R.id.contractitem_label_contractStatus,
R.id.contractitem_label_premium,
R.id.contractitem_label_feilv,
R.id.contractitem_label_receivedPremium,
R.id.contractitem_label_Name },
new int[] {R.id.listitem_button_look, R.id.listitem_button_pay,
R.id.listitem_main1,R.id.contractitem_label_companyImage,R.id.contractitem_label_payImage },
new BasicAdapter2.ListAdapterListener() {
#Override
public void onClickAtOKButton(View v) {
String company = dTable.GetValue((Integer)v.getTag(), 1).toString();//产品名
String status = dTable.GetValue((Integer)v.getTag(), 4).toString();//保单状态
switch (v.getId()) {
case R.id.listitem_button_pay:
polnum = dTable.GetValue((Integer)v.getTag(), 3).toString();
String numPol = dTable.GetValue((Integer)v.getTag(), 2).toString();//是“保单号”还是“投保单号”
if (numPol.contains("aa")) {
Intent intent = new Intent();
intent.setClass(getActivity(),PolicyInformationActivity.class);
intent.putExtra("polnum", polnum);
startActivity(intent);
} else if (numPol.contains("bb")) {
toastDialog();
}
break;
case R.id.listitem_button_look:
Toast.makeText(getActivity(),"...", Toast.LENGTH_SHORT).show();
LogUtil.e("company+status", company+"=="+status);
break;
case R.id.listitem_main1:
break;
}
}
},
new BasicAdapter2.VisibleAdapterListener() {
#Override
public int onSetVisible(View v) {
String company = dTable.GetValue((Integer)v.getTag(), 1).toString();//产品名
String status = dTable.GetValue((Integer)v.getTag(), 4).toString();//保单状态
LogUtil.e("status","=="+status);
int drawId;
switch (v.getId()) {
case R.id.contractitem_label_companyImage:
if ( company.contains("cc") ) {
drawId = R.drawable.taikang2x;
return drawId;
} else if (company.contains("dd") ) {
drawId = R.drawable.youban2x;
return drawId;
}
break;
case R.id.contractitem_label_payImage:
if ( status.equals("ee") ) {
drawId = R.drawable.security2x;
return drawId;
} else if (status.equals("ff")) {
drawId = R.drawable.nopay2x;
return drawId;
} else if ( status.equals("gg")) {
drawId = R.drawable.invalid2x;
return drawId;
}
break;
case R.id.listitem_button_pay:
if (company.contains("hh") && status.equals("ii")) {
return 0;
} else if (company.contains("jj") || status.equals("kk")) {
return 4;
}
break;
}
return 99;
}
});
handler = new Handler();
this.Adapter.Start(this.MainView);
this.Start += Step;
this.End += Step;
}
private void LoadData(){
this.dTable.Load("AgentCode="+OnlineAllInsuranceFragment.SelectCode+"&Start="+Start+"&End="+End);
this.Start += Step;
this.End += Step;
}
private void stopRefresh() {
this.MainView.stopRefresh();
this.MainView.setRefreshTime("just");
}
private void stopLoadMore() {
this.MainView.stopLoadMore();
}
#Override
public void onRefresh() {
handler.postDelayed(new Runnable() {
#Override
public void run() {
SetList();
stopRefresh();
}
}, 2000);
}
#Override
public void onLoadMore() {
handler.postDelayed(new Runnable() {
#Override
public void run() {
LoadData();
stopLoadMore();
}
}, 2000);
}
#SuppressLint("HandlerLeak")
Handler handler1 = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case OVER:
Control.ExitDialog();
break;
default:
break;
}
super.handleMessage(msg);
}
};
Runnable runSetList = new Runnable() {
#Override
public void run() {
SetList();
}
};
private void toastDialog() {
CustomDialog.Builder builder = new CustomDialog.Builder(getActivity());
builder.setTitle("xx");
builder.setMessage("yy");
builder.setNegativeButton("vv", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.setPositiveButton("ww", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Control.StartDialog(getActivity());
new Thread(new Runnable() {
public void run() {
Looper.prepare();
startActivity(new Intent(getActivity(),HomeActivity.class));
send();
handler1.sendEmptyMessage(1);
Looper.loop();
}
}).start();
}
});
Dialog noticeDialog = builder.create();
noticeDialog.setCancelable(false);
noticeDialog.setCanceledOnTouchOutside(false);
noticeDialog.show();
}
private void send() {
}
}
And when I keep away from this Fragment then comeback,the data become normal,too.The data is not normal just when my first in the Fragment.

Seekbar doesnt play from the point where it is dragged by the user

I have the problem with the seekbar thumb, although I have added every necessary codes for it to work. still the seekbar thumb doesn't play from the point dragged by the user. instead the thumb positioned itself back to the point it was last playing though. Any help will be appreciated.
plus = (ImageButton) findViewById(R.id.imageButton2);
minus = (ImageButton) findViewById(R.id.imageButton4);
player = MediaPlayer.create(this, R.raw.songnames);
player.setLooping(false);
im = (ImageButton) this.findViewById(R.id.imageButton3);
seekbar = (SeekBar) findViewById(R.id.mantraProgressBar);
seekbar.setVisibility(ProgressBar.VISIBLE);
seekbar.setProgress(0);
seekbar.setMax(player.getDuration());
new Thread(this).start();
im.setOnClickListener(this);
player.start();
im.setImageResource(R.drawable.pause_tran);
Toast.makeText(this, isPlaying, Toast.LENGTH_LONG).show();
plus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int cu = player.getCurrentPosition();
player.seekTo(cu - 5000);
}
});
minus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int cu = player.getCurrentPosition();
player.seekTo(cu + 5000);
}
});
}
#Override
public void onClick(View arg0) {
if (arg0.getId() == R.id.imageButton3) {
if (player.isPlaying()) {
player.pause();
Toast.makeText(this, notPlaying, Toast.LENGTH_LONG).show();
ImageButton img1 = (ImageButton) this.findViewById(R.id.imageButton3);
img1.setImageResource(R.drawable.play_tran);
} else {
player.start();
Toast.makeText(this, isPlaying, Toast.LENGTH_LONG).show();
ImageButton img1 = (ImageButton) this.findViewById(R.id.imageButton3);
img1.setImageResource(R.drawable.pause_tran);
}
}
}
#Override
public void run() {
int currentPosition = 0;
String s;
int total = player.getDuration();
while (player != null && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = player.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seekbar.setProgress(currentPosition);
}
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
player.seekTo(progress);
seekbar.setProgress(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
public class MainActivity extends AppCompatActivity {
private MyVideoView mVV;
private Handler mhandler;
private SeekBar seekbar;
private int duration;
private int backPositon = 0;
private int currentPosition;
private SharedPreferences sp;
private MediaController controller;
private TextView tv_curr;
private TextView tv_duration;
private Handler handler;
private boolean mExit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mVV = (MyVideoView) findViewById(R.id.vv);
seekbar = (SeekBar) findViewById(R.id.seekbar);
tv_curr = (TextView) findViewById(R.id.tv_currtime);
tv_duration = (TextView) findViewById(R.id.tv_duration);
//get duration of video
getDuration();
//video start
playVideo();
//get current time
getCurrentDuration();
//listener
initEvent();
}
private void initHanlder() {
handler=new Handler(){
#Override
public void handleMessage(Message msg) {
if (msg.what==0x123){
tv_curr.setText(timeFormat(mVV.getCurrentPosition()));
seekbar.setProgress(mVV.getCurrentPosition());
}
if(msg.what==0x133){
int changedProgress = msg.arg1;
tv_curr.setText(timeFormat(changedProgress));
mVV.seekTo(changedProgress);
seekbar.setProgress(changedProgress);
mVV.start();
}
}
};
new Thread(new Runnable() {
#Override
public void run() {
while (mVV.getCurrentPosition()<duration){
Message message = Message.obtain();
message.what=0x123;
handler.sendMessage(message);
SystemClock.sleep(1000);
if(mExit){
break;
}
}
}
}).start();
}
private void getDuration() {
mVV.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
duration = mVV.getDuration();
timeFormat(duration);
Log.d("TAG", "---duration" + timeFormat(duration));
seekbar.setMax(duration);
//TextView time
tv_duration.setText(timeFormat(duration));
//init handler
initHanlder();
}
});
}
private String timeFormat(int time) {
StringBuilder mFormatBuilder;
Formatter mFormatter;
mFormatBuilder = new StringBuilder();
mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());
int totalSeconds = time / 1000;
int seconds = totalSeconds % 60;
int minutes = (totalSeconds / 60) % 60;
int hours = totalSeconds / 3600;
mFormatBuilder.setLength(0);
if (hours > 0) {
return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
} else {
return mFormatter.format("%02d:%02d", minutes, seconds).toString();
}
}
private void playVideo() {
File file = new File(Environment.getExternalStorageDirectory(), "cgx_video/db.mp4");
if (!file.exists()) {
file.mkdir();
}
Log.d("TAG", file.toString());
mVV.setVideoPath(file.getPath());
mVV.start();
}
private void initEvent() {
seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
currentPosition=progress;
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
mVV.pause();
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
if(handler!=null){
Message message = Message.obtain();
message.what=0x133;
message.arg1=currentPosition;
handler.sendMessage(message);
}
}
});
}
#Override
protected void onPause() {
super.onPause();
Log.d("TAG", "---onPause");
mVV.pause();
backPositon = mVV.getCurrentPosition();
Log.d("TAG", "backPositon:" + backPositon);
}
#Override
protected void onStop() {
super.onStop();
Log.d("TAG", "---onStop");
}
#Override
protected void onResume() {
super.onResume();
Log.d("TAG", backPositon + "---backPositon");
mVV.seekTo(backPositon);
mVV.start();
}
#Override
protected void onDestroy() {
//in case of leak of memeroy
mExit=true;
super.onDestroy();
}
}

Stop repetitive radio streaming android

I have a problem with my app. I have an app that streams radio stations. The stream starts when the user clicks on a item of the gridview. To stop the stream i made a button(stop) that appears when the stream starts. The problem appears when the user click many times the same item of the gridview because when click on stop button the stream don't stop, how can i solve that ?
public class MainActivity extends ActionBarActivity {
private GridView grid;
private InterstitialAd interstitial, inter2;
private TextView name;
private ProgressBar bar;
private ImageView stop;
private RelativeLayout rela;
private RadioPlayerManager mRadioManager;
private String[] web = {
"Radio RDS",
"Rai 1 Radio",
"Radio R101",
"Radio RTL102.5",
"Radio Virgin",
"Radio RMC",
"Radio Antenna1",
"Radio 105",
"Radio Milano",
"Radio Onda Libera",
};
private int[] imageId = {
R.drawable.playy,
R.drawable.playy,
R.drawable.playy,
R.drawable.playy,
R.drawable.playy,
R.drawable.playy,
R.drawable.playy,
R.drawable.playy,
R.drawable.playy,
R.drawable.playy,
R.drawable.playy,
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRadioManager = new RadioPlayerManager();
rela = (RelativeLayout) findViewById(R.id.relativeLayout);
bar = (ProgressBar) findViewById(R.id.progressBar);
stop = (ImageView) findViewById(R.id.imageView);
name = (TextView) findViewById(R.id.textView3);
grid = (GridView) findViewById(R.id.gridView1);
bar.setVisibility(View.GONE);
rela.setVisibility(View.GONE);
CustomGrid adapter = new CustomGrid(MainActivity.this, web, imageId);
grid.setAdapter(adapter);
ads();
listeners();
firstRun();
animations();
}
private void ads() {
interstitial = new InterstitialAd(this);
interstitial.setAdUnitId("ca-app-pub-5426545253667840/9595287619");
inter2 = new InterstitialAd(this);
inter2.setAdUnitId("ca-app-pub-5426545253667840/9595287619");
AdRequest adRequest1 = new AdRequest.Builder().build();
inter2.loadAd(adRequest1);
inter2.setAdListener(new AdListener() {
public void onAdLoaded() {
displayInterstitial();
}
});
AdRequest adRequest2 = new AdRequest.Builder().build();
interstitial.loadAd(adRequest2);
interstitial.setAdListener(new AdListener() {
public void onAdLoaded() {
displayInterstitial();
}
public void onAdClosed() {
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR).build();
// Load the interstitial ad again
interstitial.loadAd(adRequest);
}
});
}
public void displayInterstitial() {
if (interstitial.isLoaded()) {
}
}
private void firstRun() {
boolean firstrun = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getBoolean("firstrun", true);
if (firstrun) {
new android.app.AlertDialog.Builder(this)
.setTitle("Radio Italia") //set the Title text
.setMessage("Ciao! " +
"Con Radio Italia puoi ascoltare la maggior parte delle radio italiane gratis, senza nessun costo." +
"Radio Italia ha al suo interno degli spot(ads) che aiutano lo sviluppatore a continuare il suo lavoro." +
"Se ti piace l'app non dimenticarti di darli 5 stele su Play Store. Grazie!")
.setNeutralButton("OK!", null).show(); //Sets the button type
}
// Save the state with shared preferences
getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.edit()
.putBoolean("firstrun", false)
.commit();
}
private void listeners() {
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
rela.setVisibility(View.VISIBLE);
bar.setVisibility(View.VISIBLE);
if (position == 0) {
mRadioManager.play("http://www.rds.it:8000/stream", mediaPlayerCallback);
name.setText("Stai ascoltando RDS");
bar.setVisibility(View.INVISIBLE);
}
if (position == 1) {
mRadioManager.play("http://icestreaming.rai.it/1.mp3", mediaPlayerCallback);
name.setText("Stai ascoltando Rai 1");
bar.setVisibility(View.INVISIBLE);
}
if (position == 2) {
mRadioManager.play("http://str30.creacast.com/r101a", mediaPlayerCallback);
name.setText("Stai ascoltando R101");
bar.setVisibility(View.INVISIBLE);
}
if (position == 3) {
mRadioManager.play("http://shoutcast.rtl.it:3010/stream/1/", mediaPlayerCallback);
name.setText("Stai ascoltando RTL102.5");
bar.setVisibility(View.INVISIBLE);
}
if (position == 4) {
mRadioManager.play("http://shoutcast.unitedradio.it:1301/", mediaPlayerCallback);
name.setText("Stai ascoltando Virgin Radio");
bar.setVisibility(View.INVISIBLE);
}
if (position == 5) {
mRadioManager.play("http://shoutcast.unitedradio.it:1103/", mediaPlayerCallback);
name.setText("Stai ascoltando RMC");
bar.setVisibility(View.INVISIBLE);
}
if (position == 6) {
mRadioManager.play("http://s3.mediastreaming.it:7568/", mediaPlayerCallback);
name.setText("Stai ascoltando Antenna1");
bar.setVisibility(View.INVISIBLE);
}
if (position == 7) {
mRadioManager.play("http://shoutcast.unitedradio.it:1101/", mediaPlayerCallback);
name.setText("Stai ascoltando Radio105");
bar.setVisibility(View.INVISIBLE);
}
if (position == 8) {
mRadioManager.play("http://sh1.inmystream.info:8175/", mediaPlayerCallback);
name.setText("Stai ascoltando Radio Milano");
bar.setVisibility(View.INVISIBLE);
}
if (position == 9) {
mRadioManager.play("http://s6.mediastreaming.it:9064/", mediaPlayerCallback);
name.setText("Stai ascoltando Onda Libera");
bar.setVisibility(View.INVISIBLE);
} else {
mRadioManager.stop();
}
}
;
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mRadioManager.stop();
rela.setVisibility(View.INVISIBLE);
interstitial.show();
}
});
}
private void animations() {
Animation anim = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.abc_fade_in);
anim.setDuration(1500);
name.setAnimation(anim);
anim.setRepeatCount(Animation.INFINITE);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
#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.
switch (item.getItemId()) {
case R.id.share:
shareIt();
break;
case R.id.play:
gp();
break;
case R.id.like:
fb();
break;
case R.id.plus:
plus();
break;
}
return true;
}
private void fb() {
try {
Intent fb = new Intent(Intent.ACTION_VIEW, Uri.parse("fb://page/315814045239841"));
startActivity(fb);
} catch (Exception e) {
Intent fb = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/Denis-Projects-315814045239841/"));
startActivity(fb);
}
}
private void shareIt() {
String shareBody = "Ascult cele mai tari posturi de manele cu aplicatia Radio manele 2016. Descarc-o si tu,e gratuit! https://play.google.com/store/apps/details?id=com.denisprojects.radiomanele2016";
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Radio manele 2016");
sharingIntent.putExtra(Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Distribuie"));
}
private void gp() {
// TODO Auto-generated method stub
Intent gp = new Intent(Intent.ACTION_VIEW);
gp.setData(Uri.parse("https://play.google.com/store/apps/developer?id=DenisProjects"));
startActivity(gp);
}
private void plus() {
Intent plus = new Intent(Intent.ACTION_VIEW);
plus.setData(Uri.parse("https://plus.google.com/u/0/102131527060290623635"));
startActivity(plus);
}
private MediaPlayerCallback mediaPlayerCallback = new MediaPlayerCallback() {
#Override
public void onMetadata(String value){
}
#Override
public void onError() { rela.setVisibility(View.VISIBLE);
name.setText("Errore!Scegli altra radio");
}
#Override
public void onBuffering() {
}
#Override
public void onPlaying() {
}
#Override
public void onStopped() {
}
};
}
public class RadioPlayerManager {
private MultiPlayer mMultiPlayer;
private MediaPlayerCallback mCallback;
private static String TAG = RadioPlayerManager.class.getSimpleName();
public RadioPlayerManager() {
try {
java.net.URL.setURLStreamHandlerFactory(new java.net.URLStreamHandlerFactory() {
public java.net.URLStreamHandler createURLStreamHandler(String protocol) {
Log.d(TAG, "Asking for stream handler for protocol: '" + protocol + "'");
if ("icy".equals(protocol))
return new com.spoledge.aacdecoder.IcyURLStreamHandler();
return null;
}
});
} catch (Throwable t) {
Log.w(TAG, "Cannot set the ICY URLStreamHandler - maybe already set ? - " + t);
}
}
public void play(String url, MediaPlayerCallback callback) {
mCallback = callback;
mMultiPlayer = new MultiPlayer(mPlayerCallback, MultiPlayer.DEFAULT_AUDIO_BUFFER_CAPACITY_MS, MultiPlayer.DEFAULT_DECODE_BUFFER_CAPACITY_MS);
mMultiPlayer.playAsync(url);
mCallback.onBuffering();
}
public void stop() {
mMultiPlayer.stop();
}
private PlayerCallback mPlayerCallback = new PlayerCallback() {
#Override
public void playerStarted() {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
mCallback.onPlaying();
}
});
}
#Override
public void playerPCMFeedBuffer(boolean b, int i, int i1) {
}
#Override
public void playerStopped(int i) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
mCallback.onStopped();
}
});
}
#Override
public void playerException(Throwable throwable) {
mCallback.onError();
}
#Override
public void playerMetadata(String key, final String value) {
if ("StreamTitle".equals(key)) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
mCallback.onMetadata(value);
}
});
}
}
#Override
public void playerAudioTrackCreated(AudioTrack audioTrack) {
}
public boolean isPlaying(){
mMultiPlayer.stop();
return true;
}
};
}
public interface MediaPlayerCallback {
void onMetadata(String value);
void onError();
void onBuffering();
void onPlaying();
void onStopped();
}
No one knows how to do that ?
it is better to not start playing if the selected gridview item is already playing. so you can store the value of playing gridview item and check it before you call mRadioManager.play("http://s6.mediastreaming.it:9064/", mediaPlayerCallback);

Categories

Resources