基于Service的简易音乐播放器

第一步在MainActivity中获取XML中的组件并初始化界面点击事件,在MainActivity建一个ActivityReceiver继承BroadcastReceiver用以监听歌曲状态的变化从而更新UI,代码如下:

 
[java]  view plain  copy
  1. public class MainActivity extends Activity implements View.OnClickListener{  
  2.     TextView title,author,situation;  
  3.     Button play,stop;  
  4.     //  播放控制开始结束控制ACTION  
  5.     public static final String CTL_ACTION = "com.example.service_musicplayer.ctl_action";  
  6.     //  歌曲播放状态ACTION  
  7.     public static final String UPDATE_ACTION = "com.example.service_musicplayer.update_action";  
  8.     ActivityReceiver activityReceiver;  
  9.     //定义播放状态  0x11代表没有播放  0x12 代表正在播放  0x13代表暂停  
  10.     int status = 0x11;  
  11.     //  存放歌曲名  
  12.     String titleStr[] = {"Music-1","Music-2","Music-3"};  
  13.     //  存放歌手名  
  14.     String authorStr[] = {"author-1","author-2","author-3"};  
  15.     @Override  
  16.     protected void onCreate(Bundle savedInstanceState) {  
  17.         super.onCreate(savedInstanceState);  
  18.         setContentView(R.layout.activity_main);  
  19.         play = (Button) findViewById(R.id.play);  
  20.         stop = (Button) findViewById(R.id.stop);  
  21.         title = (TextView) findViewById(R.id.title);  
  22.         author = (TextView) findViewById(R.id.author);  
  23.         situation = (TextView) findViewById(R.id.situation);  
  24.         play.setOnClickListener(this);  
  25.         stop.setOnClickListener(this);  
  26.         //  使用代码方式为broadcastReceiver注册监听  
  27.          activityReceiver = new ActivityReceiver();  
  28.         IntentFilter intentFilter = new IntentFilter();  
  29.         intentFilter.addAction(UPDATE_ACTION);  
  30.         //  注册broadcastReceiver  
  31.         registerReceiver(activityReceiver,intentFilter);  
  32.         Intent intent = new Intent(this,MusicService.class);  
  33.         startService(intent);  
  34.     }  
  35.   
  36.     @Override  
  37.     public void onClick(View v) {  
  38.         Intent intent = new Intent();  
  39.         intent.setAction(CTL_ACTION);  
  40.         switch (v.getId()){  
  41.             case R.id.play:  
  42.                 intent.putExtra("control",1);  
  43.                 break;  
  44.             case R.id.stop:  
  45.                 intent.putExtra("control",2);  
  46.                 break;  
  47.         }  
[java]  view plain  copy
  1.      <span style="white-space:pre">   </span>sendBroadcast(intent);  
  2.     }  
  3.     //   自定义BroadcastReceiver 监听Servicec传来的广播  
  4.     public class ActivityReceiver extends BroadcastReceiver{  
  5.   
  6.         @Override  
  7.         public void onReceive(Context context, Intent intent) {  
  8.             String str = "";  
  9.             int update  = intent.getIntExtra("update",-1);  
  10.             int current = intent.getIntExtra("current",-1);  
  11.             if(current >= 0){  
  12.                 title.setText(titleStr[current]);  
  13.                 author.setText(authorStr[current]);  
  14.             }  
  15.             switch (update){  
  16.                 case 0x11:  
  17.                //     status = 0x11;  
  18.                     str = "未播放";  
  19.                     break;  
  20.                 case 0x12:  
  21.               //      status = 0x12;  
  22.                     str = "正在播放";  
  23.                     break;  
  24.                 case 0x13:  
  25.                //     status = 0x13;  
  26.                     str = "暂停";  
  27.                     break;  
  28.             }  
  29.             situation.setText(str);  
  30.         }  
  31.     }  
  32. }  

第二步:新建MusicService继承Service,MusicService中建了一个MyReceiver类继承BroadcastReceiver类用以监听歌曲播放状态的变化,以广播的方式将歌曲播放状态发出,在MainActivity中的ActivityReceiver能监听到此状态变化来更新UI,代码如下:

[java]  view plain  copy
  1. <span style="font-size:18px;">public class MusicService extends Service {  
  2.     String musics[] = new String[]{"Leo Kayyu - Nokia Tune(Remix).mp3""canon.mp3""Cvked - iphone(Caked Up Mashup).mp3"};  
  3.     int current = 0;  
  4.     int status = 0x11// 0x11不在播放状态  0x12正在播放  0x13暂停播放  
  5.     MediaPlayer mediaPlayer;  
  6.     AssetManager am;  
  7.     MyReceiver serviceReceiver;  
  8.     @Override  
  9.     public IBinder onBind(Intent intent) {  
  10.   
  11.         return null;  
  12.     }  
  13.   
  14.     @Override  
  15.     public void onCreate() {  
  16.         am = getAssets();  
  17.         serviceReceiver = new MyReceiver();  
  18.         //  代码方式为MyReceiver注册  
  19.         IntentFilter intentFilter = new IntentFilter();  
  20.         intentFilter.addAction(MainActivity.CTL_ACTION);  
  21.         registerReceiver(serviceReceiver,intentFilter);  
  22.         mediaPlayer = new MediaPlayer();  
  23.         mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {  
  24.             @Override  
  25.             public void onCompletion(MediaPlayer mp) {  
  26.                 current++;  
  27.                 if(current>=3) {  
  28.                     current = 0;  
  29.                 }  
  30.                     Intent sendIntent = new Intent(MainActivity.UPDATE_ACTION);  
  31.                     sendIntent.putExtra("current",current);  
  32.                     sendBroadcast(sendIntent);  
  33.                     prepareAndPlay(musics[current]);  
  34.             }  
  35.         });  
  36.     }  
  37.     //   监听歌曲的播放状态,在歌曲播放状态改变时触发  
  38.     public class MyReceiver extends BroadcastReceiver{  
  39.   
  40.         @Override  
  41.         public void onReceive(Context context, Intent intent) {  
  42.             int control = intent.getIntExtra("control",-1);  
  43.             switch(control){  
  44.                 case 1:  
  45.                         //原来是没播放的状态  
  46.                     if(status == 0x11){  
  47.                         prepareAndPlay(musics[current]);  
  48.                         status = 0x12;  
  49.                         //原来处于播放状态  
  50.                     }else if(status == 0x12){  
  51.                         mediaPlayer.pause();  
  52.                         status = 0x13;  
  53.                         //  原来处于暂停状态  
  54.                     }else if(status == 0x13){  
  55.                         mediaPlayer.start();  
  56.                         status = 0x12;  
  57.                     }  
  58.                     break;  
  59.                 case 2:  
  60.                     //  原来在播放或暂停状态  
  61.                     if(status == 0x12 || status == 0x13){  
  62.                         mediaPlayer.stop();  
  63.                         status = 0x11;  
  64.                     }  
  65.                     break;  
  66.             }  
  67.             Intent sendIntent = new Intent(MainActivity.UPDATE_ACTION);  
  68.             sendIntent.putExtra("update",status);  
  69.             sendIntent.putExtra("current",current);  
  70.             sendBroadcast(sendIntent);  
  71.         }  
  72.     }  
  73.     public void prepareAndPlay(String music){  
  74.         try {</span>  
[java]  view plain  copy
  1. <span style="font-size:18px;"><span style="white-space:pre">    </span>    mediaPlayer.reset();  
  2.             AssetFileDescriptor afd = am.openFd(URLEncoder.encode(music,"utf-8"));  
  3.             mediaPlayer.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());  
  4.             // 准备声音  
  5.             mediaPlayer.prepare();  
  6.             // 播放  
  7.             mediaPlayer.start();  
  8.         } catch (IOException e) {  
  9.             e.printStackTrace();  
  10.         }  
  11.     }  
  12. }</span>  
:程序的布局文件

[html]  view plain  copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     xmlns:tools="http://schemas.android.com/tools"  
  4.     android:layout_width="match_parent"  
  5.     android:layout_height="match_parent"  
  6.     android:paddingBottom="@dimen/activity_vertical_margin"  
  7.     android:paddingLeft="@dimen/activity_horizontal_margin"  
  8.     android:paddingRight="@dimen/activity_horizontal_margin"  
  9.     android:paddingTop="@dimen/activity_vertical_margin"  
  10.     tools:context="com.example.service_musicplayer.MainActivity">  
  11.   
  12.     <TextView  
  13.         android:id="@+id/title"  
  14.         android:layout_width="match_parent"  
  15.         android:layout_height="wrap_content"  
  16.         android:text="歌名"  
  17.         android:textSize="20dp"/>  
  18.     <Button  
  19.         android:id="@+id/play"  
  20.         android:layout_width="wrap_content"  
  21.         android:layout_height="wrap_content"  
  22.         android:text="play"  
  23.         android:layout_below="@+id/title"/>  
  24.     <Button  
  25.         android:id="@+id/stop"  
  26.         android:layout_width="wrap_content"  
  27.         android:layout_height="wrap_content"  
  28.         android:text="stop"  
  29.         android:layout_toRightOf="@+id/play"  
  30.         android:layout_alignBaseline="@+id/play"/>  
  31.     <TextView  
  32.         android:id="@+id/author"  
  33.         android:layout_width="wrap_content"  
  34.         android:layout_height="wrap_content"  
  35.         android:layout_below="@+id/play"  
  36.         android:text="作者/歌手"  
  37.         android:textSize="20dp"/>  
  38.     <TextView  
  39.         android:id="@+id/situation"  
  40.         android:layout_width="wrap_content"  
  41.         android:layout_height="wrap_content"  
  42.         android:layout_below="@+id/play"  
  43.         android:text="播放状态"  
  44.         android:textSize="20dp"  
  45.         android:layout_toRightOf="@+id/author"  
  46.         android:layout_marginLeft="20dp"/>  
  47. </RelativeLayout>  

运行界面如下:


注意事项 :歌曲文件放在assets文件下,使用Android studio 时没有assets文件就要自己新建一个assets文件,歌曲名不能有中文,另在程序中为两个广播注册了再配置文件中无须再注册,但记得在AndroidManifest.xml中注册service,注册注册代码为:
<service android:name=".MusicService"/>
(以上代码参照了安卓疯狂讲义,但是书上没讲音频文件应该放在哪里,自己新添了播放状态TextView)
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值