Android:如何从片段中的主活动获取MediaPlayer对象



我正在开发一个安卓应用程序,我正在使用NavigationDrawer,只有一个活动(MainActivity)和片段。我在ActionBar上有一个无线电直播按钮,所以我在MainActivity中为直播按钮制作了一个MediaPlayer的对象,它工作正常,现在我在其中一个片段中有一些声音文件,我想获取我在 MainActivity 中制作的mediaPlayer对象以便使用它。请注意,实时流按钮始终在应用程序顶部可见,因此如果我在具有声音文件的片段中,我希望能够收听声音文件,如果我单击实时流按钮,声音文件将暂停,实时流将打开。

这是我的代码:这是主活动(仅相对部分):

public class MainActivity extends ActionBarActivity {
   private static final String RADIO_STREAM_URL= "http://198.178.123.23:8662/stream/1/;listen.mp3";
   MediaPlayer mediaPlayer;
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
     // Inflate the menu; this adds items to the action bar if it is present.
       getMenuInflater().inflate(R.menu.main, menu);
       mediaPlayer = new MediaPlayer();
       mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
       try {
           mediaPlayer.setDataSource(RADIO_STREAM_URL);
       } catch (IOException e) {
           e.printStackTrace();
       }
       return true;
   }
   @Override
   public boolean onOptionsItemSelected(MenuItem item) {
    if (item != null )
    {
        if(item.getItemId() == android.R.id.home){
            if (mDrawerLayout.isDrawerOpen(Gravity.END)){
                mDrawerLayout.closeDrawer(Gravity.END);
            } else {
                mDrawerLayout.openDrawer(Gravity.END);
            }
        }else if(item.getItemId() == R.id.action_settings){
            try {
                mediaPlayer.prepareAsync();
            } catch (IllegalStateException e) {
                e.printStackTrace();
            }

            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mediaPlayer) {
                    if(mediaPlayer.isPlaying()){
                        mediaPlayer.stop();
                        Log.e("ANA Radio","was playing");
                    }else{
                        Log.e("ANA Radio","was not playing");
                        mediaPlayer.start();
                    }
                }
            });
        }
    }
    return false;
}

现在如何在片段中获取mediaPlayer对象?

在这里试试这个:在您的片段中,您可以编写以下代码来获取媒体播放器对象:

((MainActivity)getActivity()).mediaPlayer

另一种解决方案是,您使您的媒体播放器成为类的成员。要做到这一点,请像这样:

public static MediaPlayer mediaPlayer;

最新更新