当我在活动之间切换时,如何让流在线继续播放?

时间:2017-09-18 13:32:59

标签: android android-activity stream

我花了将近一整天时间试图找到针对特定MediaPlayer问题的解决方案,下面的代码是针对我的主要活动我正在构建一个Android应用程序,它会流式传输电台,但是当我切换时活动之间的流停止, 当我在活动之间切换时,如何让流在线(广播)继续播放?

package radiofm.arabel;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.ImageButton;

import static android.widget.AbsListView.OnScrollListener.SCROLL_STATE_IDLE;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    ImageButton id_play,id_pause;

    private Button btn;
    private boolean playPause;
    private MediaPlayer mediaPlayer;
    private ProgressDialog progressDialog;
    private boolean initialStage = true;


    FragmentTransaction fragmentTransaction;
    NavigationView navigationView=null;
    Toolbar toolbar =null;



    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mToggle;



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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        Log.d("myTag", "This is my toolbar");


        id_play = (ImageButton) findViewById(R.id.id_play);
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        progressDialog = new ProgressDialog(this);
        id_play.setEnabled(true);
        id_play.setImageResource(R.drawable.play);
        id_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!playPause) {
                    id_play.setImageResource(R.drawable.pause);

                    if (initialStage) {
                        Log.d("myTag", "This is my excute");
                        new Player().execute("http://arabelfm.ice.infomaniak.ch/arabelprodcastfm.mp3");
                    } else {
                        Log.d("myTag", "This is my beforestart");

                        if (!mediaPlayer.isPlaying())
                            Log.d("myTag", "This is my afterstart");

                        mediaPlayer.start();
                    }

                    playPause = true;

                } else {
                    id_play.setImageResource(R.drawable.play);
                    Log.d("myTag", "This is my beforestop");

                    if (mediaPlayer.isPlaying()) {
                        Log.d("myTag", "This is afterstop");

                        mediaPlayer.reset();

                    }

                    playPause = false;
                }
            }
        });




        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);


    }

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

        if (mediaPlayer != null) {
            mediaPlayer.reset();
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }



    class Player extends AsyncTask<String, Void, Boolean> {
        @Override
        protected Boolean doInBackground(String... strings) {
            Boolean prepared = false;

            try {
                mediaPlayer.setDataSource(strings[0]);
                mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mediaPlayer) {
                        Log.d("myTag", "This is my listnner");
                        initialStage = true;
                        playPause = false;
                        id_play.setImageResource(R.drawable.play);
                        mediaPlayer.stop();
                        mediaPlayer.reset();
                    }
                });

                mediaPlayer.prepare();
                prepared = true;

            } catch (Exception e) {
//                Log.e("MyAudioStreamingApp", e.getMessage());
                prepared = false;
            }

            return prepared;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);

            if (progressDialog.isShowing()) {
                progressDialog.cancel();
            }

            mediaPlayer.start();
            initialStage = true;
        }

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

            progressDialog.setMessage("Buffering...");
            progressDialog.show();
        }
    }



    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @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);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }



    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_alarm) {
            Intent goToNextActivity = new Intent(getApplicationContext(), Add_Alarm.class);
            startActivity(goToNextActivity);
        } else if (id == R.id.nav_aaaaa) {


        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        }


        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}

1 个答案:

答案 0 :(得分:0)

MyService.java

public class MyService extends Service {
private final MediaPlayer mediaPlayer;

public MyService() {
            }

@Override
    public void onCreate() {
        super.onCreate();
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
//You may want to initialise all your stuff here

}

//call these from any context
public void startPlayer() {
    mediaPlayer.start();
}

//You may not need the AsyncTask again so push the relevant code into the service
//This method could be collapsed into startPlayer()
public void executePlayer() {
    new Player().execute("http://arabelfm.ice.infomaniak.ch/arabelprodcastfm.mp3");
}

public boolean isPlaying() {
    return mediaPlayer.isPlaying();
}

public void reset() {
    mediaPlayer.reset();
}

@Override
public IBinder onBind(Intent intent) {
    return null;
}

启动服务后,它将继续运行,直到您决定将其删除为止,如果您在此处完成所有媒体播放器操作,然后使用您的活动中的命令进行控制,则可能会更好。