如何防止并发流

时间:2013-08-17 16:30:38

标签: android streaming media-player against

我为一家广播电台编写了一个应用程序,运行良好。如果我单击返回桌面并再次单击以激活应用程序,则会导致应用再次流式传输,从而导致同时运行2个流。

这是我的代码;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    this.setTitle("Standart FM");

    startButton = (Button) findViewById(R.id.buttonBasla);
    facebookButton = (Button) findViewById(R.id.buttonFacebook);
    twitterButton = (Button) findViewById(R.id.buttonTwitter);
    Intent myService = new Intent(this, MyMediaPlayerService.class);
    pd = new ProgressDialog(MainActivity.this);

    mediaPlayer = new MediaPlayer();

    if (isOnline()) {

        pd.setCancelable(false);
        pd.setMessage("Yükleniyor...");
        pd.show();

        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        try {
            mediaPlayer.setDataSource(path);
            mediaPlayer.prepareAsync();

        } catch (Exception e) {
            e.printStackTrace();
        }

        mediaPlayer
                .setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        mp.start();
                        pd.dismiss();
                    }
                });
    } else {
        ....
    }

    startButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent myService = new Intent(MainActivity.this,
                    MyMediaPlayerService.class);
            if (mediaPlayer.isPlaying()) {
                startButton.setBackgroundResource(R.drawable.andplaybtn);
                mediaPlayer.stop();
            } else {
                startButton.setBackgroundResource(R.drawable.andstopbtn);

                mediaPlayer.reset();
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                try {
                    mediaPlayer.setDataSource(path);
                    mediaPlayer.prepareAsync();
                    pd.setCancelable(false);
                    pd.setMessage("Yükleniyor...");
                    pd.show();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                mediaPlayer
                        .setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

                            @Override
                            public void onPrepared(MediaPlayer mp) {
                                mp.start();
                                pd.dismiss();

                            }
                        });
            }
        }
    });

}

 }

我该如何解决这个问题?如何防止此活动中的并发流?请帮帮我。

1 个答案:

答案 0 :(得分:0)

您应该在onPause方法中停止媒体播放器,并且还要说mediaPlayer = null;

@Override
protected void onPause() {
    super.onPause();

    mediaPlayer.stop();
    mediaPlayer=null;
}