如何防止并发流



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

这是我的密码;

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();
                            }
                        });
            }
        }
    });
}
 }

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

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

@Override
protected void onPause() {
    super.onPause();
    mediaPlayer.stop();
    mediaPlayer=null;
}

相关内容

  • 没有找到相关文章

最新更新