实现下载功能的暂停,取消以及断点续传功能

pull/1/head
jsyjst 6 years ago
parent c7c822b476
commit 3d2c37a4f5

@ -2,7 +2,7 @@
<litepal> <litepal>
<dbname value="SongList" /> <dbname value="SongList" />
<version value="16" /> <version value="23" />
<list> <list>
<mapping class="com.example.musicplayer.entiy.OnlineSong" /> <mapping class="com.example.musicplayer.entiy.OnlineSong" />
@ -12,5 +12,7 @@
<mapping class="com.example.musicplayer.entiy.HistorySong" /> <mapping class="com.example.musicplayer.entiy.HistorySong" />
<mapping class="com.example.musicplayer.entiy.AlbumCollection" /> <mapping class="com.example.musicplayer.entiy.AlbumCollection" />
<mapping class="com.example.musicplayer.entiy.DownloadSong" /> <mapping class="com.example.musicplayer.entiy.DownloadSong" />
<mapping class="com.example.musicplayer.entiy.DownloadInfo"/>
<mapping class="com.example.musicplayer.entiy.Song"/>
</list> </list>
</litepal> </litepal>

@ -6,10 +6,13 @@ import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.SeekBar; import android.widget.SeekBar;
import android.widget.TextView; import android.widget.TextView;
import com.example.musicplayer.R; import com.example.musicplayer.R;
import com.example.musicplayer.callback.OnDeleteClickListener;
import com.example.musicplayer.callback.OnItemClickListener;
import com.example.musicplayer.entiy.DownloadInfo; import com.example.musicplayer.entiy.DownloadInfo;
import com.example.musicplayer.util.MediaUtil; import com.example.musicplayer.util.MediaUtil;
@ -24,26 +27,41 @@ import java.util.List;
*/ */
public class DownloadingAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { public class DownloadingAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<DownloadInfo> downloadInfoList; private List<DownloadInfo> downloadInfoList;
private List<String> downloadSongId;
private OnItemClickListener onItemClickListener;
private OnDeleteClickListener onDeleteClickListener;
public void setOnDeleteClickListener(OnDeleteClickListener onDeleteClickListener){
this.onDeleteClickListener = onDeleteClickListener;
}
public DownloadingAdapter(List<DownloadInfo> downloadInfoList) { public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
public DownloadingAdapter(List<DownloadInfo> downloadInfoList,List<String> downloadSongId) {
this.downloadInfoList = downloadInfoList; this.downloadInfoList = downloadInfoList;
this.downloadSongId = downloadSongId;
} }
class ViewHolder extends RecyclerView.ViewHolder { class ViewHolder extends RecyclerView.ViewHolder {
TextView songTv; TextView songTv;
TextView currentSizeTv; TextView sizeTv;
TextView totalSizeTv;
SeekBar seekBar; SeekBar seekBar;
View itemView; View itemView;
ImageView canacleIv;
public ViewHolder(@NonNull View itemView) { public ViewHolder(@NonNull View itemView) {
super(itemView); super(itemView);
this.itemView = itemView; this.itemView = itemView;
songTv = itemView.findViewById(R.id.songTv); songTv = itemView.findViewById(R.id.songTv);
currentSizeTv = itemView.findViewById(R.id.currentSizeTv); sizeTv = itemView.findViewById(R.id.sizeTv);
totalSizeTv = itemView.findViewById(R.id.totalSizeTv);
seekBar = itemView.findViewById(R.id.seekBar); seekBar = itemView.findViewById(R.id.seekBar);
canacleIv = itemView.findViewById(R.id.cancelIv);
} }
} }
@ -51,23 +69,40 @@ public class DownloadingAdapter extends RecyclerView.Adapter<RecyclerView.ViewHo
@NonNull @NonNull
@Override @Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()) View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.recycler_downing_item, viewGroup, false); .inflate(R.layout.recycler_downing_item, viewGroup, false);
ViewHolder viewHolder = new ViewHolder(view); ViewHolder viewHolder = new ViewHolder(view);
return viewHolder; return viewHolder;
} }
@SuppressLint("SetTextI18n") @SuppressLint({"SetTextI18n", "ClickableViewAccessibility"})
@Override @Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) { public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
ViewHolder holder = (ViewHolder) viewHolder; ViewHolder holder = (ViewHolder) viewHolder;
if(downloadInfoList.size() == 0) return; if (downloadInfoList.size() == 0) return;
DownloadInfo downloadInfo = downloadInfoList.get(i); DownloadInfo downloadInfo = downloadInfoList.get(i);
holder.itemView.setVisibility(downloadInfo.getProgress() == 100 ? View.GONE : View.VISIBLE);
holder.songTv.setText(downloadInfo.getSongName()); holder.songTv.setText(downloadInfo.getSongName());
holder.currentSizeTv.setText(MediaUtil.formatSize(downloadInfo.getCurrentSize()) + "M"); if (downloadSongId.size()!=0&&downloadSongId.get(0).equals(downloadInfo.getSongId())) {//如果当前歌曲正在下载
holder.totalSizeTv.setText(MediaUtil.formatSize(downloadInfo.getTotalSize()) + "M"); holder.sizeTv.setText(
MediaUtil.formatSize(downloadInfo.getCurrentSize()) + "M"
+ " / "
+ MediaUtil.formatSize(downloadInfo.getTotalSize()) + "M");
holder.seekBar.setVisibility(View.VISIBLE);
}else {//当前歌曲并未下载
holder.sizeTv.setText(downloadInfo.getSinger());
holder.seekBar.setVisibility(View.GONE);
}
holder.seekBar.setOnTouchListener((view, motionEvent) -> true); //消费该事件让seekBar不能拖动和点击
holder.seekBar.setProgress(downloadInfo.getProgress()); holder.seekBar.setProgress(downloadInfo.getProgress());
//点击事件
holder.itemView.setOnClickListener(view -> {
if(!downloadSongId.get(0).equals(downloadInfo.getSongId())) holder.sizeTv.setText("正在获取歌曲大小");
onItemClickListener.onClick(i);
});
//取消
holder.canacleIv.setOnClickListener(view -> onDeleteClickListener.onClick(i));
} }
@Override @Override

@ -13,11 +13,11 @@ public class Constant {
public static final int TYPE_ALBUM_SONG = 3; public static final int TYPE_ALBUM_SONG = 3;
//播放列表 //播放列表
public static final int LIST_TYPE_LOCAL = 0; //本地列表 public static final int LIST_TYPE_LOCAL = 1; //本地列表
public static final int LIST_TYPE_ONLINE = 1; //专辑列表 public static final int LIST_TYPE_ONLINE = 2; //专辑列表
public static final int LIST_TYPE_LOVE = 2; //我的收藏列表 public static final int LIST_TYPE_LOVE = 3; //我的收藏列表
public static final int LIST_TYPE_HISTORY = 3; //最近播放列表 public static final int LIST_TYPE_HISTORY = 4; //最近播放列表
public static final int LIST_TYPE_DOWNLOAD = 4; //下载列表 public static final int LIST_TYPE_DOWNLOAD = 5; //下载列表
public static final int HISTORY_MAX_SIZE = 100; public static final int HISTORY_MAX_SIZE = 100;
@ -68,9 +68,9 @@ public class Constant {
//download //download
public final static int TYPE_DOWNLOADING = 0; public final static int TYPE_DOWNLOADING = 0;
public final static int TYPE_PAUSED = 1; public final static int TYPE_DOWNLOAD_PAUSED = 1;
public final static int TYPE_CANCELED = 2; public final static int TYPE_DOWNLOAD_CANCELED = 2;
public final static int TYPE_SUCCESS = 3; public final static int TYPE_DOWNLOAD_SUCCESS = 3;
public final static int TYPE_FAILED = 4; public final static int TYPE_DOWNLOAD_FAILED = 4;
public final static int TYPE_DOWNLOADED = 5; public final static int TYPE_DOWNLOADED = 5;
} }

@ -1,8 +1,6 @@
package com.example.musicplayer.download; package com.example.musicplayer.download;
import android.os.AsyncTask; import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import com.example.musicplayer.app.Api; import com.example.musicplayer.app.Api;
@ -64,7 +62,7 @@ public class DownloadTask extends AsyncTask<DownloadInfo, DownloadInfo, Integer>
} }
long contentLength = getContentLength(downloadUrl); //实际文件长度 long contentLength = getContentLength(downloadUrl); //实际文件长度
if (contentLength == 0) { if (contentLength == 0) {
return TYPE_FAILED; return TYPE_DOWNLOAD_FAILED;
} else if (contentLength == downloadedLength) { //已下载 } else if (contentLength == downloadedLength) { //已下载
return TYPE_DOWNLOADED; return TYPE_DOWNLOADED;
} }
@ -87,9 +85,9 @@ public class DownloadTask extends AsyncTask<DownloadInfo, DownloadInfo, Integer>
int len; int len;
while ((len = is.read(b)) != -1) { while ((len = is.read(b)) != -1) {
if (isCanceled) { if (isCanceled) {
return TYPE_CANCELED; return TYPE_DOWNLOAD_CANCELED;
} else if (isPaused) { } else if (isPaused) {
return TYPE_PAUSED; return TYPE_DOWNLOAD_PAUSED;
} else { } else {
total += len; total += len;
saveFile.write(b, 0, len); saveFile.write(b, 0, len);
@ -101,7 +99,7 @@ public class DownloadTask extends AsyncTask<DownloadInfo, DownloadInfo, Integer>
} }
} }
response.body().close(); response.body().close();
return TYPE_SUCCESS; return TYPE_DOWNLOAD_SUCCESS;
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
@ -120,7 +118,7 @@ public class DownloadTask extends AsyncTask<DownloadInfo, DownloadInfo, Integer>
e.printStackTrace(); e.printStackTrace();
} }
} }
return TYPE_FAILED; return TYPE_DOWNLOAD_FAILED;
} }
@Override @Override
@ -136,16 +134,16 @@ public class DownloadTask extends AsyncTask<DownloadInfo, DownloadInfo, Integer>
@Override @Override
protected void onPostExecute(Integer status) { protected void onPostExecute(Integer status) {
switch (status) { switch (status) {
case TYPE_SUCCESS: case TYPE_DOWNLOAD_SUCCESS:
mDownListener.onSuccess(); mDownListener.onSuccess();
break; break;
case TYPE_FAILED: case TYPE_DOWNLOAD_FAILED:
mDownListener.onFailed(); mDownListener.onFailed();
break; break;
case TYPE_PAUSED: case TYPE_DOWNLOAD_PAUSED:
mDownListener.onPaused(); mDownListener.onPaused();
break; break;
case TYPE_CANCELED: case TYPE_DOWNLOAD_CANCELED:
mDownListener.onCanceled(); mDownListener.onCanceled();
break; break;
case TYPE_DOWNLOADED: case TYPE_DOWNLOADED:
@ -163,7 +161,7 @@ public class DownloadTask extends AsyncTask<DownloadInfo, DownloadInfo, Integer>
isCanceled = true; isCanceled = true;
} }
private long getContentLength(String downloadUrl) throws IOException { public long getContentLength(String downloadUrl) throws IOException {
OkHttpClient client = new OkHttpClient(); OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder() Request request = new Request.Builder()
.url(downloadUrl) .url(downloadUrl)

@ -1,5 +1,7 @@
package com.example.musicplayer.entiy; package com.example.musicplayer.entiy;
import org.litepal.crud.LitePalSupport;
/** /**
* <pre> * <pre>
* author : * author :
@ -8,60 +10,77 @@ package com.example.musicplayer.entiy;
* </pre> * </pre>
*/ */
public class DownloadInfo { public class DownloadInfo extends LitePalSupport {
private String songName; private String songName;
private String singer;
private String url; private String url;
private String songId; private String songId;
private int progress; private int progress;
private long currentSize; private long currentSize;
private long totalSize; private long totalSize;
private Song song;
public int getProgress() { public String getSongName() {
return progress; return songName;
} }
public long getCurrentSize() { public void setSongName(String songName) {
return currentSize; this.songName = songName;
} }
public long getTotalSize() { public String getSinger() {
return totalSize; return singer;
} }
public String getSongName() { public void setSinger(String singer) {
return songName; this.singer = singer;
} }
public String getUrl() {
return url;
}
public void setCurrentSize(long currentSize) { public void setUrl(String url) {
this.currentSize = currentSize; this.url = url;
}
public String getSongId() {
return songId;
}
public void setSongId(String songId) {
this.songId = songId;
}
public int getProgress() {
return progress;
} }
public void setProgress(int progress) { public void setProgress(int progress) {
this.progress = progress; this.progress = progress;
} }
public void setSongName(String songName) { public long getCurrentSize() {
this.songName = songName; return currentSize;
} }
public void setTotalSize(long totalSize) { public void setCurrentSize(long currentSize) {
this.totalSize = totalSize; this.currentSize = currentSize;
} }
public String getUrl() { public long getTotalSize() {
return url; return totalSize;
} }
public void setUrl(String url) { public void setTotalSize(long totalSize) {
this.url = url; this.totalSize = totalSize;
} }
public String getSongId() { public Song getSong() {
return songId; return song;
} }
public void setSongId(String songId) { public void setSong(Song song) {
this.songId = songId; this.song = song;
} }
} }

@ -17,6 +17,7 @@ public class HistorySong extends LitePalSupport {
private String pic; private String pic;
private long duration; private long duration;
private boolean isOnline; private boolean isOnline;
private boolean isDownload;
@ -100,4 +101,12 @@ public class HistorySong extends LitePalSupport {
public void setMediaId(String mediaId) { public void setMediaId(String mediaId) {
this.mediaId = mediaId; this.mediaId = mediaId;
} }
public void setDownload(boolean download) {
isDownload = download;
}
public boolean isDownload() {
return isDownload;
}
} }

@ -17,6 +17,7 @@ public class Love extends LitePalSupport{
private String pic; private String pic;
private long duration; private long duration;
private boolean isOnline; private boolean isOnline;
private boolean isDownload;
public int getId() { public int getId() {
@ -99,4 +100,12 @@ public class Love extends LitePalSupport{
public void setMediaId(String mediaId) { public void setMediaId(String mediaId) {
this.mediaId = mediaId; this.mediaId = mediaId;
} }
public boolean isDownload() {
return isDownload;
}
public void setDownload(boolean download) {
isDownload = download;
}
} }

@ -17,6 +17,7 @@ public class OnlineSong extends LitePalSupport {
private String pic; private String pic;
private String lrc; private String lrc;
private long duration; private long duration;
private boolean isDownload;
public int getId() { public int getId() {
@ -98,4 +99,12 @@ public class OnlineSong extends LitePalSupport {
public void setMediaId(String mediaId) { public void setMediaId(String mediaId) {
this.mediaId = mediaId; this.mediaId = mediaId;
} }
public void setDownload(boolean download) {
isDownload = download;
}
public boolean isDownload() {
return isDownload;
}
} }

@ -1,12 +1,14 @@
package com.example.musicplayer.entiy; package com.example.musicplayer.entiy;
import org.litepal.crud.LitePalSupport;
import java.io.Serializable; import java.io.Serializable;
/** /**
* Created by on 2018/10/19. * Created by on 2018/10/19.
*/ */
public class Song implements Serializable { public class Song extends LitePalSupport implements Serializable {
private static final long serialVersionUID=1L; private static final long serialVersionUID=1L;
private String songId; //歌曲id private String songId; //歌曲id
@ -20,62 +22,88 @@ public class Song implements Serializable {
private int current;//在音乐列表的位置 private int current;//在音乐列表的位置
private String imgUrl; //歌曲照片 private String imgUrl; //歌曲照片
private boolean isOnline; //是否为网络歌曲 private boolean isOnline; //是否为网络歌曲
private int listType; //歌曲列表类别 private int listType; //歌曲列表类别,0表示当前没有列表即可能在播放网络歌曲
private boolean isDownload;//是否为下载的歌曲
public String getImgUrl() {
return imgUrl; public String getSongId() {
return songId;
} }
public int getCurrent() { public void setSongId(String songId) {
return current; this.songId = songId;
} }
public long getDuration() { public String getQqId() {
return duration; return qqId;
} }
public long getCurrentTime() { public void setQqId(String qqId) {
return currentTime; this.qqId = qqId;
} }
public String getUrl() { public String getMediaId() {
return url; return mediaId;
}
public void setMediaId(String mediaId) {
this.mediaId = mediaId;
} }
public String getSinger() { public String getSinger() {
return singer; return singer;
} }
public void setSinger(String singer) {
this.singer = singer;
}
public long getDuration() {
return duration;
}
public void setDuration(long duration) {
this.duration = duration;
}
public String getSongName() { public String getSongName() {
return songName; return songName;
} }
public void setImgUrl(String imgUrl) { public void setSongName(String songName) {
this.imgUrl = imgUrl; this.songName = songName;
} }
public void setCurrent(int current) { public String getUrl() {
this.current = current; return url;
}
public void setUrl(String url) {
this.url = url;
}
public long getCurrentTime() {
return currentTime;
} }
public void setCurrentTime(long currentTime) { public void setCurrentTime(long currentTime) {
this.currentTime = currentTime; this.currentTime = currentTime;
} }
public void setDuration(long duration) { public int getCurrent() {
this.duration = duration; return current;
} }
public void setUrl(String url) { public void setCurrent(int current) {
this.url = url; this.current = current;
} }
public void setSinger(String singer) { public String getImgUrl() {
this.singer = singer; return imgUrl;
} }
public void setSongName(String songName) { public void setImgUrl(String imgUrl) {
this.songName = songName; this.imgUrl = imgUrl;
} }
public boolean isOnline() { public boolean isOnline() {
@ -94,28 +122,12 @@ public class Song implements Serializable {
this.listType = listType; this.listType = listType;
} }
public String getSongId() { public boolean isDownload() {
return songId; return isDownload;
}
public void setSongId(String songId) {
this.songId = songId;
}
public String getQqId() {
return qqId;
}
public void setQqId(String qqId) {
this.qqId = qqId;
} }
public String getMediaId() { public void setDownload(boolean download) {
return mediaId; isDownload = download;
}
public void setMediaId(String mediaId) {
this.mediaId = mediaId;
} }
public String toString(){ public String toString(){

@ -0,0 +1,24 @@
package com.example.musicplayer.event;
/**
* <pre>
* author :
* time : 2019/09/20
* desc :
* </pre>
*/
public class SongListNumEvent {
private int type;
public SongListNumEvent(int type){
this.type = type;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
}

@ -120,6 +120,7 @@ public class DbHelperImpl implements DbHelper {
love.setOnline(song.isOnline()); love.setOnline(song.isOnline());
love.setQqId(song.getQqId()); love.setQqId(song.getQqId());
love.setMediaId(song.getMediaId()); love.setMediaId(song.getMediaId());
love.setDownload(song.isDownload());
return love.save(); return love.save();
} }

@ -1,9 +1,11 @@
package com.example.musicplayer.presenter; package com.example.musicplayer.presenter;
import com.example.musicplayer.app.Constant;
import com.example.musicplayer.base.presenter.BasePresenter; import com.example.musicplayer.base.presenter.BasePresenter;
import com.example.musicplayer.contract.ILocalContract; import com.example.musicplayer.contract.ILocalContract;
import com.example.musicplayer.entiy.LocalSong; import com.example.musicplayer.entiy.LocalSong;
import com.example.musicplayer.event.SongListNumEvent;
import com.example.musicplayer.event.SongLocalSizeChangeEvent; import com.example.musicplayer.event.SongLocalSizeChangeEvent;
import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.EventBus;
@ -30,7 +32,7 @@ public class LocalPresenter extends BasePresenter<ILocalContract.View> implement
@Override @Override
public void saveSong(List<LocalSong> localSongs) { public void saveSong(List<LocalSong> localSongs) {
if(mModel.saveSong(localSongs)) { if(mModel.saveSong(localSongs)) {
EventBus.getDefault().post(new SongLocalSizeChangeEvent()); EventBus.getDefault().post(new SongListNumEvent(Constant.LIST_TYPE_LOCAL));
mView.showToast("成功导入本地音乐"); mView.showToast("成功导入本地音乐");
mView.showMusicList(localSongs); mView.showMusicList(localSongs);
} }

@ -24,10 +24,13 @@ import com.example.musicplayer.entiy.DownloadInfo;
import com.example.musicplayer.entiy.DownloadSong; import com.example.musicplayer.entiy.DownloadSong;
import com.example.musicplayer.entiy.Song; import com.example.musicplayer.entiy.Song;
import com.example.musicplayer.event.DownloadEvent; import com.example.musicplayer.event.DownloadEvent;
import com.example.musicplayer.event.SongDownloadedEvent;
import com.example.musicplayer.event.SongListNumEvent;
import com.example.musicplayer.util.CommonUtil; import com.example.musicplayer.util.CommonUtil;
import com.example.musicplayer.view.MainActivity; import com.example.musicplayer.view.MainActivity;
import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.EventBus;
import org.litepal.LitePal;
import java.io.File; import java.io.File;
import java.util.HashMap; import java.util.HashMap;
@ -48,7 +51,6 @@ public class DownloadService extends Service {
private DownloadTask downloadTask; private DownloadTask downloadTask;
private String downloadUrl; private String downloadUrl;
private DownloadBinder downloadBinder = new DownloadBinder(); private DownloadBinder downloadBinder = new DownloadBinder();
private HashMap<String, Song> downloadingMap = new HashMap<>();
private LinkedList<Song> downloadQueue = new LinkedList<>();//等待队列 private LinkedList<Song> downloadQueue = new LinkedList<>();//等待队列
private DownloadListener listener = new DownloadListener() { private DownloadListener listener = new DownloadListener() {
@Override @Override
@ -60,8 +62,7 @@ public class DownloadService extends Service {
@Override @Override
public void onSuccess() { public void onSuccess() {
downloadTask = null; downloadTask = null;
saveToDb(); //下载成功,则保存数据到数据库 saveToDb(); //下载成功,则保存数据到数据库,顺便从下载数据库中移除
EventBus.getDefault().post(new DownloadEvent(Constant.TYPE_SUCCESS));//通知已下载列表
start();//下载队列中的其它歌曲 start();//下载队列中的其它歌曲
//下载成功通知前台服务通知关闭,并创建一个下载成功的通知 //下载成功通知前台服务通知关闭,并创建一个下载成功的通知
stopForeground(true); stopForeground(true);
@ -77,6 +78,7 @@ public class DownloadService extends Service {
@Override @Override
public void onFailed() { public void onFailed() {
downloadTask = null; downloadTask = null;
//下载失败通知前台服务通知关闭,并创建一个下载失败的通知 //下载失败通知前台服务通知关闭,并创建一个下载失败的通知
stopForeground(true); stopForeground(true);
getNotificationManager().notify(1, getNotification("下载失败", -1)); getNotificationManager().notify(1, getNotification("下载失败", -1));
@ -86,6 +88,9 @@ public class DownloadService extends Service {
@Override @Override
public void onPaused() { public void onPaused() {
downloadTask = null; downloadTask = null;
downloadQueue.poll();//从下载列表中移除该歌曲
start();//下载下载列表中的歌曲
EventBus.getDefault().post(new DownloadEvent(Constant.TYPE_DOWNLOAD_PAUSED)); //下载暂停
Toast.makeText(DownloadService.this, "下载已暂停", Toast.LENGTH_SHORT).show(); Toast.makeText(DownloadService.this, "下载已暂停", Toast.LENGTH_SHORT).show();
} }
@ -106,6 +111,12 @@ public class DownloadService extends Service {
public class DownloadBinder extends Binder { public class DownloadBinder extends Binder {
public void startDownload(Song song) { public void startDownload(Song song) {
downloadQueue.offer(song);//将歌曲放到等待队列中 downloadQueue.offer(song);//将歌曲放到等待队列中
try {
postDownloadEvent(song);//通知正在下载界面
} catch (Exception e) {
e.printStackTrace();
}
if (downloadTask != null) { if (downloadTask != null) {
CommonUtil.showToast(DownloadService.this, "已经加入下载队列"); CommonUtil.showToast(DownloadService.this, "已经加入下载队列");
} else { } else {
@ -120,26 +131,41 @@ public class DownloadService extends Service {
} }
} }
public void cancelDownload() { public void resumeDownload() {
if (downloadTask != null) { start();
}
public void cancelDownload(String downloadUrl,String songId) {
//如果该歌曲正在下载则需要将downloadTask置为null
if (downloadTask != null&&downloadQueue.peek().getSongId().equals(songId)) {
downloadTask.cancelDownload(); downloadTask.cancelDownload();
} else { }
if (downloadUrl != null) { //将该歌曲从下载队列中移除
//取消下载需要将文件删除并将通知关闭 for (int i = 0; i < downloadQueue.size(); i++) {
String fileName = downloadUrl.substring(downloadUrl.lastIndexOf("/") + 1, downloadUrl.indexOf("?")); Song song = downloadQueue.get(i);
File downloadFile = new File(Api.STORAGE_SONG_FILE); if(song.getSongId().equals(songId)) downloadQueue.remove(i);
String directory = String.valueOf(downloadFile); }
File file = new File(fileName + directory); //将该歌曲从正在下载的数据库中移除
if (file.exists()) { LitePal.deleteAll(DownloadInfo.class, "songId=?", songId);//删除已下载歌曲的相关列
file.delete(); //通知正在下载列表
} EventBus.getDefault().post(new DownloadEvent(Constant.TYPE_DOWNLOAD_CANCELED));
getNotificationManager().cancel(1); //取消下载需要将文件删除并将通知关闭
stopForeground(true); if (downloadUrl != null) {
Toast.makeText(DownloadService.this, "下载已取消", Toast.LENGTH_SHORT).show(); String fileName = downloadUrl.substring(downloadUrl.lastIndexOf("/") + 1, downloadUrl.indexOf("?"));
File downloadFile = new File(Api.STORAGE_SONG_FILE);
String directory = String.valueOf(downloadFile);
File file = new File(fileName ,directory);
if (file.exists()) {
file.delete();
} }
getNotificationManager().cancel(1);
stopForeground(true);
Toast.makeText(DownloadService.this, "下载已取消", Toast.LENGTH_SHORT).show();
} }
} }
}
}
private void start() { private void start() {
if (downloadTask == null && !downloadQueue.isEmpty()) { if (downloadTask == null && !downloadQueue.isEmpty()) {
@ -148,6 +174,8 @@ public class DownloadService extends Service {
downloadInfo.setSongId(song.getSongId()); downloadInfo.setSongId(song.getSongId());
downloadInfo.setUrl(song.getUrl()); downloadInfo.setUrl(song.getUrl());
downloadInfo.setSongName(song.getSongName()); downloadInfo.setSongName(song.getSongName());
downloadInfo.setSinger(song.getSinger());
downloadInfo.setSong(song);
downloadUrl = song.getUrl(); downloadUrl = song.getUrl();
downloadTask = new DownloadTask(listener); downloadTask = new DownloadTask(listener);
downloadTask.execute(downloadInfo); downloadTask.execute(downloadInfo);
@ -193,6 +221,8 @@ public class DownloadService extends Service {
private void saveToDb() { private void saveToDb() {
Song song = downloadQueue.poll(); Song song = downloadQueue.poll();
LitePal.deleteAll(DownloadInfo.class, "songId=?", song.getSongId());//删除已下载歌曲的相关列
LitePal.deleteAll(Song.class, "songId=?", song.getSongId());//删除已下载歌曲的关联表中的相关列
DownloadSong downloadSong = new DownloadSong(); DownloadSong downloadSong = new DownloadSong();
downloadSong.setName(song.getSongName()); downloadSong.setName(song.getSongName());
downloadSong.setSongId(song.getSongId()); downloadSong.setSongId(song.getSongId());
@ -202,5 +232,19 @@ public class DownloadService extends Service {
downloadSong.setMediaId(song.getMediaId()); downloadSong.setMediaId(song.getMediaId());
downloadSong.setUrl(Api.STORAGE_SONG_FILE + "C400" + song.getMediaId() + ".m4a"); downloadSong.setUrl(Api.STORAGE_SONG_FILE + "C400" + song.getMediaId() + ".m4a");
downloadSong.save(); downloadSong.save();
EventBus.getDefault().post(new DownloadEvent(Constant.TYPE_DOWNLOAD_SUCCESS));//通知已下载列表
EventBus.getDefault().post(new SongListNumEvent(Constant.LIST_TYPE_DOWNLOAD)); //通知主界面的下载个数需要改变
}
private void postDownloadEvent(Song song) {
DownloadInfo downloadInfo = new DownloadInfo();
downloadInfo.setSongName(song.getSongName());
downloadInfo.setSongId(song.getSongId());
downloadInfo.setUrl(song.getUrl());
downloadInfo.setProgress(0);
downloadInfo.setSinger(song.getSinger());
downloadInfo.setSong(song);
song.save();
downloadInfo.save();
} }
} }

@ -23,6 +23,7 @@ import com.example.musicplayer.event.SongAlbumEvent;
import com.example.musicplayer.event.SongCollectionEvent; import com.example.musicplayer.event.SongCollectionEvent;
import com.example.musicplayer.event.SongDownloadedEvent; import com.example.musicplayer.event.SongDownloadedEvent;
import com.example.musicplayer.event.SongHistoryEvent; import com.example.musicplayer.event.SongHistoryEvent;
import com.example.musicplayer.event.SongListNumEvent;
import com.example.musicplayer.event.SongLocalEvent; import com.example.musicplayer.event.SongLocalEvent;
import com.example.musicplayer.event.SongStatusEvent; import com.example.musicplayer.event.SongStatusEvent;
import com.example.musicplayer.model.https.RetrofitFactory; import com.example.musicplayer.model.https.RetrofitFactory;
@ -103,7 +104,11 @@ public class PlayerService extends Service {
mCurrent=getNextCurrent(mCurrent, mPlayMode, mDownloadList.size());//根据播放模式来播放下一曲 mCurrent=getNextCurrent(mCurrent, mPlayMode, mDownloadList.size());//根据播放模式来播放下一曲
saveDownloadInfo(mCurrent); saveDownloadInfo(mCurrent);
} }
mPlayStatusBinder.play(mListType); if(mListType!=0) {
mPlayStatusBinder.play(mListType);
}else {
mPlayStatusBinder.stop();
}
}); });
/** /**
* MediaPlayersetOnCompletionListener * MediaPlayersetOnCompletionListener
@ -237,7 +242,7 @@ public class PlayerService extends Service {
mCurrent=getNextCurrent(mCurrent, mPlayMode, mDownloadList.size());//根据播放模式来播放下一曲 mCurrent=getNextCurrent(mCurrent, mPlayMode, mDownloadList.size());//根据播放模式来播放下一曲
saveDownloadInfo(mCurrent); saveDownloadInfo(mCurrent);
} }
mPlayStatusBinder.play(mListType); if(mListType!=0) mPlayStatusBinder.play(mListType);
} }
public void last() { public void last() {
@ -259,7 +264,7 @@ public class PlayerService extends Service {
mCurrent = getLastCurrent(mCurrent,mPlayMode,mDownloadList.size()); mCurrent = getLastCurrent(mCurrent,mPlayMode,mDownloadList.size());
saveDownloadInfo(mCurrent); saveDownloadInfo(mCurrent);
} }
mPlayStatusBinder.play(mListType); if(mListType!=0) mPlayStatusBinder.play(mListType);
} }
/** /**
@ -362,6 +367,7 @@ public class PlayerService extends Service {
song.setOnline(love.isOnline()); song.setOnline(love.isOnline());
song.setDuration(love.getDuration()); song.setDuration(love.getDuration());
song.setMediaId(love.getMediaId()); song.setMediaId(love.getMediaId());
song.setDownload(love.isDownload());
FileUtil.saveSong(song); FileUtil.saveSong(song);
} }
@ -380,6 +386,7 @@ public class PlayerService extends Service {
song.setOnline(false); song.setOnline(false);
song.setDuration(downloadSong.getDuration()); song.setDuration(downloadSong.getDuration());
song.setMediaId(downloadSong.getMediaId()); song.setMediaId(downloadSong.getMediaId());
song.setDownload(true);
FileUtil.saveSong(song); FileUtil.saveSong(song);
} }
@ -398,6 +405,7 @@ public class PlayerService extends Service {
song.setOnline(historySong.isOnline()); song.setOnline(historySong.isOnline());
song.setDuration(historySong.getDuration()); song.setDuration(historySong.getDuration());
song.setMediaId(historySong.getMediaId()); song.setMediaId(historySong.getMediaId());
song.setDownload(historySong.isDownload());
FileUtil.saveSong(song); FileUtil.saveSong(song);
} }
@ -422,10 +430,13 @@ public class PlayerService extends Service {
history.setOnline(song.isOnline()); history.setOnline(song.isOnline());
history.setDuration(song.getDuration()); history.setDuration(song.getDuration());
history.setMediaId(song.getMediaId()); history.setMediaId(song.getMediaId());
history.setDownload(song.isDownload());
history.saveAsync().listen(new SaveCallback() { history.saveAsync().listen(new SaveCallback() {
@Override @Override
public void onFinish(boolean success) { public void onFinish(boolean success) {
if (success) { if (success) {
//告诉主界面最近播放的数目需要改变
EventBus.getDefault().post(new SongListNumEvent(Constant.LIST_TYPE_HISTORY));
if (LitePal.findAll(HistorySong.class).size() > Constant.HISTORY_MAX_SIZE) { if (LitePal.findAll(HistorySong.class).size() > Constant.HISTORY_MAX_SIZE) {
LitePal.delete(HistorySong.class, LitePal.findFirst(HistorySong.class).getId()); LitePal.delete(HistorySong.class, LitePal.findFirst(HistorySong.class).getId());
} }

@ -43,9 +43,10 @@ import com.example.musicplayer.app.Api;
import com.example.musicplayer.app.Constant; import com.example.musicplayer.app.Constant;
import com.example.musicplayer.base.activity.BaseMvpActivity; import com.example.musicplayer.base.activity.BaseMvpActivity;
import com.example.musicplayer.contract.IPlayContract; import com.example.musicplayer.contract.IPlayContract;
import com.example.musicplayer.entiy.DownloadInfo; import com.example.musicplayer.entiy.DownloadSong;
import com.example.musicplayer.entiy.LocalSong; import com.example.musicplayer.entiy.LocalSong;
import com.example.musicplayer.entiy.Song; import com.example.musicplayer.entiy.Song;
import com.example.musicplayer.event.DownloadEvent;
import com.example.musicplayer.event.SongCollectionEvent; import com.example.musicplayer.event.SongCollectionEvent;
import com.example.musicplayer.event.SongStatusEvent; import com.example.musicplayer.event.SongStatusEvent;
import com.example.musicplayer.presenter.PlayPresenter; import com.example.musicplayer.presenter.PlayPresenter;
@ -64,18 +65,11 @@ import com.example.musicplayer.widget.LrcView;
import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode; import org.greenrobot.eventbus.ThreadMode;
import org.litepal.LitePal;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List; import java.util.List;
import butterknife.BindView; import butterknife.BindView;
import okhttp3.Connection;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
/** /**
* *
@ -185,7 +179,7 @@ public class PlayActivity extends BaseMvpActivity<PlayPresenter> implements IPla
} }
}; };
//绑定下载服务 //绑定下载服务
private ServiceConnection mDownloadConnection =new ServiceConnection() { private ServiceConnection mDownloadConnection = new ServiceConnection() {
@Override @Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) { public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
mDownloadBinder = (DownloadService.DownloadBinder) iBinder; mDownloadBinder = (DownloadService.DownloadBinder) iBinder;
@ -226,9 +220,9 @@ public class PlayActivity extends BaseMvpActivity<PlayPresenter> implements IPla
//绑定服务,播放和下载的服务 //绑定服务,播放和下载的服务
Intent playIntent = new Intent(PlayActivity.this, PlayerService.class); Intent playIntent = new Intent(PlayActivity.this, PlayerService.class);
Intent downIntent = new Intent(PlayActivity.this,DownloadService.class); Intent downIntent = new Intent(PlayActivity.this, DownloadService.class);
bindService(playIntent, mPlayConnection, Context.BIND_AUTO_CREATE); bindService(playIntent, mPlayConnection, Context.BIND_AUTO_CREATE);
bindService(downIntent,mDownloadConnection,Context.BIND_AUTO_CREATE); bindService(downIntent, mDownloadConnection, Context.BIND_AUTO_CREATE);
//界面填充 //界面填充
mSong = FileUtil.getSong(); mSong = FileUtil.getSong();
@ -239,19 +233,31 @@ public class PlayActivity extends BaseMvpActivity<PlayPresenter> implements IPla
mSeekBar.setMax((int) mSong.getDuration()); mSeekBar.setMax((int) mSong.getDuration());
mSeekBar.setProgress((int) mSong.getCurrentTime()); mSeekBar.setProgress((int) mSong.getCurrentTime());
mDownLoadIv.setVisibility(mSong.isOnline() ? View.VISIBLE : View.GONE); //下载按钮是否隐藏 mDownLoadIv.setVisibility(mSong.isOnline() ? View.VISIBLE : View.GONE); //下载按钮是否隐藏
mDownLoadIv.setImageDrawable(mSong.isDownload() ? getDrawable(R.drawable.downloaded) : getDrawable(R.drawable.download_song));
mPlayMode = mPresenter.getPlayMode();//得到播放模式 mPlayMode = mPresenter.getPlayMode();//得到播放模式
if(mPlayMode == Constant.PLAY_ORDER){ if (mPlayMode == Constant.PLAY_ORDER) {
mPlayModeBtn.setBackground(getDrawable(R.drawable.play_mode_order)); mPlayModeBtn.setBackground(getDrawable(R.drawable.play_mode_order));
}else if(mPlayMode == Constant.PLAY_RANDOM){ } else if (mPlayMode == Constant.PLAY_RANDOM) {
mPlayModeBtn.setBackground(getDrawable(R.drawable.play_mode_random)); mPlayModeBtn.setBackground(getDrawable(R.drawable.play_mode_random));
}else { } else {
mPlayModeBtn.setBackground(getDrawable(R.drawable.play_mode_single)); mPlayModeBtn.setBackground(getDrawable(R.drawable.play_mode_single));
} }
} }
@Subscribe(threadMode = ThreadMode.MAIN)
public void onDownloadSuccessEvent(DownloadEvent event){
if(event.getDownloadStatus() == Constant.TYPE_DOWNLOAD_SUCCESS){
mDownLoadIv.setImageDrawable(
LitePal.where("songId=?", mSong.getSongId()).find(DownloadSong.class).size() != 0
? getDrawable(R.drawable.downloaded)
: getDrawable(R.drawable.download_song));
}
}
@Override @Override
protected PlayPresenter getPresenter() { protected PlayPresenter getPresenter() {
//与Presenter建立关系 //与Presenter建立关系
@ -341,7 +347,7 @@ public class PlayActivity extends BaseMvpActivity<PlayPresenter> implements IPla
public void onStopTrackingTouch(SeekBar seekBar) { public void onStopTrackingTouch(SeekBar seekBar) {
if (mPlayStatusBinder.isPlaying()) { if (mPlayStatusBinder.isPlaying()) {
mMediaPlayer = mPlayStatusBinder.getMediaPlayer(); mMediaPlayer = mPlayStatusBinder.getMediaPlayer();
mMediaPlayer.seekTo(seekBar.getProgress()*1000); mMediaPlayer.seekTo(seekBar.getProgress() * 1000);
startUpdateSeekBarProgress(); startUpdateSeekBarProgress();
} else { } else {
time = seekBar.getProgress(); time = seekBar.getProgress();
@ -367,8 +373,8 @@ public class PlayActivity extends BaseMvpActivity<PlayPresenter> implements IPla
mPlayStatusBinder.resume(); mPlayStatusBinder.resume();
flag = false; flag = false;
if (isSeek) { if (isSeek) {
Log.d(TAG, "onClick: "+time); Log.d(TAG, "onClick: " + time);
mMediaPlayer.seekTo(time*1000); mMediaPlayer.seekTo(time * 1000);
isSeek = false; isSeek = false;
} }
mDisc.play(); mDisc.play();
@ -380,7 +386,7 @@ public class PlayActivity extends BaseMvpActivity<PlayPresenter> implements IPla
} else { } else {
mPlayStatusBinder.play(mListType); mPlayStatusBinder.play(mListType);
} }
mMediaPlayer.seekTo((int) mSong.getCurrentTime()*1000); mMediaPlayer.seekTo((int) mSong.getCurrentTime() * 1000);
mDisc.play(); mDisc.play();
mPlayBtn.setSelected(true); mPlayBtn.setSelected(true);
startUpdateSeekBarProgress(); startUpdateSeekBarProgress();
@ -419,18 +425,18 @@ public class PlayActivity extends BaseMvpActivity<PlayPresenter> implements IPla
String lrc = FileUtil.getLrcFromNative(mSong.getSongName()); String lrc = FileUtil.getLrcFromNative(mSong.getSongName());
if (null == lrc) { if (null == lrc) {
String qqId = mSong.getQqId(); String qqId = mSong.getQqId();
if(Constant.SONG_ID_UNFIND.equals(qqId)){//匹配不到歌词 if (Constant.SONG_ID_UNFIND.equals(qqId)) {//匹配不到歌词
getLrcError(null); getLrcError(null);
}else if(null == qqId){//歌曲的id还未匹配 } else if (null == qqId) {//歌曲的id还未匹配
mPresenter.getSongId(mSong.getSongName(),mSong.getDuration()); mPresenter.getSongId(mSong.getSongName(), mSong.getDuration());
}else {//歌词还未匹配 } else {//歌词还未匹配
mPresenter.getLrc(qqId,Constant.SONG_LOCAL); mPresenter.getLrc(qqId, Constant.SONG_LOCAL);
} }
}else { } else {
showLrc(lrc); showLrc(lrc);
} }
} else { } else {
mPresenter.getLrc(mSong.getSongId(),Constant.SONG_ONLINE); mPresenter.getLrc(mSong.getSongId(), Constant.SONG_ONLINE);
} }
} }
); );
@ -441,7 +447,11 @@ public class PlayActivity extends BaseMvpActivity<PlayPresenter> implements IPla
}); });
//歌曲下载 //歌曲下载
mDownLoadIv.setOnClickListener(v -> { mDownLoadIv.setOnClickListener(v -> {
mDownloadBinder.startDownload(mSong); if (mSong.isDownload()) {
showToast(getString(R.string.downloded));
} else {
mDownloadBinder.startDownload(mSong);
}
}); });
} }
@ -647,20 +657,20 @@ public class PlayActivity extends BaseMvpActivity<PlayPresenter> implements IPla
@Override @Override
public void getSongIdSuccess(String songId) { public void getSongIdSuccess(String songId) {
Log.d(TAG, "getSongIdSuccess: "+songId); Log.d(TAG, "getSongIdSuccess: " + songId);
setLocalSongId(songId);//保存音乐信息 setLocalSongId(songId);//保存音乐信息
mPresenter.getLrc(songId,Constant.SONG_LOCAL);//获取歌词 mPresenter.getLrc(songId, Constant.SONG_LOCAL);//获取歌词
} }
@Override @Override
public void saveLrc(String lrc) { public void saveLrc(String lrc) {
FileUtil.saveLrcToNative(lrc,mSong.getSongName()); FileUtil.saveLrcToNative(lrc, mSong.getSongName());
} }
//改变播放模式 //改变播放模式
private void changePlayMode(){ private void changePlayMode() {
View playModeView = LayoutInflater.from(this).inflate(R.layout.play_mode,null); View playModeView = LayoutInflater.from(this).inflate(R.layout.play_mode, null);
ConstraintLayout orderLayout = playModeView.findViewById(R.id.orderLayout); ConstraintLayout orderLayout = playModeView.findViewById(R.id.orderLayout);
ConstraintLayout randomLayout = playModeView.findViewById(R.id.randomLayout); ConstraintLayout randomLayout = playModeView.findViewById(R.id.randomLayout);
ConstraintLayout singleLayout = playModeView.findViewById(R.id.singleLayout); ConstraintLayout singleLayout = playModeView.findViewById(R.id.singleLayout);
@ -669,7 +679,7 @@ public class PlayActivity extends BaseMvpActivity<PlayPresenter> implements IPla
TextView singleTv = playModeView.findViewById(R.id.singleTv); TextView singleTv = playModeView.findViewById(R.id.singleTv);
//显示弹窗 //显示弹窗
PopupWindow popupWindow = new PopupWindow(playModeView, ScreenUtil.dip2px(this,130),ScreenUtil.dip2px(this,150)); PopupWindow popupWindow = new PopupWindow(playModeView, ScreenUtil.dip2px(this, 130), ScreenUtil.dip2px(this, 150));
//设置背景色 //设置背景色
popupWindow.setBackgroundDrawable(getDrawable(R.color.transparent)); popupWindow.setBackgroundDrawable(getDrawable(R.color.transparent));
//设置焦点 //设置焦点
@ -678,20 +688,20 @@ public class PlayActivity extends BaseMvpActivity<PlayPresenter> implements IPla
popupWindow.setOutsideTouchable(true); popupWindow.setOutsideTouchable(true);
popupWindow.update(); popupWindow.update();
//设置弹出的位置 //设置弹出的位置
popupWindow.showAsDropDown(mPlayModeBtn,0,-50); popupWindow.showAsDropDown(mPlayModeBtn, 0, -50);
//显示播放模式 //显示播放模式
int mode = mPresenter.getPlayMode(); int mode = mPresenter.getPlayMode();
if(mode == Constant.PLAY_ORDER){ if (mode == Constant.PLAY_ORDER) {
orderTv.setSelected(true); orderTv.setSelected(true);
randomTv.setSelected(false); randomTv.setSelected(false);
singleTv.setSelected(false); singleTv.setSelected(false);
}else if(mode == Constant.PLAY_RANDOM){ } else if (mode == Constant.PLAY_RANDOM) {
randomTv.setSelected(true); randomTv.setSelected(true);
orderTv.setSelected(false); orderTv.setSelected(false);
singleTv.setSelected(false); singleTv.setSelected(false);
}else { } else {
singleTv.setSelected(true); singleTv.setSelected(true);
randomTv.setSelected(false); randomTv.setSelected(false);
orderTv.setSelected(false); orderTv.setSelected(false);

@ -21,6 +21,7 @@ import com.example.musicplayer.entiy.LocalSong;
import com.example.musicplayer.entiy.Love; import com.example.musicplayer.entiy.Love;
import com.example.musicplayer.event.AlbumCollectionEvent; import com.example.musicplayer.event.AlbumCollectionEvent;
import com.example.musicplayer.event.DownloadEvent; import com.example.musicplayer.event.DownloadEvent;
import com.example.musicplayer.event.SongListNumEvent;
import com.example.musicplayer.event.SongLocalSizeChangeEvent; import com.example.musicplayer.event.SongLocalSizeChangeEvent;
import com.example.musicplayer.view.main.collection.CollectionFragment; import com.example.musicplayer.view.main.collection.CollectionFragment;
import com.example.musicplayer.view.main.download.DownloadFragment; import com.example.musicplayer.view.main.download.DownloadFragment;
@ -126,18 +127,19 @@ public class MainFragment extends Fragment {
} }
@Subscribe(threadMode = ThreadMode.MAIN) @Subscribe(threadMode = ThreadMode.MAIN)
public void onLocalSizeEvent(SongLocalSizeChangeEvent event) { public void onSongListEvent(SongListNumEvent event){
mLocalMusicNum.setText(String.valueOf(LitePal.findAll(LocalSong.class).size())); int type = event.getType();
} if(type == Constant.LIST_TYPE_HISTORY){
mHistoryMusicNum.setText(String.valueOf(LitePal.findAll(HistorySong.class).size()));
@Subscribe(threadMode = ThreadMode.MAIN,sticky = true) }else if(type == Constant.LIST_TYPE_LOCAL){
public void onDownloadSuccessEvent(DownloadEvent event){ mLocalMusicNum.setText(String.valueOf(LitePal.findAll(LocalSong.class).size()));
if(event.getDownloadStatus() == Constant.TYPE_SUCCESS){ }else if(type == Constant.LIST_TYPE_DOWNLOAD){
mDownloadMusicNum.setText(String.valueOf(LitePal.findAll(DownloadSong.class).size())); mDownloadMusicNum.setText(String.valueOf(LitePal.findAll(DownloadSong.class).size()));
} }
} }
private void onClick() { private void onClick() {
//本地音乐 //本地音乐
mLocalMusicLinear.setOnClickListener(v -> replaceFragment(new LocalFragment())); mLocalMusicLinear.setOnClickListener(v -> replaceFragment(new LocalFragment()));

@ -11,7 +11,6 @@ import android.support.annotation.Nullable;
import android.support.v4.app.Fragment; import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView; import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
@ -19,9 +18,7 @@ import android.view.ViewGroup;
import com.example.musicplayer.R; import com.example.musicplayer.R;
import com.example.musicplayer.adapter.DownloadSongAdapter; import com.example.musicplayer.adapter.DownloadSongAdapter;
import com.example.musicplayer.app.Constant; import com.example.musicplayer.app.Constant;
import com.example.musicplayer.callback.OnItemClickListener;
import com.example.musicplayer.entiy.DownloadSong; import com.example.musicplayer.entiy.DownloadSong;
import com.example.musicplayer.entiy.Love;
import com.example.musicplayer.entiy.Song; import com.example.musicplayer.entiy.Song;
import com.example.musicplayer.event.DownloadEvent; import com.example.musicplayer.event.DownloadEvent;
import com.example.musicplayer.event.SongDownloadedEvent; import com.example.musicplayer.event.SongDownloadedEvent;
@ -112,6 +109,7 @@ public class DownloadMusicFragment extends Fragment {
song.setDuration(downloadSong.getDuration()); song.setDuration(downloadSong.getDuration());
song.setListType(Constant.LIST_TYPE_DOWNLOAD); song.setListType(Constant.LIST_TYPE_DOWNLOAD);
song.setMediaId(downloadSong.getMediaId()); song.setMediaId(downloadSong.getMediaId());
song.setDownload(true);
FileUtil.saveSong(song); FileUtil.saveSong(song);
mPlayStatusBinder.play(Constant.LIST_TYPE_DOWNLOAD); mPlayStatusBinder.play(Constant.LIST_TYPE_DOWNLOAD);
@ -120,7 +118,7 @@ public class DownloadMusicFragment extends Fragment {
@Subscribe(threadMode = ThreadMode.MAIN) @Subscribe(threadMode = ThreadMode.MAIN)
public void onDownloadSuccessEvent(DownloadEvent event){ public void onDownloadSuccessEvent(DownloadEvent event){
if(event.getDownloadStatus() == Constant.TYPE_SUCCESS){ if(event.getDownloadStatus() == Constant.TYPE_DOWNLOAD_SUCCESS){
mDownloadSongList.clear(); mDownloadSongList.clear();
mDownloadSongList.addAll(orderList(LitePal.findAll(DownloadSong.class))); mDownloadSongList.addAll(orderList(LitePal.findAll(DownloadSong.class)));
mAdapter.notifyDataSetChanged(); mAdapter.notifyDataSetChanged();

@ -1,6 +1,12 @@
package com.example.musicplayer.view.main.download; package com.example.musicplayer.view.main.download;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle; import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import android.support.annotation.Nullable; import android.support.annotation.Nullable;
import android.support.v4.app.Fragment; import android.support.v4.app.Fragment;
@ -11,17 +17,23 @@ import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import com.example.SpeedDialog.dialog.SpeedDialog;
import com.example.SpeedDialog.listener.OnSelectClickListener;
import com.example.musicplayer.R; import com.example.musicplayer.R;
import com.example.musicplayer.adapter.DownloadingAdapter; import com.example.musicplayer.adapter.DownloadingAdapter;
import com.example.musicplayer.app.Constant; import com.example.musicplayer.app.Constant;
import com.example.musicplayer.entiy.DownloadInfo; import com.example.musicplayer.entiy.DownloadInfo;
import com.example.musicplayer.event.DownloadEvent; import com.example.musicplayer.event.DownloadEvent;
import com.example.musicplayer.service.DownloadService;
import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode; import org.greenrobot.eventbus.ThreadMode;
import org.litepal.LitePal;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List; import java.util.List;
import butterknife.BindView; import butterknife.BindView;
@ -44,7 +56,24 @@ public class DownloadingFragment extends Fragment {
Unbinder unbinder; Unbinder unbinder;
private DownloadingAdapter mAdapter; private DownloadingAdapter mAdapter;
private LinearLayoutManager mLinearLayoutManager; private LinearLayoutManager mLinearLayoutManager;
private List<DownloadInfo> mDownloadInfoList; private List<DownloadInfo> mDownloadInfoList; //下载队列
private List<String> mDownloadSongId; //用来判断当前下载的歌曲
private HashMap<String,Integer> mSongPositionMap;//歌曲Id获取歌曲位置
private boolean isTouch;
private DownloadService.DownloadBinder mDownloadBinder;
//绑定下载服务
private ServiceConnection mDownloadConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
mDownloadBinder = (DownloadService.DownloadBinder) iBinder;
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
}
};
@Nullable @Nullable
@Override @Override
@ -52,7 +81,6 @@ public class DownloadingFragment extends Fragment {
View view = inflater.inflate(R.layout.fragment_download_ing, container, false); View view = inflater.inflate(R.layout.fragment_download_ing, container, false);
EventBus.getDefault().register(this); EventBus.getDefault().register(this);
unbinder = ButterKnife.bind(this, view); unbinder = ButterKnife.bind(this, view);
return view; return view;
} }
@ -60,27 +88,79 @@ public class DownloadingFragment extends Fragment {
@Override @Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) { public void onActivityCreated(@Nullable Bundle savedInstanceState) {
initRecycler(); initRecycler();
//绑定服务
Intent downIntent = new Intent(getActivity(), DownloadService.class);
getActivity().bindService(downIntent, mDownloadConnection, Context.BIND_AUTO_CREATE);
super.onActivityCreated(savedInstanceState); super.onActivityCreated(savedInstanceState);
} }
private void initRecycler() { private void initRecycler() {
mDownloadInfoList = new ArrayList<>(); mDownloadInfoList = new LinkedList<>();
mDownloadSongId = new ArrayList<>();
mDownloadSongId.add("");
mDownloadInfoList.addAll(orderList(LitePal.findAll(DownloadInfo.class,true)));
songDowningRecycle.setItemAnimator(null); //解决进度刷新闪屏问题
mLinearLayoutManager = new LinearLayoutManager(getActivity()); mLinearLayoutManager = new LinearLayoutManager(getActivity());
mAdapter = new DownloadingAdapter(mDownloadInfoList); mAdapter = new DownloadingAdapter(mDownloadInfoList,mDownloadSongId);
songDowningRecycle.setLayoutManager(mLinearLayoutManager); songDowningRecycle.setLayoutManager(mLinearLayoutManager);
songDowningRecycle.setAdapter(mAdapter); songDowningRecycle.setAdapter(mAdapter);
//暂停
mAdapter.setOnItemClickListener(position -> {
DownloadInfo downloadInfo = mDownloadInfoList.get(position);
if(downloadInfo.getSongId().equals(mDownloadSongId.get(0))){
mDownloadBinder.pauseDownload();
}else {
mDownloadBinder.startDownload(mDownloadInfoList.get(position).getSong());
}
});
//取消下载
mAdapter.setOnDeleteClickListener(position -> {
SpeedDialog speedDialog = new SpeedDialog(getActivity(),SpeedDialog.SELECT_TYPE);
speedDialog.setTitle(getString(R.string.download_cancel))
.setMessage(getString(R.string.download_cancel_message))
.setSureText(getString(R.string.download_sure))
.setSureClickListener(dialog -> {
mDownloadBinder.cancelDownload(mDownloadInfoList.get(position).getUrl(),mDownloadInfoList.get(position).getSongId());
})
.show();
});
} }
@Subscribe(threadMode = ThreadMode.MAIN) @Subscribe(threadMode = ThreadMode.MAIN)
public void onDownloadingMessage(DownloadEvent event) { public void onDownloadingMessage(DownloadEvent event) {
int status = event.getDownloadStatus();
if (event.getDownloadStatus() == Constant.TYPE_DOWNLOADING) { if (status == Constant.TYPE_DOWNLOADING) {
mDownloadSongId.clear();
mDownloadSongId.add(event.getDownloadInfo().getSongId());
((LinkedList)mDownloadInfoList).poll();
((LinkedList)mDownloadInfoList).addFirst(event.getDownloadInfo());
mAdapter.notifyItemChanged(0);
}else if(status == Constant.TYPE_DOWNLOAD_SUCCESS){
mDownloadInfoList.clear(); mDownloadInfoList.clear();
mDownloadInfoList.add(event.getDownloadInfo()); mDownloadInfoList.addAll(orderList(LitePal.findAll(DownloadInfo.class,true)));
mAdapter.notifyDataSetChanged();
}else if(status == Constant.TYPE_DOWNLOAD_PAUSED){
mDownloadSongId.clear();
mDownloadSongId.add("");
mAdapter.notifyDataSetChanged(); mAdapter.notifyDataSetChanged();
}else if(status == Constant.TYPE_DOWNLOAD_CANCELED){
mDownloadInfoList.clear();
mDownloadInfoList.addAll(orderList(LitePal.findAll(DownloadInfo.class,true)));
mAdapter.notifyDataSetChanged();
}
}
private List<DownloadInfo> orderList(List<DownloadInfo> tempList){
List<DownloadInfo> downloadInfos=new ArrayList<>();
downloadInfos.clear();
for(int i=tempList.size()-1;i>=0;i--){
downloadInfos.add(tempList.get(i));
} }
return downloadInfos;
} }
@Override @Override

@ -23,6 +23,7 @@ import com.example.musicplayer.app.Constant;
import com.example.musicplayer.base.fragment.BaseMvpFragment; import com.example.musicplayer.base.fragment.BaseMvpFragment;
import com.example.musicplayer.contract.IAlbumSongContract; import com.example.musicplayer.contract.IAlbumSongContract;
import com.example.musicplayer.entiy.AlbumSong; import com.example.musicplayer.entiy.AlbumSong;
import com.example.musicplayer.entiy.DownloadSong;
import com.example.musicplayer.entiy.Song; import com.example.musicplayer.entiy.Song;
import com.example.musicplayer.event.SongAlbumEvent; import com.example.musicplayer.event.SongAlbumEvent;
import com.example.musicplayer.presenter.AlbumSongPresenter; import com.example.musicplayer.presenter.AlbumSongPresenter;
@ -197,6 +198,8 @@ public class AlbumSongFragment extends BaseMvpFragment<AlbumSongPresenter> imple
song.setImgUrl(Api.ALBUM_PIC+dataBean.getAlbummid()+ Api.JPG); song.setImgUrl(Api.ALBUM_PIC+dataBean.getAlbummid()+ Api.JPG);
song.setUrl(null); song.setUrl(null);
song.setMediaId(dataBean.getStrMediaMid()); song.setMediaId(dataBean.getStrMediaMid());
//判断是否已经下载
song.setDownload(LitePal.where("songId=?", dataBean.getSongmid()).find(DownloadSong.class).size() != 0);
FileUtil.saveSong(song); FileUtil.saveSong(song);
mPlayStatusBinder.play(Constant.LIST_TYPE_ONLINE); mPlayStatusBinder.play(Constant.LIST_TYPE_ONLINE);

@ -20,6 +20,7 @@ import com.example.musicplayer.app.Constant;
import com.example.musicplayer.base.fragment.BaseLoadingFragment; import com.example.musicplayer.base.fragment.BaseLoadingFragment;
import com.example.musicplayer.contract.ISearchContentContract; import com.example.musicplayer.contract.ISearchContentContract;
import com.example.musicplayer.entiy.Album; import com.example.musicplayer.entiy.Album;
import com.example.musicplayer.entiy.DownloadSong;
import com.example.musicplayer.entiy.SearchSong; import com.example.musicplayer.entiy.SearchSong;
import com.example.musicplayer.entiy.Song; import com.example.musicplayer.entiy.Song;
import com.example.musicplayer.event.OnlineSongChangeEvent; import com.example.musicplayer.event.OnlineSongChangeEvent;
@ -34,6 +35,7 @@ import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode; import org.greenrobot.eventbus.ThreadMode;
import org.litepal.LitePal;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -169,6 +171,7 @@ public class SearchContentFragment extends BaseLoadingFragment<SearchContentPres
song.setDuration(dataBean.getInterval()); song.setDuration(dataBean.getInterval());
song.setOnline(true); song.setOnline(true);
song.setMediaId(dataBean.getStrMediaMid()); song.setMediaId(dataBean.getStrMediaMid());
song.setDownload(LitePal.where("songId=?", dataBean.getSongmid()).find(DownloadSong.class).size() != 0);
FileUtil.saveSong(song); FileUtil.saveSong(song);
//网络获取歌曲地址 //网络获取歌曲地址
mPresenter.getSongUrl(dataBean.getSongmid()); mPresenter.getSongUrl(dataBean.getSongmid());

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.3 KiB

@ -18,7 +18,7 @@
app:layout_constraintLeft_toLeftOf="parent"/> app:layout_constraintLeft_toLeftOf="parent"/>
<TextView <TextView
android:id="@+id/currentSizeTv" android:id="@+id/sizeTv"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:textColor="@color/short_white" android:textColor="@color/short_white"
@ -27,23 +27,6 @@
app:layout_constraintLeft_toLeftOf="@+id/songTv" app:layout_constraintLeft_toLeftOf="@+id/songTv"
app:layout_constraintTop_toBottomOf="@+id/songTv"/> app:layout_constraintTop_toBottomOf="@+id/songTv"/>
<TextView
android:id="@+id/biasTv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/short_white"
android:text="@string/bias"
app:layout_constraintLeft_toRightOf="@+id/currentSizeTv"
app:layout_constraintTop_toTopOf="@+id/currentSizeTv"/>
<TextView
android:id="@+id/totalSizeTv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/short_white"
tools:text="5.7M"
app:layout_constraintLeft_toRightOf="@+id/biasTv"
app:layout_constraintTop_toTopOf="@+id/currentSizeTv"/>
@ -55,10 +38,10 @@
android:progressDrawable="@drawable/seekbar_bg" android:progressDrawable="@drawable/seekbar_bg"
android:maxHeight="5dp" android:maxHeight="5dp"
android:max="100" android:max="100"
app:layout_constraintLeft_toRightOf="@+id/totalSizeTv" app:layout_constraintLeft_toRightOf="@+id/sizeTv"
app:layout_constraintTop_toTopOf="@+id/totalSizeTv" app:layout_constraintTop_toTopOf="@+id/sizeTv"
app:layout_constraintRight_toLeftOf="@id/cancelIv" app:layout_constraintRight_toLeftOf="@id/cancelIv"
app:layout_constraintBottom_toBottomOf="@id/totalSizeTv" app:layout_constraintBottom_toBottomOf="@id/sizeTv"
/> />
<ImageView <ImageView
@ -76,5 +59,5 @@
android:layout_height="0.1dip" android:layout_height="0.1dip"
android:background="@color/gray" android:background="@color/gray"
android:layout_marginTop="@dimen/dp_10" android:layout_marginTop="@dimen/dp_10"
app:layout_constraintTop_toBottomOf="@id/totalSizeTv"/> app:layout_constraintTop_toBottomOf="@id/sizeTv"/>
</android.support.constraint.ConstraintLayout> </android.support.constraint.ConstraintLayout>

@ -51,6 +51,12 @@
<string name="play_mode_single">单曲循环</string> <string name="play_mode_single">单曲循环</string>
<string name="bias">&#160;/&#160;</string> <string name="bias">&#160;/&#160;</string>
//download
<string name="downloded">该歌曲已下载</string>
<string name="download_cancel">取消下载</string>
<string name="download_cancel_message">确定不再下载吗?</string>
<string name="download_sure">删除</string>
</resources> </resources>

Loading…
Cancel
Save