0

问题很简单,媒体播放器在从远程服务器实现源时阻塞了 UI。我使用同步准备来初始化媒体播放器,但在重置媒体播放器时它会阻止 UI。

在这里,我使用线程编写了一个代码,它有很大帮助,但需要一个干净的解决方案。

public class QuranPlayerAct extends Activity implements DownloadMusicLstn,SeekBar.OnSeekBarChangeListener, OnClickListener, MediaPlayer.OnPreparedListener, OnCompletionListener, PlayerBtnClickedLstn, Runnable {

private static final int PLAY_FROM_LOCAL = 234;
private static final int PLAY_FROM_SERVER = 321;
private static final String TAG = "SongsListAct";
private static final int PAUSED = 756;
private static final int STARTED = 554;
private static final int STOPED = 386;
private static final int CLOSED = 453;
private TextView downloadEsplasedTV;
private RelativeLayout playerRetLay;
private ListView musicLst;
private ProgressBar dwnPrgV;
private ImageView playImgV;
private SeekBar songProgressBar;
private TextView songTitleLabel;
private TextView songCurrentDurationLabel;
private TextView songTotalDurationLabel;
private MediaPlayer mp;
private Utilities utils;
private Handler handler;
private boolean stopDownload;
private RelativeLayout downloadRetLay;
private ArrayList<String> musicFiles;
private ImageButton closeImgV;
private TextView downloadTitle;
private long currentDuration;
private Runnable mUpdateTimeTask = new Runnable() {

    public void run() {
        if (mPrepared) {
            long totalDuration = mp.getDuration();
            currentDuration = mp.getCurrentPosition();

            songTotalDurationLabel.setText(""
                    + utils.milliSecondsToTimer(totalDuration));
            songCurrentDurationLabel.setText(""
                    + utils.milliSecondsToTimer(currentDuration));

            int progress = (int) (utils.getProgressPercentage(
                    currentDuration, totalDuration));
            songProgressBar.setProgress(progress);
        }
        handler.postDelayed(this, 100);
    }
};
private TextView downloadTotalTV;
private TextView downloadPercentageTV;
private ImageView stopImgV;
private ImageButton closeDownloadImgV;
private int fileSize;
private boolean mPrepared;
private ProgressBar songsLoadingPB;
private String url;
private String fName;
private boolean stopped;
private int plLoc;
private int track_no;
private int state;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.act_quran_player);
    // setActionBar();
    setActionBar2();
    getRefs();

    handler = new Handler();
    initMediaPlayer();
     playerRetLay.setVisibility(View.GONE);
    // updateList();

    createAppDirectory();

    Thread t = new Thread(this);
    t.start();

}

private void setActionBar2() {
    final ActionBar bar = getActionBar();

    bar.setDisplayShowHomeEnabled(false);
    bar.setDisplayShowCustomEnabled(true);
    bar.setDisplayShowTitleEnabled(false);
    bar.setCustomView(R.layout.player_actionbar_lay);
}

/*
 * private void setActionBar() { final ActionBar bar = getActionBar();
 * 
 * bar.setDisplayShowHomeEnabled(false);
 * bar.setDisplayShowCustomEnabled(true);
 * bar.setDisplayShowTitleEnabled(false);
 * bar.setCustomView(R.layout.player_actionbar_lay);
 * 
 * TextView tv = (TextView) bar.getCustomView().findViewById(
 * R.id.action_bar_title);
 * 
 * try { tv.setTypeface(Typeface .createFromAsset(getAssets(),
 * "DANUBE__.TTF")); } catch (Exception e) { e.printStackTrace(); } }
 */

@Override
public void onResume() {
    super.onResume();
    setVisiblilityToPlayerAndUI(false);
    updateProgressBar();
    if(state==CLOSED)playerRetLay.setVisibility(View.GONE);
}

@Override
public void onPause() {
    super.onPause();
    l("Activity paused");
    stopDownload = true;
    setVisiblilityToPlayerAndUI(false);
    handler.removeCallbacks(mUpdateTimeTask);
    if (mp != null)
        switch (state) {
        case STARTED:
            mp.pause();
            playImgV.setImageResource(R.drawable.play_img);
            break;
        }
}

private void getRefs() {
    musicLst = (ListView) findViewById(R.id.musLst_lstV);
    playerRetLay = (RelativeLayout) findViewById(R.id.musLst_player_retLay);
    dwnPrgV = (ProgressBar) findViewById(R.id.musLst_down_progbarV);
    downloadRetLay = (RelativeLayout) findViewById(R.id.musLst_dwn_retLay);

    playImgV = (ImageView) findViewById(R.id.musLst_ply_btn);
    songProgressBar = (SeekBar) findViewById(R.id.musLst_seek_bar);
    songTitleLabel = (TextView) findViewById(R.id.musLst_mus_det_txt);
    songCurrentDurationLabel = (TextView) findViewById(R.id.time_esplased_TV);
    songTotalDurationLabel = (TextView) findViewById(R.id.total_time_TV);
    closeImgV = (ImageButton) findViewById(R.id.musLst_close_btn);
    downloadTitle = (TextView) findViewById(R.id.musLst_down_title_TV);

    downloadEsplasedTV = (TextView) findViewById(R.id.time_esplased_TV22);
    downloadTotalTV = (TextView) findViewById(R.id.total_time_TV2);
    downloadPercentageTV = (TextView) findViewById(R.id.total_percentage);

    stopImgV = (ImageView) findViewById(R.id.musLst_stop_btn);
    closeDownloadImgV = (ImageButton) findViewById(R.id.close_down_btn);

    songsLoadingPB = (ProgressBar) findViewById(R.id.songs_load_progressbar);

}


@Override
public void run() {

    if (!isNetworkAvailable()) {
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                Toast.makeText(QuranPlayerAct.this,
                        "No Internet Connection Available",
                        Toast.LENGTH_LONG).show();
            }
        });
        return;
    }

    MusicAppUtils appUtils = new MusicAppUtils();

    String jsn = appUtils
            .getDataFromUrl(MusicAppCommons.HTTP_AIMANSANGAM_COM_LISTFILES_PHP);

    if (jsn == null)
        return;
    jsn = jsn.replace(",]", "]");
    musicFiles = appUtils.parseMusicFilesJson(jsn);
    updateList();

}

private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager
            .getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

private void createAppDirectory() {
    if (MusicAppCommons
            .checkFileExist(MusicAppCommons.AIMANSANGAM_MUSIC_DIR)) {
        Log.i(TAG, "app directory already exist");
        return;
    }
    File dir = new File(MusicAppCommons.AIMANSANGAM_MUSIC_DIR);
    if (dir.mkdirs())
        Log.i(TAG, "app directory created");
}

private void setVisiblilityToPlayerAndUI(boolean b) {
    if (b) {
        songsLoadingPB.setVisibility(View.VISIBLE);
        downloadRetLay.setVisibility(View.VISIBLE);
        // playerRetLay.setVisibility(View.VISIBLE);
    } else {
        songsLoadingPB.setVisibility(View.GONE);
        downloadRetLay.setVisibility(View.GONE);
        // playerRetLay.setVisibility(View.GONE);
    }
}

private void initMediaPlayer() {

    utils = new Utilities();
    mp = new MediaPlayer();
    mp.setOnCompletionListener(this);
    songProgressBar.setOnSeekBarChangeListener(this);
    playImgV.setOnClickListener(this);
    closeDownloadImgV.setOnClickListener(this);
    closeImgV.setOnClickListener(this);
    stopImgV.setOnClickListener(this);
}

private void resetTimeLabel() {
    runOnUiThread(new Runnable() {

        @Override
        public void run() {
            songTotalDurationLabel.setText("..");
            songCurrentDurationLabel.setText("..");

        }
    });
}

public void updateProgressBar() {
    handler.removeCallbacks(mUpdateTimeTask);
    handler.postDelayed(mUpdateTimeTask, 100);
}

@Override
public void onDestroy() {
    super.onDestroy();
    handler.removeCallbacks(mUpdateTimeTask);
    if (mp != null)
        mp.release();
}

public void updateList() {
    l("called update list");
    if (musicFiles == null)
        return;
    updateMusicListView(MusicLstAdapter.MUSIC_NOT_DOWNLOADING);
}

private void updateMusicListView(int state) {
    final MusicLstAdapter lstAdapter = new MusicLstAdapter(this,
            musicFiles, this, state, this);
    runOnUiThread(new Runnable() {

        @Override
        public void run() {
            musicLst.setAdapter(lstAdapter);
            lstAdapter.notifyDataSetChanged();
        }
    });
}

@Override
public void onClick(View v) {
    if (v == closeDownloadImgV) {

        downloadRetLay.setVisibility(View.GONE);
        stopDownload = true;
        Toast.makeText(this, "Download canceled", Toast.LENGTH_SHORT)
                .show();
    } else if (v == playImgV) {
        if (stopped)
            new PlayerThread();

        if (mp.isPlaying()) {
            if (mp != null) {
                state = PAUSED;
                mp.pause();
                l("pause");
                playImgV.setImageResource(R.drawable.play_img);
            }
        } else {
            if (mp != null) {
                state = STARTED;
                mp.start();
                l("start");
                playImgV.setImageResource(R.drawable.pause_img);
            }
        }
    } else if (v == closeImgV) {
        l("close clicked");
        state = CLOSED;
        playerRetLay.setVisibility(View.GONE);
        handler.removeCallbacks(mUpdateTimeTask);
        mp.stop();
        mPrepared = false;
        new Thread(new Runnable() {

            @Override
            public void run() {
                mp.reset();
            }
        }).start();
    } else if (v == stopImgV) {
        l("stop clicked");
        state = STOPED;
        handler.removeCallbacks(mUpdateTimeTask);
        mp.stop();
        resetTimeLabel();
        playImgV.setImageResource(R.drawable.play_img);
        stopped = true;
        mPrepared = false;
    }
}

// --------************************************************************************
@Override
public void setSize(final int fileSize) {
    handler.post(new Runnable() {

        @Override
        public void run() {
            dwnPrgV.setMax(fileSize);
            QuranPlayerAct.this.fileSize = fileSize;
            float size = (float) fileSize / 1048576;
            DecimalFormat format = new DecimalFormat("#.##");
            downloadTotalTV.setText(format.format(size) + " MB");
            downloadPercentageTV.setText("0 %");
        }
    });
}

@Override
public void onProgressUpdate(final long total) {
    handler.post(new Runnable() {

        @Override
        public void run() {
            dwnPrgV.setProgress((int) total);
            float size = (float) total / 1048576;
            DecimalFormat format = new DecimalFormat("#.##");
            downloadEsplasedTV.setText(format.format(size) + " MB");
            float l = total / (float) fileSize * 100;
            int round = Math.round(l);
            downloadPercentageTV.setText(round + " %");
        }
    });
}

@Override
public void finished() {
    handler.post(new Runnable() {

        @Override
        public void run() {
            downloadRetLay.setVisibility(View.GONE);

        }
    });

    updateMusicListView(MusicLstAdapter.MUSIC_NOT_DOWNLOADING);
}

@Override
public void onDownloadSuccess(boolean success) {
    if (success) {

    } else {

    }

}

@Override
public boolean isStopDownload() {
    return stopDownload;
}

@Override
public void downloadStarted(final String fName) {
    stopDownload = false;
    handler.post(new Runnable() {

        @Override
        public void run() {
            downloadTitle.setText(fName);
            downloadRetLay.setVisibility(View.VISIBLE);

        }
    });
    updateMusicListView(MusicLstAdapter.MUSIC_DOWNLOADING);
}

// ----------------*****************************************************************************

@Override
public void onProgressChanged(SeekBar seekBar, int progress,
        boolean fromTouch) {
}

@Override
public void onStartTrackingTouch(SeekBar seekBar) {
    handler.removeCallbacks(mUpdateTimeTask);
}

@Override
public void onStopTrackingTouch(SeekBar seekBar) {
    handler.removeCallbacks(mUpdateTimeTask);
    int totalDuration = mp.getDuration();
    int currentPosition = utils.progressToTimer(seekBar.getProgress(),
            totalDuration);

    mp.seekTo(currentPosition);

    updateProgressBar();
}

@Override
public void onPrepared(MediaPlayer mp) {
    l("onprepared");
    mPrepared = true;
    mp.start();
    state = STARTED;
    playImgV.setImageResource(R.drawable.pause_img);
}

private void l(String str) {
    Log.i(TAG, str);
}

// ---------------------***************************************************************************
private class PlayerThread extends Thread {

    public PlayerThread() {
        start();
    }

    @Override
    public void run() {
        try {

            stopped = false;
            mPrepared = false;
            resetTimeLabel();
            mp.reset();
            mp.setDataSource(url);

            if (plLoc == PLAY_FROM_SERVER) {

                mp.prepareAsync();
                mp.setOnPreparedListener(QuranPlayerAct.this);
                updatePlayerImg(R.drawable.play_img);

            } else {

                mp.prepare();
                mp.start();
                mPrepared = true;
                state = STARTED;
                updatePlayerImg(R.drawable.pause_img);

            }

            updatePlayerUI();
            updateProgressBar();

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

    private void updatePlayerUI() {
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                songTitleLabel.setText(fName);
                songProgressBar.setProgress(0);
                songProgressBar.setMax(100);

            }
        });
    }

}

private void updatePlayerImg(final int playImg) {
    runOnUiThread(new Runnable() {

        @Override
        public void run() {
            playImgV.setImageResource(playImg);
        }
    });
}

// ------------------------------

@Override
public void onCompletion(MediaPlayer mp) {
    track_no++;
    if (track_no > musicFiles.size() - 1) {
        track_no = 0;
    }
    playerRetLay.setVisibility(View.VISIBLE);

    fName = musicFiles.get(track_no);
    String filePath = MusicAppCommons.AIMANSANGAM_MUSIC_DIR + "/" + fName;
    if (MusicAppCommons.checkFileExist(filePath)) {
        url = filePath;
        plLoc = PLAY_FROM_LOCAL;

    } else {
        url = MusicAppCommons.HTTP_AIMANSANGAM_COM_QURAN_FILES + fName;
        url = url.replace(" ", "%20");
        plLoc = PLAY_FROM_SERVER;

    }
    new PlayerThread();
}

@Override
public void clickedOnPlayBtn(int val) {
    this.track_no = val;
    l("song clicked");
    playerRetLay.setVisibility(View.VISIBLE);

    fName = musicFiles.get(val);
    String filePath = MusicAppCommons.AIMANSANGAM_MUSIC_DIR + "/" + fName;
    if (MusicAppCommons.checkFileExist(filePath)) {
        url = filePath;
        plLoc = PLAY_FROM_LOCAL;

    } else {
        url = MusicAppCommons.HTTP_AIMANSANGAM_COM_QURAN_FILES + fName;
        url = url.replace(" ", "%20");
        plLoc = PLAY_FROM_SERVER;

    }
    new PlayerThread();

}

}

4

0 回答 0