I wanted to implement the start / pause buttons in notification, but the getCurrentPosition method does not give out a real number, only 0.

public void songStream(int songPos){ player.reset(); songPosition = songPos; playSong = songList.get(songPosition); currSong = playSong.getId(); Log.i(TAG,"Artist "+playSong.getArtist()+" Song "+playSong.getTitle()); trackUri = ContentUris.withAppendedId (android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, currSong); try { player.setDataSource(getApplicationContext(),trackUri); } catch (IOException e) { e.printStackTrace(); } player.setAudioStreamType(AudioManager.STREAM_MUSIC); try { player.prepare(); } catch (IOException e) { e.printStackTrace(); } player.start(); } 

Here I am processing clicks from notofication:

 @Override public int onStartCommand(Intent intent, int flags, int startId){ songStream(songPosition); showNotification(); if (intent.getAction().equals(Constants.PREV_ACTION)){ try{ songStream(songPosition-1); } catch (ArrayIndexOutOfBoundsException e){ songStream(songList.size()-1); } count=0; showNotification(); Log.i(TAG, "Clicked Previous"); } else if (intent.getAction().equals(Constants.PLAY_ACTION)) { player.pause(); pausePosition=player.getCurrentPosition(); ++count; showNotification(); Log.i(TAG, "Clicked Play Current position "+pausePosition); } else if (intent.getAction().equals(Constants.PAUSE_ACTION)) { player.seekTo(pausePosition); player.start(); ++count; showNotification(); Log.i(TAG, "Clicked Pause"); } else if (intent.getAction().equals(Constants.NEXT_ACTION)){ try{ songStream(songPosition+1); }catch (IndexOutOfBoundsException e){ songStream(0); } count=0; showNotification(); Log.i(TAG, "Clicked Next");} return START_NOT_STICKY; } 

I assigned the pausePosition variable to player.getCurrentPosition, i.e. after pressing the start button, the song should play from the moment the pause button was pressed. The question is: what prevents getCurrentPosition from getting a real position in the song, and not 0?

  • one
    In onStartCommand , you are the first to make an unconditional call to songStream(songPosition); in which the player resets and loads the same track first. - woesss
  • That is, you need to set the condition under which the songStream will be called only if the player is not active? - Max Charlin
  • In principle, you can transfer it to the condition when the user clicked on the play (you have PAUSE_ACTION for some reason), otherwise it is either called or not required. - woesss
  • Note on the code: try-catch on an IndexOutOfBoundsException is not a good solution, a better condition is comparing the variable songPosition with zero in PREV_ACTION and with songList.size() in NEXT_ACTION . And when switching, you do not remember the new track number (that is, next-> next-> next restarts the same track). - woesss
  • Thank you very much, now everything works) - Max Charlin

0