package com.weishitechsub.quanminchangKmianfei.utils;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
import androidx.annotation.Nullable;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.weishitechsub.quanminchangKmianfei.LCAppcation;
import com.weishitechsub.quanminchangKmianfei.bean.DownloadedSong;
import com.weishitechsub.quanminchangKmianfei.bean.MusicBean;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
public class MusicCache {
// === 持久化键名 ===
private static final String KEY_FAVORITE_LIST = "music_cache_favorite_list";
// === 内存缓存(提高性能)===
private static List<MusicBean.DataBean> mainMusicList;
private static List<MusicBean.DataBean> favoriteList; // 缓存收藏列表
private static MusicBean.DataBean currentPlayingSong;
private static int currentPosition = -1;
private static final String KEY_DOWNLOADED_SONGS = "downloaded_songs";//下载
// === 获取 SharedPreferences 的方法 ===
private static android.content.SharedPreferences getSP(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context);
}
// === 主音乐列表操作 ===
public static void setMainMusicList(List<MusicBean.DataBean> list) {
if (list != null) {
mainMusicList = new ArrayList<>(list);
} else {
mainMusicList = null;
}
}
@Nullable
public static List<MusicBean.DataBean> getMainMusicList() {
return mainMusicList;
}
@Nullable
public static MusicBean.DataBean getMusicAt(int position) {
if (mainMusicList == null || position < 0 || position >= mainMusicList.size()) {
return null;
}
return mainMusicList.get(position);
}
// === 当前播放歌曲操作 ===
public static void setCurrentPlayingSong(MusicBean.DataBean song, int position) {
currentPlayingSong = song;
currentPosition = position;
}
public static MusicBean.DataBean getCurrentPlayingSong() {
return currentPlayingSong;
}
public static int getCurrentPlayingPosition() {
return currentPosition;
}
public static void clearCurrentPlaying() {
currentPlayingSong = null;
currentPosition = -1;
}
// === 收藏列表操作(重点新增部分)===
/**
* 获取收藏列表(优先从内存读,内存为空则从 SP 加载)
*/
public static List<MusicBean.DataBean> getFavoriteList(Context context) {
if (context == null) return new ArrayList<>();
// 不再依赖内存缓存!每次从 SP 读取最真实的数据
return loadFavoriteListFromSP(context);
}
/**
* 添加歌曲到收藏列表
*/
public static void addFavorite(Context context, MusicBean.DataBean song) {
if (context == null || song == null) return;
List<MusicBean.DataBean> list = getFavoriteList(context);
if (!list.contains(song)) {
list.add(song);
saveFavoriteListToSP(context, list); // 立即写入 SP
}
// 更新内存缓存(可选)
favoriteList = new ArrayList<>(list);
}
/**
* 从收藏列表移除歌曲
*/
public static void removeFavorite(Context context, MusicBean.DataBean song) {
if (context == null || song == null) return;
List<MusicBean.DataBean> list = getFavoriteList(context);
if (list.remove(song)) {
saveFavoriteListToSP(context, list); // 立即写入 SP
}
// 更新内存缓存
favoriteList = new ArrayList<>(list);
}
/**
* 判断某首歌是否已收藏
*/
public static boolean isFavorite(MusicBean.DataBean song) {
if (song == null) return false;
Context context = LCAppcation.getInstance();
if (context == null) return false;
List<MusicBean.DataBean> list = getFavoriteList(context);
return list.contains(song);
}
/**
* 清空收藏列表
*/
public static void clearFavoriteList(Context context) {
saveFavoriteListToSP(context, new ArrayList<>());
favoriteList = new ArrayList<>();
}
// === 私有方法:持久化读写 ===
private static List<MusicBean.DataBean> loadFavoriteListFromSP(Context context) {
String json = getSP(context).getString(KEY_FAVORITE_LIST, "[]");
Log.d("MusicCache", "从 SP 读取收藏列表: " + json);
Type type = new TypeToken<List<MusicBean.DataBean>>(){}.getType();
Gson gson = new Gson();
try {
List<MusicBean.DataBean> list = gson.fromJson(json, type);
return list != null ? list : new ArrayList<>();
} catch (Exception e) {
e.printStackTrace();
return new ArrayList<>();
}
}
private static void saveFavoriteListToSP(Context context, List<MusicBean.DataBean> list) {
Gson gson = new Gson();
String json = gson.toJson(list);
Log.d("MusicCache", "正在保存收藏列表: " + json);
getSP(context).edit().putString(KEY_FAVORITE_LIST, json).apply();
}
public static void syncCollectionStatus(List<MusicBean.DataBean> songs, Context context) {
if (songs == null || context == null) return;
List<MusicBean.DataBean> favorites = getFavoriteList(context); // 从 SP 读出所有已收藏歌曲
for (MusicBean.DataBean song : songs) {
boolean collected = favorites.contains(song); // 判断是否在收藏列表里
song.setCollected(collected); // 更新 UI 状态
}
}
// 保存已下载歌曲列表
public static void saveDownloadedList(Context context, List<DownloadedSong> list) {
SharedPreferences sp = context.getSharedPreferences("app_data", Context.MODE_PRIVATE);
Gson gson = new Gson();
String json = gson.toJson(list);
sp.edit().putString(KEY_DOWNLOADED_SONGS, json).apply();
}
// 获取已下载歌曲列表
public static List<DownloadedSong> getDownloadedList(Context context) {
SharedPreferences sp = context.getSharedPreferences("app_data", Context.MODE_PRIVATE);
String json = sp.getString(KEY_DOWNLOADED_SONGS, null);
if (json == null) {
return new ArrayList<>();
}
Gson gson = new Gson();
Type type = new TypeToken<List<DownloadedSong>>(){}.getType();
return gson.fromJson(json, type);
}
// 清空下载记录(可选)
public static void clearDownloadList(Context context) {
SharedPreferences sp = context.getSharedPreferences("app_data", Context.MODE_PRIVATE);
sp.edit().remove(KEY_DOWNLOADED_SONGS).apply();
}
/**
* 兼容 DownloadedSong:将其转为 MusicBean.DataBean 进行收藏
* 不修改任何原有逻辑,仅做桥接
*/
public static void addFavorite(Context context, DownloadedSong song) {
if (context == null || song == null) return;
MusicBean.DataBean fakeBean = new MusicBean.DataBean();
fakeBean.setTitle(song.getTitle());
fakeBean.setSinger(song.getSinger());
fakeBean.setCover(song.getCover()); // 假设有 getCoverUrl()
fakeBean.setMusic(song.getMusic());
fakeBean.setLrc(song.getLrc());
addFavorite(context, fakeBean); // 复用原有逻辑
}
public static void removeFavorite(Context context, DownloadedSong song) {
if (context == null || song == null) return;
MusicBean.DataBean fakeBean = new MusicBean.DataBean();
fakeBean.setTitle(song.getTitle());
fakeBean.setSinger(song.getSinger());
removeFavorite(context, fakeBean);
}
public static boolean isFavorite(DownloadedSong song) {
if (song == null) return false;
MusicBean.DataBean fakeBean = new MusicBean.DataBean();
fakeBean.setTitle(song.getTitle());
fakeBean.setSinger(song.getSinger());
return isFavorite(fakeBean);
}
}
package com.weishitechsub.quanminchangKmianfei.fragment.specail;
import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.hfd.common.util.ToastUtil;
import com.weishitechsub.quanminchangKmianfei.R;
import com.weishitechsub.quanminchangKmianfei.adtakubase.activity.BaseBindActivity;
import com.weishitechsub.quanminchangKmianfei.bean.DownloadedSong;
import com.weishitechsub.quanminchangKmianfei.bean.MusicBean;
import com.weishitechsub.quanminchangKmianfei.bean.SongBean;
import com.weishitechsub.quanminchangKmianfei.databinding.ActivityLoveBinding;
import com.weishitechsub.quanminchangKmianfei.dialog.CommonDeleteDialog;
import com.weishitechsub.quanminchangKmianfei.dialog.CommonDialog;
import com.weishitechsub.quanminchangKmianfei.dialog.CustomBottomDialog;
import com.weishitechsub.quanminchangKmianfei.dialog.PermissionDialog;
import com.weishitechsub.quanminchangKmianfei.fragment.Adapter.DownloadedSongsAdapter;
import com.weishitechsub.quanminchangKmianfei.fragment.Adapter.SongAdapter;
import com.weishitechsub.quanminchangKmianfei.fragment.Adapter.WorksListAdapter;
import com.weishitechsub.quanminchangKmianfei.fragment.lilv.LiLvFragment;
import com.weishitechsub.quanminchangKmianfei.fragment.lilv.SingActivity;
import com.weishitechsub.quanminchangKmianfei.utils.LocalData;
import com.weishitechsub.quanminchangKmianfei.utils.MusicCache;
import com.weishitechsub.quanminchangKmianfei.utils.OnMultiClickListener;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import pub.devrel.easypermissions.EasyPermissions;
public class LoveActivity extends BaseBindActivity<ActivityLoveBinding> implements SongAdapter.OnIvClickListener, EasyPermissions.PermissionCallbacks,DownloadedSongsAdapter.OnDownloadedIvClickListener {
private int type;
private String title;
private TextView tvTitle;
private SongAdapter songAdapter;
WorksListAdapter singAdapter;
WorksListAdapter oratoriAdapter;
private int pos;
private AlertDialog progressDialog;
private static final String[] PERMS_CAMERA = new String[] {Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE}; // 需要请求的权限数组
private static final int RC_CAMERA_PERM = 123; // 请求码,唯一标识
private List<DownloadedSong> dataList = new ArrayList<>();
private DownloadedSongsAdapter downloadedSongsAdapter;
@Override
protected void init() {
tvTitle = mBinding.tvTitle;
Intent intent = getIntent();
if (intent != null) {
type = intent.getIntExtra("type", 0);
title = intent.getStringExtra("title");
}
setOnData();
setOnClick();
setupRecyclerView(); // 初始化列表
}
private void setupRecyclerView() {
mBinding.rv.setLayoutManager(new LinearLayoutManager(this));
if (type == 0) {
// 显示收藏列表
List<MusicBean.DataBean> favorites = MusicCache.getFavoriteList(this);
songAdapter = new SongAdapter(favorites);
songAdapter.setOnIvClickListener(this);
mBinding.rv.setAdapter(songAdapter);
} else if (type == 1){
//显示下载本地歌曲
mBinding.rv.setLayoutManager(new LinearLayoutManager(this));
downloadedSongsAdapter = new DownloadedSongsAdapter(dataList);
downloadedSongsAdapter.setDownloadedOnIvClickListener(this);
mBinding.rv.setAdapter(downloadedSongsAdapter);
loadDownloadedSongs();
} else if (type == 2){
// 显示K歌记录列表
mBinding.rv.setLayoutManager(new LinearLayoutManager(this));
singAdapter = new WorksListAdapter(new ArrayList<>()); // 你的适配器类
mBinding.rv.setAdapter(singAdapter);
List<SongBean> songBeanList = LocalData.getInstance().getSongList();
if (null == songBeanList) {
songBeanList = new ArrayList<>();
}
if (songBeanList.size() > 0) {
singAdapter.getData().clear();
singAdapter.setNewData(songBeanList);
singAdapter.notifyDataSetChanged();
} else {
singAdapter.setNewData(null);
// singAdapter.setEmptyView(R.layout.empty_work_view);
}
singAdapter.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
//处理多选逻辑
Bundle bundle = new Bundle();
bundle.putString("filePath", singAdapter.getData().get(position).getSongFilePath());
bundle.putString("songName", singAdapter.getData().get(position).getSongName());
toClass(PlayActivity.class, bundle);
}
});
}else {
mBinding.rv.setLayoutManager(new LinearLayoutManager(LoveActivity.this));
if (null == oratoriAdapter) {
oratoriAdapter = new WorksListAdapter(new ArrayList<>()); // 你的适配器类
}
mBinding.rv.setAdapter(oratoriAdapter);
List<SongBean> songBeanList = LocalData.getInstance().getOratoriList();
if (null == songBeanList) {
songBeanList = new ArrayList<>();
}
if (songBeanList.size() > 0) {
oratoriAdapter.getData().clear();
oratoriAdapter.setNewData(songBeanList);
oratoriAdapter.notifyDataSetChanged();
} else {
oratoriAdapter.setNewData(null);
// oratoriAdapter.setEmptyView(R.layout.empty_work_view);
}
oratoriAdapter.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
Bundle bundle = new Bundle();
bundle.putString("filePath", oratoriAdapter.getData().get(position).getSongFilePath());
bundle.putString("songName", oratoriAdapter.getData().get(position).getSongName());
toClass(PlayActivity.class, bundle);
}
});
}
}
private void loadDownloadedSongs() {
dataList.clear();
List<DownloadedSong> list = MusicCache.getDownloadedList(this);
dataList.addAll(list);
downloadedSongsAdapter.notifyDataSetChanged();
}
private void setOnClick() {
mBinding.iv.setOnClickListener(new OnMultiClickListener() {
@Override
public void onMultiClick(View v) {
finish();
}
});
mBinding.tvSc.setOnClickListener(new OnMultiClickListener() {
@Override
public void onMultiClick(View v) {
CommonDeleteDialog commonDialog = new CommonDeleteDialog(LoveActivity.this,"是否确认删除");
commonDialog.show();
commonDialog.setOnDialogClickListener(new CommonDeleteDialog.OnDialogClickListener() {
@Override
public void onSureClickListener() {
}
@Override
public void onQuitClickListener() {
commonDialog.dismiss();
}
});
}
});
}
public void setOnData(){
if (type == 0) {
tvTitle.setText(title);
}else if (type == 1){
tvTitle.setText(title);
}else if (type == 2){
tvTitle.setText(title);
}else {
tvTitle.setText(title);
}
}
@Override
public void onIvClick(int position, ImageView iv_gd) {
iv_gd.setOnClickListener(new OnMultiClickListener() {
@Override
public void onMultiClick(View v) {
CustomBottomDialog dialog = new CustomBottomDialog(LoveActivity.this);
MusicBean.DataBean song = songAdapter.getItem(position);
dialog.setTitle(song.getTitle(),song.getSinger(),song.getCover(),song.isCollected());
//去演唱点击事件
dialog.setOnYcClickListener(new CustomBottomDialog.OnYcClickListener() {
@Override
public void onYcClick() {
Intent intent = new Intent(LoveActivity.this, SingActivity.class);
intent.putExtra("song_data", song); // 直接传递 Serializable 对象
startActivity(intent);
}
});
//去k歌点击事件
dialog.setOnKgClickListener(new CustomBottomDialog.OnKgClickListener() {
@Override
public void onKgClick() {
Intent intent = new Intent(LoveActivity.this, SingActivity.class);
intent.putExtra("song_data", song);
startActivity(intent);
}
});
//下载歌曲点击事件
dialog.setOnDownloadClickListener(new CustomBottomDialog.OnDownloadClickListener() {
@Override
public void onDownloadClick() {
pos = position;
getSavePermissions(position);
}
});
//收藏点击事件
dialog.setOnLikeClickListener(new CustomBottomDialog.OnLikeClickListener() {
@Override
public void onLikeClick() {
// 切换收藏状态
boolean nowCollected = !song.isCollected();
song.setCollected(nowCollected);
dialog.updateLikeStatus(nowCollected); // 实时更新界面
if (nowCollected) {
MusicCache.addFavorite(LoveActivity.this, song);
} else {
MusicCache.removeFavorite(LoveActivity.this, song);
}
ToastUtil.showShortToast(nowCollected ? "已收藏" : "已取消收藏");
}
});
dialog.show();
}
});
}
@Override
public void onDownloadedIvClick(int position, ImageView iv_gd) {
iv_gd.setOnClickListener(new OnMultiClickListener() {
@Override
public void onMultiClick(View v) {
CustomBottomDialog dialog = new CustomBottomDialog(LoveActivity.this);
DownloadedSong item = downloadedSongsAdapter.getItem(position);
dialog.setTitle(item.getTitle(),item.getSinger(),item.getCover(),item.isCollected());
//去演唱点击事件
dialog.setOnYcClickListener(new CustomBottomDialog.OnYcClickListener() {
@Override
public void onYcClick() {
Intent intent = new Intent(LoveActivity.this, SingActivity.class);
intent.putExtra("song_data", item); // 直接传递 Serializable 对象
startActivity(intent);
}
});
//去k歌点击事件
dialog.setOnKgClickListener(new CustomBottomDialog.OnKgClickListener() {
@Override
public void onKgClick() {
Intent intent = new Intent(LoveActivity.this, SingActivity.class);
intent.putExtra("song_data", item);
startActivity(intent);
}
});
//下载歌曲点击事件
dialog.setOnDownloadClickListener(new CustomBottomDialog.OnDownloadClickListener() {
@Override
public void onDownloadClick() {
pos = position;
getSavePermissions(position);
}
});
//收藏点击事件
dialog.setOnLikeClickListener(new CustomBottomDialog.OnLikeClickListener() {
@Override
public void onLikeClick() {
// 切换收藏状态
boolean nowCollected = !item.isCollected();
item.setCollected(nowCollected);
dialog.updateLikeStatus(nowCollected); // 实时更新界面
if (nowCollected) {
MusicCache.addFavorite(LoveActivity.this, item);
} else {
MusicCache.removeFavorite(LoveActivity.this, item);
}
ToastUtil.showShortToast(nowCollected ? "已收藏" : "已取消收藏");
}
});
dialog.show();
}
});
}
private void getSavePermissions(int position) {
// 检查并请求权限
if (!EasyPermissions.hasPermissions(LoveActivity.this, PERMS_CAMERA)) {
new PermissionDialog(LoveActivity.this,"权限说明:由于下载歌曲,需要相应的存储权限。拒绝将无法使用此功能").show();
EasyPermissions.requestPermissions(LoveActivity.this, "需要相应的存储权限", RC_CAMERA_PERM, PERMS_CAMERA);
} else {
saveSongAtPosition(position); //开始下载指定位置的歌曲
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}
@Override
public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
if(requestCode == RC_CAMERA_PERM){
saveSongAtPosition(pos);
}
}
@Override
public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
}
private void saveSongAtPosition(int position) {
MusicBean.DataBean song = songAdapter.getItem(position);
if (song == null) {
ToastUtil.showShortToast("无效的歌曲信息");
return;
}
if (song.getMusic() == null || song.getMusic().isEmpty()) {
ToastUtil.showShortToast("歌曲地址无效");
return;
}
showProgressDialog(LoveActivity.this);
new SaveTask(song).execute(); // 启动异步任务下载
}
private void showProgressDialog(Context context) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("正在保存...");
builder.setCancelable(false);
progressDialog = builder.create();
progressDialog.show();
}
private class SaveTask extends AsyncTask<Void, Void, Boolean> {
private final MusicBean.DataBean song;
private String targetPath;
private Exception exception;
SaveTask(MusicBean.DataBean song) {
this.song = song;
}
@Override
protected Boolean doInBackground(Void... voids) {
try {
String urlStr = song.getMusic();
String fileName = song.getTitle();
if (fileName == null) fileName = "music_" + System.currentTimeMillis();
File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
if (!dir.exists()) dir.mkdirs();
targetPath = new File(dir, fileName + ".mp3").getAbsolutePath();
InputStream inputStream = new java.net.URL(urlStr).openStream();
FileOutputStream outStream = new FileOutputStream(targetPath);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
outStream.flush();
outStream.close();
inputStream.close();
// 通知媒体库刷新
Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
scanIntent.setData(Uri.fromFile(new File(targetPath)));
sendBroadcast(scanIntent);
return true;
} catch (Exception e) {
e.printStackTrace();
exception = e;
return false;
}
}
@Override
protected void onPostExecute(Boolean success) {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
if (success) {
Toast.makeText(LoveActivity.this, "音乐已保存至: " + targetPath, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(LoveActivity.this, "保存失败: " + (exception != null ? exception.getMessage() : "未知错误"), Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onResume() {
super.onResume();
// 每次进入都刷新(以防新增了)
if (type == 1) {
loadDownloadedSongs();
}
}
}点击mBinding.tvSc清空我喜欢的、我下载的数据