实现代码如下:
PlayService如下:
package com.iwanghang.drmplayer; import android.app.Service; import android.content.Intent; import android.media.MediaPlayer; import android.media.MediaPlayer.OnCompletionListener; import android.media.MediaPlayer.OnErrorListener; import android.net.Uri; import android.os.Binder; import android.os.IBinder; import com.iwanghang.drmplayer.utils.MediaUtils; import com.iwanghang.drmplayer.vo.Mp3Info; import java.io.IOException; import java.util.ArrayList; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * 音乐播放的服务组件 * 实现功能: * 播放 * 暂停 * 下一首 * 上一首 * 获取当前歌曲的播放进度 * <p/> * 需要在AndroidManifest.xml添加以下代码: * <service * android:name=".PlayService" * android:enabled="true" * android:exported="true"> * </service> * <p/> * 实现功能(播放模式play_mode): * 顺序播放 * 随机播放 * 单曲循环 */ public class PlayService extends Service implements OnCompletionListener, OnErrorListener { private MediaPlayer mPlayer; private int currentPosition;//当前正在播放的歌曲的位置 ArrayList<Mp3Info> mp3Infos; private MusicUpdatrListener musicUpdatrListener; //创建一个单实力的线程,用于更新音乐信息 private ExecutorService es = Executors.newSingleThreadExecutor(); //播放模式 public static final int ORDER_PLAY = 1;//顺序播放 public static final int RANDOM_PLAY = 2;//随机播放 public static final int SINGLE_PLAY = 3;//单曲循环 private int play_mode = ORDER_PLAY;//播放模式,默认为顺序播放 /** * @param play_mode ORDER_PLAY = 1;//顺序播放 * RANDOM_PLAY = 2;//随机播放 * SINGLE_PLAY = 3;//单曲循环 */ //set方法 public void setPlay_mode(int play_mode) { this.play_mode = play_mode; } //get方法 public int getPlay_mode() { return play_mode; } private boolean isPause = false;//歌曲播放中的暂停状态 public boolean isPause() { return isPause; } //切换播放列表,默认MY_MUSIC_LIST public static final int MY_MUSIC_LIST = 1; public static final int LOVE_MUSIC_LIST = 2; private int changePlayList = MY_MUSIC_LIST; public int getChangePlayList() {//get方法 return changePlayList; } public void setChangePlayList(int changePlayList) {//set方法 this.changePlayList = changePlayList; } public PlayService() { } //ArrayList<Mp3Info> mp3Infos; set方法 public void setMp3Infos(ArrayList<Mp3Info> mp3Infos) { this.mp3Infos = mp3Infos; } public int getCurrentPosition() { return currentPosition; } private Random random = new Random();//创建随机对象 //MediaPlayer.Completion 播放完成 实现播放下一首功能 //播放完成以后,判断播放模式(曲目循环方式) //为了实现循环后,可以显示音乐信息,需要在PlayAcivity的change里添加对应代码 @Override public void onCompletion(MediaPlayer mp) { switch (play_mode) { case ORDER_PLAY://顺序播放 next();//下一首 break; case RANDOM_PLAY://随机播放 //currentPosition = random.nextInt(mp3Infos.size());//随机下标为mp3Infos.size() //play(currentPosition); play(random.nextInt(mp3Infos.size())); break; case SINGLE_PLAY://单曲循环 play(currentPosition); break; default: break; } } //MediaPlayer.Error 播放错误 处理实现播放下一首功能出现的错误 @Override public boolean onError(MediaPlayer mp, int what, int extra) { mp.reset();//重启 return false; } //内部类PlayBinder实现Binder,得到当前PlayService对象 class PlayBinder extends Binder { public PlayService getPlayService() { System.out.println("PlayService #1 " + PlayService.this); return PlayService.this; } } @Override public IBinder onBind(Intent intent) { return new PlayBinder();//通过PlayBinder拿到PlayService,给Activity调用 } @Override public void onCreate() { super.onCreate(); //恢复状态值 DRMPlayerApp app = (DRMPlayerApp) getApplication(); currentPosition = app.sp.getInt("currentPosition", 0); play_mode = app.sp.getInt("play_mode", PlayService.ORDER_PLAY); //创建DRMPlayerApp继承Application,同时需要在把AndroidManiFest中的public换成DRMPlayerApp //在DRMPlayerApp的onCreate中 实例化 SharedPreferences //在MainActivity的onDestroy中 保存状态值 //在PlayService的onCreate中 恢复状态值 mPlayer = new MediaPlayer(); mPlayer.setOnCompletionListener(this);//注册播放完成事件 mPlayer.setOnErrorListener(this);//注册播放错误事件 mp3Infos = MediaUtils.getMp3Infos(this);//获取Mp3列表 es.execute(updateSteatusRunnable);//更新进度值 } @Override public void onDestroy() { super.onDestroy(); //回收线程 if (es != null && !es.isShutdown()) {//当进度值等于空,并且,进度值没有关闭 es.shutdown(); es = null; } } //利用Runnable来实现多线程 /** * Runnable * Java中实现多线程有两种途径:继承Thread类或者实现Runnable接口. * Runnable接口非常简单,就定义了一个方法run(),继承Runnable并实现这个 * 方法就可以实现多线程了,但是这个run()方法不能自己调用,必须由系统来调用,否则就和别的方法没有什么区别了. * 好处:数据共享 */ Runnable updateSteatusRunnable = new Runnable() {//更新状态 @Override public void run() { //不断更新进度值 while (true) { //音乐更新监听不为空,并且,媒体播放不为空,并且媒体播放为播放状态 if (musicUpdatrListener != null && mPlayer != null && mPlayer.isPlaying()) { musicUpdatrListener.onPublish(getCurrentProgress());//获取当前的进度值 } try { Thread.sleep(500);//500毫秒更新一次 } catch (InterruptedException e) { e.printStackTrace(); } } } }; //播放 public void play(int position) { Mp3Info mp3Info; if (position >= 0 && position < mp3Infos.size()) { } else { position = 0; } mp3Info = mp3Infos.get(position);//获取mp3Info对象 //进行播放,播放前判断 try { mPlayer.reset();//重启 mPlayer.setDataSource(this, Uri.parse(mp3Info.getUrl()));//资源解析,Mp3地址 mPlayer.prepare();//准备 mPlayer.start();//开始(播放) currentPosition = position;//保存当前位置到currentPosition,比如第一首,currentPosition = 1 } catch (IOException e) { e.printStackTrace(); } if (musicUpdatrListener != null) { musicUpdatrListener.onChange(currentPosition);//更新当前位置 } } //暂停 public void pause() { if (mPlayer.isPlaying()) { mPlayer.pause(); isPause = true; } } //下一首 public void next() { if (currentPosition >= mp3Infos.size() - 1) {//如果超出最大值,(因为第一首是0),说明已经是最后一首 currentPosition = 0;//回到第一首 } else { currentPosition++;//下一首 } play(currentPosition); } //上一首 previous public void prev() { if (currentPosition - 1 < 0) {//如果上一首小于0,说明已经是第一首 currentPosition = mp3Infos.size() - 1;//回到最后一首 } else { currentPosition--;//上一首 } play(currentPosition); } //默认开始播放的方法 public void start() { if (mPlayer != null && !mPlayer.isPlaying()) {//判断当前歌曲不等于空,并且没有在播放的状态 mPlayer.start(); } } //获取当前是否为播放状态,提供给MyMusicListFragment的播放暂停按钮点击事件判断状态时调用 public boolean isPlaying() { if (mPlayer != null) { return mPlayer.isPlaying(); } return false; } //获取当前的进度值 public int getCurrentProgress() { if (mPlayer != null && mPlayer.isPlaying()) {//mPlayer不为空,并且,为播放状态 return mPlayer.getCurrentPosition(); } return 0; } //getDuration 获取文件的持续时间 public int getDuration() { return mPlayer.getDuration(); } //seekTo 寻找指定的时间位置 (跳到某个时间点进行播放) public void seekTo(int msec) { mPlayer.seekTo(msec); } //更新状态的接口(PlayService的内部接口),并在BaseActivity中实现 public interface MusicUpdatrListener {//音乐更新监听器 public void onPublish(int progress);//发表进度事件(更新进度条) public void onChange(int position); //更新歌曲位置.按钮的状态等信息 //声明MusicUpdatrListener后,添加set方法 } //set方法 public void setMusicUpdatrListener(MusicUpdatrListener musicUpdatrListener) { this.musicUpdatrListener = musicUpdatrListener; } }
package com.iwanghang.drmplayer; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.AdapterView.OnItemClickListener; import com.iwanghang.drmplayer.adapter.MyMusicListAdapter; import com.iwanghang.drmplayer.vo.Mp3Info; import com.lidroid.xutils.exception.DbException; import java.util.ArrayList; /** * Created by iwanghang on 16/4/27. * 我的收藏音乐列表界面 */ public class MyLoveMusicActivity extends BaseActivity implements OnItemClickListener { private ListView listView_love; private DRMPlayerApp app; private ArrayList<Mp3Info> loveMp3Infos; private MyMusicListAdapter adapter; private boolean isChange = false;//表示当前播放列表是否为收藏列表 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); app = (DRMPlayerApp) getApplication(); setContentView(R.layout.avtivity_my_love_music_list);//绑定布局 listView_love = (ListView) findViewById(R.id.listView_love);//实例化布局 listView_love.setOnItemClickListener(this); initData();//初始化数据 //listView_love.setAdapter(); } private void initData() {//初始化数据 try { loveMp3Infos = (ArrayList<Mp3Info>) app.dbUtils.findAll(Mp3Info.class);//查找所有已收藏音乐 adapter = new MyMusicListAdapter(this,loveMp3Infos); listView_love.setAdapter(adapter); } catch (DbException e) { e.printStackTrace(); } } //把播放服务的绑定和解绑放在onResume,onPause里,好处是,每次回到当前Activity就获取一次播放状态 @Override protected void onResume() { super.onResume(); bindPlayService();//绑定服务 } @Override protected void onPause() { super.onPause(); unbindPlayService();//解绑服务 } @Override protected void onDestroy() { super.onDestroy(); unbindPlayService();//解绑服务 } @Override public void publish(int progress) { } @Override public void change(int progress) { } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //如果当前播放列表不是收藏列表 if (playService.getChangePlayList() != playService.LOVE_MUSIC_LIST){ playService.setMp3Infos(loveMp3Infos);//播放列表切换为收藏列表 playService.setChangePlayList(playService.LOVE_MUSIC_LIST); } playService.play(position); } }
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:text="我收藏的音乐" android:textColor="@android:color/holo_blue_light" android:layout_margin="5dp" android:textSize="20sp" android:id="@+id/textView2_love" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" /> <ListView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/listView_love" android:layout_below="@+id/textView2_love" android:layout_centerHorizontal="true" /> </RelativeLayout>
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <!--<item--> <!--android:id="@+id/ilove"--> <!--android:icon="@mipmap/app_love_list"--> <!--android:showAsAction="ifRoom"--> <!--android:title="@string/action_contact"/>--> <item android:id="@+id/ilove" android:title="@string/action_contact" android:showAsAction="ifRoom"/> <item android:id="@+id/near_play" android:title="@string/action_contact_2" android:showAsAction="ifRoom"/> </menu>
package com.iwanghang.drmplayer; import android.graphics.Bitmap; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.view.ViewPager; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; import android.widget.Toast; import com.iwanghang.drmplayer.utils.ImageUtils; import com.iwanghang.drmplayer.utils.MediaUtils; import com.iwanghang.drmplayer.vo.Mp3Info; import com.lidroid.xutils.db.sqlite.Selector; import com.lidroid.xutils.exception.DbException; import java.util.ArrayList; import static com.iwanghang.drmplayer.PlayService.ORDER_PLAY; import static com.iwanghang.drmplayer.PlayService.RANDOM_PLAY; import static com.iwanghang.drmplayer.PlayService.SINGLE_PLAY; /** *PlayActivity 点击MyMusicListFragment(本地音乐)底部UI中的专辑封面图片打开的Activity */ public class PlayActivity extends BaseActivity implements OnClickListener,OnSeekBarChangeListener{ private TextView textView1_title;//歌名 private ImageView imageView1_ablum;//专辑封面图片 private SeekBar seekBar1;//进度条 private TextView textView1_start_time,textView1_end_time;//开始时间,结束时间 private ImageView imageView1_play_mode;//菜单 private ImageView imageView3_previous,imageView2_play_pause,imageView1_next;//上一首,播放暂停,下一首 private ImageView imageView1_ablum_reflection;//专辑封面图片倒影 private ImageView imageView1_favorite;//收藏按钮 //private ArrayList<Mp3Info> mp3Infos; //private int position;//当前播放的位置 private boolean isPause = false;//当前播放的是否为暂停状态 private static final int UPDATE_TIME = 0x1;//更新播放事件的标记 DRMPlayerApp app;//取出全局对象 方便调用 // private ViewPager viewPager; // private MyPagerAdapter adapter; // private MyMusicListFragment myMusicListFragment; // private NetMusicListFragment netMusicListFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_music_play); //取出全局对象 方便调用 app = (DRMPlayerApp) getApplication(); //初始化界面信息 textView1_title = (TextView) findViewById(R.id.textView1_title);//歌名 imageView1_ablum = (ImageView) findViewById(R.id.imageView1_ablum);//专辑封面图片 seekBar1 = (SeekBar) findViewById(R.id.seekBar1);//进度条 textView1_start_time = (TextView) findViewById(R.id.textView1_start_time);//开始时间 textView1_end_time = (TextView) findViewById(R.id.textView1_end_time);//结束时间 imageView1_play_mode = (ImageView) findViewById(R.id.imageView1_play_mode);//菜单 imageView3_previous = (ImageView) findViewById(R.id.imageView3_previous);//上一首 imageView2_play_pause = (ImageView) findViewById(R.id.imageView2_play_pause);//播放暂停 imageView1_next = (ImageView) findViewById(R.id.imageView1_next);//下一首 imageView1_ablum_reflection = (ImageView) findViewById(R.id.imageView1_ablum_reflection);//专辑封面图片倒影 imageView1_favorite = (ImageView) findViewById(R.id.imageView1_favorite);//收藏按钮 //注册按钮点击监听事件 imageView1_play_mode.setOnClickListener(this); imageView2_play_pause.setOnClickListener(this); imageView3_previous.setOnClickListener(this); imageView1_next.setOnClickListener(this); seekBar1.setOnSeekBarChangeListener(this); imageView1_favorite.setOnClickListener(this); //mp3Infos = MediaUtils.getMp3Infos(this); //bindPlayService();//绑定服务,异步过程,绑定后需要取得相应的值,来更新界面 myHandler = new MyHandler(this); //以下直接调用change()是不行的,因为异步问题,会发生NullPointerException空指针异常 //从MyMusicListFragment的专辑封面图片点击时间传过来的position(当前播放的位置) //position = getIntent().getIntExtra("position",0); //change(position); //通过在BaseActivity中绑定Service,添加如下代码实现change() //musicUpdatrListener.onChange(playService.getCurrentProgeress()); //从MyMusicListFragment的专辑封面图片点击时间传过来的isPause(当前播放的是否为暂停状态) //isPause = getIntent().getBooleanExtra("isPause",false); } // private void initViewPager(){//专辑封面图片Pager与歌词Pager // View album_image_layout = getLayoutInflater().inflate(R.layout.album_image_layout,null); // //初始化界面信息 // textView1_title = (TextView) findViewById(R.id.textView1_title);//歌名 // imageView1_ablum = (ImageView) findViewById(R.id.imageView1_ablum);//专辑封面图片 // views.add(album_image_layout);//添加专辑封面图片Pager // views.add(getLayoutInflater().inflate(R.layout.lrc_layout));//添加歌词Pager // viewPager.setAdapter(new MyPagerAdapter()); // } //把播放服务的绑定和解绑放在onResume,onPause里,好处是,每次回到当前Activity就获取一次播放状态 @Override protected void onResume() { super.onResume(); bindPlayService();//绑定服务 } @Override protected void onPause() { super.onPause(); unbindPlayService();//解绑服务 } @Override protected void onDestroy() { super.onDestroy(); unbindPlayService();//解绑服务 } //Handler用于更新已经播放时间 private static MyHandler myHandler; //进度条改变 (fromUser 是否来自用户的改变 , 而不是程序自身控制的改变) @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser){ //playService.pause();//暂停 playService.seekTo(progress);//寻找指定的时间位置 (跳到某个时间点进行播放) //playService.start();//播放 } } //进度条开始触摸 @Override public void onStartTrackingTouch(SeekBar seekBar) { } //进度条停止触摸 @Override public void onStopTrackingTouch(SeekBar seekBar) { } static class MyHandler extends Handler{ private PlayActivity playActivity; public MyHandler(PlayActivity playActivity){ this.playActivity = playActivity; } @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (playActivity!=null){ switch (msg.what){ case UPDATE_TIME://更新时间(已经播放时间) playActivity.textView1_start_time.setText(MediaUtils.formatTime(msg.arg1)); break; } } } } @Override public void publish(int progress) { //以下是是直接调用线程,但是不能这样做,会报错,线程异常 //textView1_start_time.setText(MediaUtils.formatTime(progress)); //所以,我们需要使用Handler Message msg = myHandler.obtainMessage(UPDATE_TIME);//用于更新已经播放时间 msg.arg1 = progress;//用于更新已经播放时间 myHandler.sendMessage(msg);//用于更新已经播放时间 seekBar1.setProgress(progress); } @Override public void change(int position) {//初始化,独立播放界面的歌曲切换后的初始化界面上的歌曲信息 //if (this.playService.isPlaying()) {//获取是否为播放状态 System.out.println("PlayActivity #100 position = " + position); Mp3Info mp3Info = playService.mp3Infos.get(position); textView1_title.setText(mp3Info.getTitle());//设置歌名 //获取专辑封面图片 Bitmap albumBitmap = MediaUtils.getArtwork(this, mp3Info.getId(), mp3Info.getAlbumId(), true, false); //改变播放界面专辑封面图片 imageView1_ablum.setImageBitmap(albumBitmap); textView1_end_time.setText(MediaUtils.formatTime(mp3Info.getDuration()));//设置结束时间 imageView2_play_pause.setImageResource(R.mipmap.app_music_pause);//设置暂停图片 seekBar1.setProgress(0);//设置当前进度为0 seekBar1.setMax((int)mp3Info.getDuration());//设置进度条最大值为MP3总时间 if (playService.isPlaying()){ imageView2_play_pause.setImageResource(R.mipmap.app_music_pause); }else { imageView2_play_pause.setImageResource(R.mipmap.app_music_play); } if(imageView1_ablum != null) { imageView1_ablum_reflection.setImageBitmap(ImageUtils.createReflectionBitmapForSingle(albumBitmap));//显示倒影 } switch (playService.getPlay_mode()){ case ORDER_PLAY://顺序播放 imageView1_play_mode.setImageResource(R.mipmap.app_mode_order); //imageView2_play_pause.setTag(ORDER_PLAY); break; case PlayService.RANDOM_PLAY://随机播放 imageView1_play_mode.setImageResource(R.mipmap.app_mode_random); //imageView2_play_pause.setTag(RANDOM_PLAY); break; case PlayService.SINGLE_PLAY://单曲循环 imageView1_play_mode.setImageResource(R.mipmap.app_mode_single); //imageView2_play_pause.setTag(SINGLE_PLAY); break; default: break; } //初始化收藏状态 try { Mp3Info loveMp3Info = app.dbUtils.findFirst(Selector.from(Mp3Info.class) .where("mp3InfoId","=",mp3Info.getMp3InfoId()));//查出歌曲,SQL语句 if (loveMp3Info!=null){ imageView1_favorite.setImageResource(R.mipmap.app_love_selected); }else { imageView1_favorite.setImageResource(R.mipmap.app_love_unselected); } } catch (DbException e) { e.printStackTrace(); } } //点击事件 @Override public void onClick(View v) { switch (v.getId()){ case R.id.imageView2_play_pause: {//播放暂停按钮 if (playService.isPlaying()) {//如果是播放状态 imageView2_play_pause.setImageResource(R.mipmap.app_music_play);//设置播放图片 playService.pause(); } else { if (playService.isPause()) { imageView2_play_pause.setImageResource(R.mipmap.app_music_pause);//设置暂停图片 playService.start();//播放事件 } else { //只有打开APP没有点击任何歌曲,同时,直接点击暂停播放按钮时.才会调用 //playService.play(0); //只有打开APP没有点击任何歌曲,同时,直接点击暂停播放按钮时.才会调用 //默认播放的是,在PlayService的onCreate中 恢复状态值 playService.play(playService.getCurrentPosition()); } } break; } case R.id.imageView1_next:{//下一首按钮 playService.next();//下一首 break; } case R.id.imageView3_previous:{//上一首按钮 playService.prev();//上一首 break; } case R.id.imageView1_play_mode:{//循环模式按钮 //int mode = (int) imageView1_play_mode.getTag(); /** * 以下Tosat内容,在strings.xml里,添加对应代码 *<string name="order_play">顺序播放</string> *<string name="random_play">随机播放</string> *<string name="single_play">单曲循环</string> */ switch (playService.getPlay_mode()){ case ORDER_PLAY: imageView1_play_mode.setImageResource(R.mipmap.app_mode_random); //imageView1_play_mode.setTag(RANDOM_PLAY); playService.setPlay_mode(RANDOM_PLAY); //Toast.makeText(getApplicationContext(),"随机播放",Toast.LENGTH_SHORT).show();//这句也可以 //Toast.makeText(PlayActivity.this, "随机播放", Toast.LENGTH_SHORT).show();//这句也可以 Toast.makeText(PlayActivity.this, getString(R.string.random_play), Toast.LENGTH_SHORT).show(); break; case RANDOM_PLAY: imageView1_play_mode.setImageResource(R.mipmap.app_mode_single); //imageView1_play_mode.setTag(SINGLE_PLAY); playService.setPlay_mode(SINGLE_PLAY); //Toast.makeText(getApplicationContext(),"单曲循环",Toast.LENGTH_SHORT).show();//这句也可以 //Toast.makeText(PlayActivity.this, "单曲循环", Toast.LENGTH_SHORT).show();//这句也可以 Toast.makeText(PlayActivity.this, getString(R.string.single_play), Toast.LENGTH_SHORT).show(); break; case SINGLE_PLAY: imageView1_play_mode.setImageResource(R.mipmap.app_mode_order); //imageView1_play_mode.setTag(ORDER_PLAY); playService.setPlay_mode(ORDER_PLAY); //Toast.makeText(getApplicationContext(),"顺序播放",Toast.LENGTH_SHORT).show();//这句也可以 //Toast.makeText(PlayActivity.this, "顺序播放", Toast.LENGTH_SHORT).show();//这句也可以 Toast.makeText(PlayActivity.this, getString(R.string.order_play), Toast.LENGTH_SHORT).show(); break; } break; } case R.id.imageView1_favorite:{//收藏按钮 //在vo.Mp3Info里 private long mp3InfoId;//在收藏音乐时用于保存原始ID Mp3Info mp3Info = playService.mp3Infos.get(playService.getCurrentPosition());//查出歌曲 try { //Mp3Info loveMp3Info = app.dbUtils.findById(Mp3Info.class,mp3Info.getId());//查出歌曲,错误的 Mp3Info loveMp3Info = app.dbUtils.findFirst(Selector.from(Mp3Info.class) .where("mp3InfoId","=",mp3Info.getMp3InfoId()));//查出歌曲,SQL语句 if (loveMp3Info==null){//不在音乐收藏数据库中 mp3Info.setMp3InfoId(mp3Info.getId()); //在音乐收藏数据库 保存音乐 app.dbUtils.save(mp3Info); imageView1_favorite.setImageResource(R.mipmap.app_love_selected); Toast.makeText(PlayActivity.this, getString(R.string.love_selected), Toast.LENGTH_SHORT).show(); }else {//在音乐收藏数据库中 //在音乐收藏数据库 删除音乐 app.dbUtils.deleteById(Mp3Info.class,loveMp3Info.getId()); imageView1_favorite.setImageResource(R.mipmap.app_love_unselected); Toast.makeText(PlayActivity.this, getString(R.string.love_unselected), Toast.LENGTH_SHORT).show(); } } catch (DbException e) { e.printStackTrace(); } break; } default: break; } } }
package com.iwanghang.drmplayer; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.BitmapFactory; import android.graphics.BitmapFactory.Options; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.LayerDrawable; import android.graphics.drawable.TransitionDrawable; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.util.TypedValue; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ListView; import com.astuetz.PagerSlidingTabStrip; import com.astuetz.viewpager.extensions.sample.QuickContactFragment; import com.iwanghang.drmplayer.utils.MediaUtils; import com.iwanghang.drmplayer.vo.Mp3Info; import java.nio.charset.CoderMalfunctionError; import java.util.ArrayList; public class MainActivity extends BaseActivity { // private final Handler handler = new Handler(); private PagerSlidingTabStrip tabs; private ViewPager pager; private MyPagerAdapter adapter; // private Drawable oldBackground = null; // private int currentColor = 0xFFC74B46; private MyMusicListFragment myMusicListFragment; private NetMusicListFragment netMusicListFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs); pager = (ViewPager) findViewById(R.id.pager); adapter = new MyPagerAdapter(getSupportFragmentManager()); pager.setAdapter(adapter); final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources() .getDisplayMetrics()); pager.setPageMargin(pageMargin); tabs.setViewPager(pager); //修改主界面颜色,稍后修复功能,暂时使用默认颜色 //changeColor(currentColor); //绑定服务 //服务在加载SplashActivity(欢迎页面)的时候,已经启动 //bindPlayService(); //这里,我在MyMusicListFragment里面绑定,而没有在MainActivity里绑定 } @Override public void publish(int progress) { //更新进度条 } @Override public void change(int position) { //更新歌曲位置.按钮的状态等信息 /** * 本地音乐的播放UI实际上在MyMusicListFragment中,所以要 * 先在MyMusicListFragmen中,写入public void changeUIStatus(int position){} * 然后,传参过去 */ if (pager.getCurrentItem()==0){//如果页面等于0,则说明选中的是第一个页面,我的音乐页面 myMusicListFragment.loadData();//初始化数据 myMusicListFragment.changeUIStatusOnPlay(position); }else if (pager.getCurrentItem()==1){ } } // @Override // public boolean onCreateOptionsMenu(Menu menu) { // getMenuInflater().inflate(R.menu.main, menu); // return true; // } // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // // switch (item.getItemId()) { // // case R.id.action_contact: // QuickContactFragment dialog = new QuickContactFragment(); // dialog.show(getSupportFragmentManager(), "QuickContactFragment"); // return true; // // } // // return super.onOptionsItemSelected(item); // } // private void changeColor(int newColor) { // // tabs.setIndicatorColor(newColor); // // // change ActionBar color just if an ActionBar is available // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { // // Drawable colorDrawable = new ColorDrawable(newColor); // Drawable bottomDrawable = getResources().getDrawable(R.drawable.actionbar_bottom); // LayerDrawable ld = new LayerDrawable(new Drawable[] { colorDrawable, bottomDrawable }); // // if (oldBackground == null) { // // if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) { // ld.setCallback(drawableCallback); // } else { // getActionBar().setBackgroundDrawable(ld); // } // // } else { // // TransitionDrawable td = new TransitionDrawable(new Drawable[] { oldBackground, ld }); // // // workaround for broken ActionBarContainer drawable handling on // // pre-API 17 builds // // https://github.com/android/platform_frameworks_base/commit/a7cc06d82e45918c37429a59b14545c6a57db4e4 // if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) { // td.setCallback(drawableCallback); // } else { // getActionBar().setBackgroundDrawable(td); // } // // td.startTransition(200); // // } // // oldBackground = ld; // // // http://stackoverflow.com/questions/11002691/actionbar-setbackgrounddrawable-nulling-background-from-thread-handler // getActionBar().setDisplayShowTitleEnabled(false); // getActionBar().setDisplayShowTitleEnabled(true); // // } // // currentColor = newColor; // // } // public void onColorClicked(View v) { // // int color = Color.parseColor(v.getTag().toString()); // changeColor(color); // // } // @Override // protected void onSaveInstanceState(Bundle outState) { // super.onSaveInstanceState(outState); // outState.putInt("currentColor", currentColor); // } // @Override // protected void onRestoreInstanceState(Bundle savedInstanceState) { // super.onRestoreInstanceState(savedInstanceState); // currentColor = savedInstanceState.getInt("currentColor"); // changeColor(currentColor); // } // private Drawable.Callback drawableCallback = new Drawable.Callback() { // @Override // public void invalidateDrawable(Drawable who) { // getActionBar().setBackgroundDrawable(who); // } // // @Override // public void scheduleDrawable(Drawable who, Runnable what, long when) { // handler.postAtTime(what, when); // } // // @Override // public void unscheduleDrawable(Drawable who, Runnable what) { // handler.removeCallbacks(what); // } // }; public class MyPagerAdapter extends FragmentPagerAdapter { private final String[] TITLES = { "本地音乐", "网络音乐"}; public MyPagerAdapter(FragmentManager fm) { super(fm); } @Override public CharSequence getPageTitle(int position) { return TITLES[position]; } @Override public int getCount() { return TITLES.length; } @Override public Fragment getItem(int position) { //return SuperAwesomeCardFragment.newInstance(position); if(position==0){ if(myMusicListFragment==null){ myMusicListFragment = MyMusicListFragment.newInstance(); } return myMusicListFragment; }else if (position == 1){ if(netMusicListFragment==null){ netMusicListFragment = NetMusicListFragment.newInstance(); } return netMusicListFragment; } return null; //return MyMusicListFragment.newInstance(); } } @Override public boolean onCreateOptionsMenu(Menu menu) {//填充菜单 getMenuInflater().inflate(R.menu.main_menu,menu); return true; } public boolean onOptionsItemSelected(MenuItem item){//菜单中事件 switch (item.getItemId()){ case R.id.ilove: Intent intent = new Intent(this,MyLoveMusicActivity.class); startActivity(intent); break; case R.id.near_play: break; } return true; } @Override protected void onDestroy() { super.onDestroy(); //保存当前播放的一些状态值 DRMPlayerApp app = (DRMPlayerApp) getApplication(); SharedPreferences.Editor editor = app.sp.edit(); //保存 当前正在播放的歌曲的位置 editor.putInt("currentPosition",playService.getCurrentPosition()); //保存 播放模式 editor.putInt("play_mode",playService.getPlay_mode()); //保存 提交 editor.commit(); //创建DRMPlayerApp继承Application,同时需要在把AndroidManiFest中的public换成DRMPlayerApp //在DRMPlayerApp的onCreate中 实例化 SharedPreferences //在MainActivity的onDestroy中 保存状态值 //在PlayService的onCreate中 恢复状态值 } }