Android小程序实现音乐播放列表攻略
在Android小程序中实现音乐播放列表,需要使用到以下知识点:
- RecyclerView控件展示列表
- Service组件进行音乐播放
- Notification通知栏控制播放状态
下面详细讲解实现的完整攻略。
实现步骤
- 设计音乐列表的布局文件
在布局文件中,使用RecyclerView
控件展示音乐列表,用TextView
显示音乐名称和歌手信息。
示例代码:
<?xml version="1.0" encoding="utf-8"?>
<androidx.recyclerview.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/playlist_recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
- 实现音乐列表的适配器
在适配器中,根据数据源展示每一条音乐列表项。同时,通过onClick()
方法监听用户点击列表项的事件。
示例代码:
public class PlaylistAdapter extends RecyclerView.Adapter<PlaylistAdapter.ViewHolder> {
private List<Song> mSongList;
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onItemClick(View view, int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
static class ViewHolder extends RecyclerView.ViewHolder {
TextView songName;
TextView singer;
public ViewHolder(@NonNull View itemView, final OnItemClickListener listener) {
super(itemView);
songName = itemView.findViewById(R.id.song_name);
singer = itemView.findViewById(R.id.singer);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (listener != null) {
int position = getAdapterPosition();
listener.onItemClick(v, position);
}
}
});
}
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.playlist_item, parent, false);
ViewHolder holder = new ViewHolder(view, mListener);
return holder;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
Song song = mSongList.get(position);
holder.songName.setText(song.getSongName());
holder.singer.setText(song.getSinger());
}
@Override
public int getItemCount() {
return mSongList.size();
}
public PlaylistAdapter(List<Song> songList) {
mSongList = songList;
}
}
- 创建音乐播放的Service组件
在Service组件中,在后台进行音乐播放,同时提供控制音乐播放状态的接口。使用MediaPlayer
控件播放音乐。
示例代码:
public class MusicService extends Service implements MediaPlayer.OnCompletionListener {
private final IBinder mBinder = new MusicBinder();
private MediaPlayer mMediaPlayer;
public class MusicBinder extends Binder {
MusicService getService() {
return MusicService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mMediaPlayer = MediaPlayer.create(this, R.raw.test_song);
mMediaPlayer.setOnCompletionListener(this);
return super.onStartCommand(intent, flags, startId);
}
public void play() {
if (!mMediaPlayer.isPlaying()) {
mMediaPlayer.start();
}
}
public void pause() {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
}
}
public void stop() {
mMediaPlayer.stop();
mMediaPlayer.release();
mMediaPlayer = null;
}
@Override
public void onCompletion(MediaPlayer mp) {
stop();
}
@Override
public void onDestroy() {
stop();
super.onDestroy();
}
}
- 创建通知栏,并控制音乐播放状态
使用NotificationCompat.Builder
创建通知栏,监听通知栏控件的点击事件,并在点击事件中控制音乐播放状态。
示例代码:
public class MusicNotification {
private static final int NOTIFICATION_ID = 1;
private static final String CHANNEL_ID = "CHANNEL_ID";
private Context mContext;
private NotificationManager mNotificationManager;
private NotificationCompat.Builder mBuilder;
public MusicNotification(Context context) {
mContext = context;
mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
createChannel();
mBuilder = new NotificationCompat.Builder(mContext, CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("app name")
.setContentText("song name")
.setContentIntent(onNotificationClick())
.addAction(onPauseButtonClick())
.setAutoCancel(true)
.setOngoing(false);
}
private void createChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID,
"app name",
NotificationManager.IMPORTANCE_HIGH);
channel.setDescription("notification description");
mNotificationManager.createNotificationChannel(channel);
}
}
private PendingIntent onNotificationClick() {
Intent intent = new Intent(mContext, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
return PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
private NotificationCompat.Action onPauseButtonClick() {
PendingIntent pausePendingIntent = createPendingIntent(Command.PAUSE);
return new NotificationCompat.Action(
android.R.drawable.ic_media_pause,
"Pause",
pausePendingIntent);
}
public void showNotification() {
mBuilder.setOngoing(true);
Notification notification = mBuilder.build();
mNotificationManager.notify(NOTIFICATION_ID, notification);
}
public void hideNotification() {
mBuilder.setOngoing(false);
Notification notification = mBuilder.build();
mNotificationManager.notify(NOTIFICATION_ID, notification);
}
private PendingIntent createPendingIntent(String command) {
Intent intent = new Intent(MusicService.ACTION_MUSIC_COMMAND);
intent.putExtra(MusicService.EXTRA_COMMAND, command);
return PendingIntent.getService(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
}
- 在MainActivity中控制音乐播放
在MainActivity中,创建Service组件,准备音乐播放并展示通知栏。同时,通过RecyclerView的onItemClickListener()
方法,监听用户的音乐选择事件。
示例代码:
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private PlaylistAdapter mAdapter;
private MusicService mMusicService;
private MusicNotification mMusicNotification;
private ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
MusicService.MusicBinder binder = (MusicService.MusicBinder) service;
mMusicService = binder.getService();
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.playlist_recyclerview);
mAdapter = new PlaylistAdapter(createSongList());
mRecyclerView.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(new PlaylistAdapter.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
mMusicService.stop();
mMusicService.play();
updateMusicNotification();
}
});
Intent intent = new Intent(this, MusicService.class);
startService(intent);
bindService(intent, mServiceConnection, BIND_AUTO_CREATE);
mMusicNotification = new MusicNotification(this);
mMusicNotification.showNotification();
}
private void updateMusicNotification() {
mMusicNotification.showNotification(); //暂定以播放状态展示通知栏
}
private List<Song> createSongList() {
List<Song> songList = new ArrayList<>();
songList.add(new Song("song 1", "singer 1"));
songList.add(new Song("song 2", "singer 2"));
songList.add(new Song("song 3", "singer 3"));
return songList;
}
@Override
protected void onDestroy() {
unbindService(mServiceConnection);
mMusicNotification.hideNotification();
super.onDestroy();
}
}
以上就是实现Android小程序音乐播放列表的完整攻略。
示例说明:
-
MainActivity中展示了三个音乐列表项,用户点击其中一个音乐列表项,便会播放该音乐,并且通过通知栏展示播放状态。用户再次点击通知栏,可控制音乐播放的暂停或继续播放。
-
在MusicService中,没有使用本地数据,只是简单地加载项目中的一首测试歌曲。若需要加载外部数据,则需要在代码中增加相关实现。
附录:
Song
类属性包含歌曲名称和歌手信息。
public class Song {
private String songName;
private String singer;
public String getSongName() {
return songName;
}
public String getSinger() {
return singer;
}
public Song(String songName, String singer) {
this.songName = songName;
this.singer = singer;
}
}
Command
类包含通知栏上的控制事件。
public class Command {
public static final String PAUSE = "PAUSE";
public static final String RESUME = "RESUME";
}
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Android小程序实现音乐播放列表 - Python技术站