按下后退按钮时,使用MediaPlayer重置活动

时间:2017-11-21 06:52:33

标签: android android-recyclerview android-mediaplayer runnable android-seekbar

我有一个AudioActivity,它使用RecyclerView显示要流式传输的音频列表。当我按回去进入MainActivity并再次打开AudioActiviy时,SeekBar和音频定时器被重置,但音乐仍在播放。我不想让seekBar重置,而是从音乐播放的地方继续。

在播放音乐时最小化应用程序(当seekBar也在更新时从AudioActivity中更新)并再次打开它会在搜索栏从音乐的位置继续时提供所需的效果。有什么方法可以模仿此效果一项活动并再次开放?

活动代码是:

public class AudioActivity extends AppCompatActivity {
RecyclerView rvAudio;

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

}


private void initialize() {
    rvAudio =(RecyclerView) findViewById(R.id.rv_audio);
    rvAudio.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
    final AudioAdapter audioAdapter = new AudioAdapter(AudioActivity.this,getData());
    rvAudio.setAdapter(audioAdapter);
    rvAudio.setLayoutManager(new LinearLayoutManager(this));
}

public static ArrayList<AudioModel> getData(){
    ArrayList<AudioModel> list = new ArrayList<>();
    String[] audioName = {"Audio one","Audio two","Audio Three"};
    String[] url ={"https://www.mfiles.co.uk/mp3-downloads/silent-night.mp3","https://www.mfiles.co.uk/mp3-downloads/silent-night.mp3","https://www.mfiles.co.uk/mp3-downloads/silent-night.mp3"};
    for (int i=0; i<url.length; i++){
        AudioModel data = new AudioModel();
        data.url= url[i];
        data.name = audioName[i];
        list.add(data);
    }
    return list;
}

@Override
public void onBackPressed() {
    super.onBackPressed();
    Intent intent = new Intent(this, MainActivity.class);
    startActivity(intent);
}
}

适配器代码:

public class AudioAdapter extends RecyclerView.Adapter<AudioAdapter.ViewHolder> {
Context context;
LayoutInflater inflator;
ArrayList<AudioModel> list = new ArrayList();
Handler seekHandler = new Handler();
Runnable run;

public AudioAdapter(Context context, ArrayList<AudioModel> list) {
    this.context = context;
    this.list = list;
    inflator = LayoutInflater.from(context);
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = inflator.inflate(R.layout.audio_recyclerview_layout, parent, false);
    AudioAdapter.ViewHolder viewHolder = new AudioAdapter.ViewHolder(view);
    return viewHolder;
}

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {

    final AudioModel modelList = list.get(position);
    holder.tvAudioName.setText(modelList.name);

    // Initializing MediaPlayer
    final MediaPlayer mediaPlayer = new MediaPlayer();

    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    try {
        mediaPlayer.setDataSource(modelList.url);
        mediaPlayer.prepare();// might take long for buffering.
    } catch (IOException e) {
        e.printStackTrace();
    }

    holder.seekBar.setMax(mediaPlayer.getDuration());
    holder.seekBar.setTag(position);
    //run.run();
    holder.seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (mediaPlayer != null && fromUser) {
                mediaPlayer.seekTo(progress);
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });
    holder.tvAudioLength.setText("0:00/"+calculateDuration(mediaPlayer.getDuration()));
    holder.btn_play.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (!mediaPlayer.isPlaying()) {
                mediaPlayer.start();
                holder.btn_play.setText("Pause");
                 run = new Runnable() {
                    @Override
                    public void run() {
                        // Updateing SeekBar every 100 miliseconds
                        holder.seekBar.setProgress(mediaPlayer.getCurrentPosition());
                        seekHandler.postDelayed(run, 100);
                        //For Showing time of audio(inside runnable)
                        int miliSeconds = mediaPlayer.getCurrentPosition();
                        if(miliSeconds!=0) {
                            //if audio is playing, showing current time;
                            long minutes = TimeUnit.MILLISECONDS.toMinutes(miliSeconds);
                            long seconds = TimeUnit.MILLISECONDS.toSeconds(miliSeconds);
                            if (minutes == 0) {
                               holder.tvAudioLength.setText("0:" + seconds + "/" +calculateDuration(mediaPlayer.getDuration()));
                            } else {
                                if (seconds >= 60) {
                                    long sec = seconds - (minutes * 60);
                                    holder.tvAudioLength.setText(minutes + ":" + sec+ "/" +calculateDuration(mediaPlayer.getDuration()));
                                }
                            }
                        }else{
                            //Displaying total time if audio not playing
                            int totalTime=mediaPlayer.getDuration();
                            long minutes = TimeUnit.MILLISECONDS.toMinutes(totalTime);
                            long seconds = TimeUnit.MILLISECONDS.toSeconds(totalTime);
                            if (minutes == 0) {
                                holder.tvAudioLength.setText("0:" + seconds);
                            } else {
                                if (seconds >= 60) {
                                    long sec = seconds - (minutes * 60);
                                    holder.tvAudioLength.setText(minutes + ":" + sec);
                                }
                            }
                        }
                    }

                };
                run.run();
            } else {
                mediaPlayer.pause();
                holder.btn_play.setText("Play");
            }
        }
    });
}

@Override
public int getItemCount() {
    return list.size();
}

class ViewHolder extends RecyclerView.ViewHolder {
    Button btn_play;
    TextView tvAudioLength;
    TextView tvAudioName;
    SeekBar seekBar;

    public ViewHolder(View itemView) {
        super(itemView);
       // mTvAudioLength =(TextView) itemView.findViewById(R.id.tv_audio_lenght);
       // mSeekBar = (SeekBar) itemView.findViewById(R.id.seekBar);
        btn_play = (Button) itemView.findViewById(R.id.btn_play);
        tvAudioLength = (TextView) itemView.findViewById(R.id.tv_audio_lenght);
        tvAudioName = (TextView) itemView.findViewById(R.id.tv_audio_name);
        seekBar = (SeekBar) itemView.findViewById(R.id.seekBar);

    }
}

private String calculateDuration(int duration) {
    String finalDuration = "";
    long minutes = TimeUnit.MILLISECONDS.toMinutes(duration);
    long seconds = TimeUnit.MILLISECONDS.toSeconds(duration);
    if (minutes == 0) {
        finalDuration = "0:" + seconds;
    } else {
        if (seconds >= 60) {
            long sec = seconds - (minutes * 60);
            finalDuration = minutes + ":" + sec;
        }
    }
    return finalDuration;
}

}

RecyclerView项目布局:

 <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    tools:context="com.example.aditya.audio.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="10dp"
        android:paddingLeft="10dp"
        android:layout_weight="1"
        android:orientation="vertical">

        <TextView
            android:id="@+id/tv_audio_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingRight="10dp"
            android:text="Audio Name"
            android:textColor="#000000"
            android:textSize="18dp"
            android:paddingTop="5dp" />
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
        <SeekBar android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingTop="10dp"
            android:layout_weight="1"
            android:id="@+id/seekBar"
            android:layout_marginRight="5dp"
            android:text="Duration"/>
    <TextView android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="5dp"
    android:layout_weight="0"
        android:id="@+id/tv_audio_lenght"
        android:paddingRight="15dp"
        android:text="0:00"/>
</LinearLayout>
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_gravity="center"
        android:layout_weight="0"
        android:orientation="horizontal"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="0dp">

        <Button
            android:id="@+id/btn_play"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="10dp"
            android:layout_marginBottom="10dp"
            android:layout_marginTop="0dp"
            android:text="Play" />

    </LinearLayout>
</LinearLayout>

AudioActivity布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.aditya.audio.MainActivity">
<android.support.v7.widget.RecyclerView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/rv_audio"
    />
</LinearLayout>

1 个答案:

答案 0 :(得分:0)

如果您想要继续跟踪当前播放的音乐并在重新访问应用程序时在视图中显示,您可以获得当前播放位置并在搜索栏中寻找该位置,如下所示:

 length=mediaplayer.getCurrentPosition();
 mediaplayer.seekTo(length);

但这不是最好的做法。如果您实现播放音乐的后台服务以及所有播放信息的跟踪,那将是明智的:

  1. Funkytunes
  2. Google sample music player
  3. 由于音频适配器中长时间的UI线程操作,音频活动也需要很长时间才能打开。当您的音乐列表增长到20,50,100时会发生什么,我认为您的应用可能会崩溃 因此,如果您像上面的应用程序一样实现后台服务和回放管理器,那将是最好的。

    当我按回去进入MainActivity并再次打开AudioActiviy时,SeekBar和音频定时器会重置,但音乐仍在播放。

    • 因为返回上一个活动会破坏音频活动视图,并重置视图。

    在播放音乐时最小化应用(当seekBar也在更新时从AudioActivity播放)并再次打开它会在搜索栏从音乐位置继续时提供所需的效果。

    • 这是因为您的应用处于后台,视图尚未销毁。