How to solve a problem? I request the length of the track time before the media player receives this data.

public class MainActivity extends AppCompatActivity implements MediaPlayer.OnPreparedListener { MediaPlayer mediaPlayer=new MediaPlayer(); Button btn; int totalDur=0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initPlayer(); btn= (Button) findViewById(R.id.button); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Uri uri=Uri.parse("content://media/external/audio/media/1"); mediaPlayer.reset(); try { mediaPlayer.setDataSource(getApplicationContext(),uri); } catch (IOException e) { e.printStackTrace(); } mediaPlayer.prepareAsync(); Log.d("myTag", String.valueOf(totalDur)); } }); } public void initPlayer() { // mediaPlayer.setWakeMode(getApplicationContext(), // PowerManager.PARTIAL_WAKE_LOCK); mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); //set listeners mediaPlayer.setOnPreparedListener(this); } @Override protected void onDestroy() { super.onDestroy(); mediaPlayer.stop(); mediaPlayer.reset(); mediaPlayer.release(); } @Override public void onPrepared(MediaPlayer mp) { //mp.reset(); mp.start(); totalDur=mp.getDuration(); Log.d("myTag", "onP " + String.valueOf(mp.getDuration())); } } 

    2 answers 2

    Found the answer. As one of the parameters - passed the widget from the main thread, and then changed the value in onprepared ())

      Alternatively, you can use AsyncTask . Then you can place the call to mp.start () in the doInBackground() method, then set Thread.sleep(1000); //ожидание 1 секунду Thread.sleep(1000); //ожидание 1 секунду , and in the onPostExecute() method already call totalDur = mp.getDuration ();

      Thus, the main stream will not be broken, and you can adjust the waiting time.

      If necessary, here _http: //startandroid.ru/ru/uroki/vse-uroki-spiskom/149-urok-86-asynctask-znakomstvo-neslozhnyj-primer.html there is a lesson on working with AsinkTaskom

      Hope this helps you. Good luck!

      • Thank you, and why Thread.sleep (1000)?) - Oleh