AsyncTask是否不响应每次点击?

时间:2018-10-11 06:25:37

标签: android android-studio android-layout android-fragments android-asynctask

我在使用Android AsyncTask时遇到问题。在Fragment中,我使用async任务从URL流式传输音频。在第一个播放按钮上,它执行没有任何问题,但是当我单击以转到下一首歌曲时,当我在下一按钮中再次单击时,UI会跳过这首歌曲,然后它可以正常工作。这意味着我必须单击两次才能执行下一步按钮功能。这是我的异步任务类:

 private class LodingToFetchMp3Url extends AsyncTask<Void, Integer, String> {
    @Override
    protected void onPreExecute() {

        super.onPreExecute();


        pDialog = new ProgressDialog(getActivity());
        pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        pDialog.setMessage("Loading...!");
        pDialog.setCancelable(false);
        pDialog.show();
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {


    }

    @Override
    protected String doInBackground(Void... params) {
        try {

            mediaPlayer.setDataSource(Constants.musicArrayListConstants.get(position).getMp3FileUrl());
            mediaPlayer.prepare(); // you must call this method after setup the datasource in setDataSource method. After calling prepare() the instance of MediaPlayer starts load data from URL to internal buffer.

        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }


    @Override
    protected void onPostExecute(String result) {
        pDialog.dismiss();

        mediaFileLengthInMilliseconds = mediaPlayer.getDuration(); // gets the song length in milliseconds from URL

        if (!mediaPlayer.isPlaying()) {



            mediaPlayer.start();
            imgPlayPause.setBackgroundResource(R.mipmap.btn_pause_black);
        } else {
            mediaPlayer.pause();
            imgPlayPause.setBackgroundResource(R.mipmap.btn_play);
        }

        primarySeekBarProgressUpdater();

        super.onPostExecute(result);
    }

}

primarySeekBarProgressUpdater();方法:

  private void primarySeekBarProgressUpdater() {
    seekBarProgress.setProgress((int) (((float) mediaPlayer.getCurrentPosition() / mediaFileLengthInMilliseconds) * 100)); // This math construction give a percentage of "was playing"/"song length"


    if (mediaPlayer.isPlaying()) {
        Runnable notification = new Runnable() {
            public void run() {
                primarySeekBarProgressUpdater();
            }
        };
        handler.postDelayed(notification, 100);
    }
}

下一步按钮的点击:

else if (v.getId() == R.id.imgNext) {

        if(Constants.dropsModelArrayListConstants.size() > position) {
            position = position + 1;

            mediaPlayer.pause();
            mediaPlayer = new MediaPlayer();

            lodingToFetchMp3Url.cancel(true);

            lodingToFetchMp3Url = new LodingToFetchMp3Url();
            lodingToFetchMp3Url.execute();
        }

    }

0 个答案:

没有答案