如何快速开发一款音乐播放器?
文末提供体验demo,实现了播放控制,进度更新,全网音乐免费下载,欢迎技术交流!
音乐播放器无非就是对mediaplayer对象的操作了,当然需要开启服务,而服务为了保活,只能使用前台服务。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(new Intent(mContext, MusicService.class));
} else {
startService(new Intent(mContext, MusicService.class));
}
启动前台服务后,你有5秒的时间发送服务通知,否则服务会被杀死并抛出异常
@Override
public void onCreate() {
super.onCreate();
// 服务通知
mNotification = createForegroundNotification();
//将服务置于启动状态 ,NOTIFICATION_ID指的是创建的通知的ID
startForeground(mNotificationId, mNotification);
创建服务通知
/**
* 创建服务通知
*/
private Notification createForegroundNotification() {
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// 唯一的通知通道的id.
String notificationChannelId = "notification_channel_music";
// Android8.0以上的系统,新建消息通道
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//用户可见的通道名称
String channelName = "音乐播放";
//通道的重要程度
int importance = NotificationManager.IMPORTANCE_NONE;
NotificationChannel notificationChannel = new NotificationChannel(notificationChannelId, channelName, importance);
notificationChannel.setDescription("音乐播放控制器");
//LED灯
notificationChannel.enableLights(false);
// notificationChannel.setLightColor(Color.RED);
//震动
notificationChannel.setVibrationPattern(new long[]{
0});
notificationChannel.enableVibration(false);
//声音
notificationChannel.setSound(null,null);
mNotificationManager.createNotificationChannel(notificationChannel);
}
mRemoteView = new RemoteViews(getPackageName(), R.layout.notification);
initRemoteView(mRemoteView);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, notificationChannelId)
.