改造的音乐播放器的例子(学习Service和BroadCastReceiver必用)

[ZT]:http://www.eoeandroid.com/thread-13616-1-1.html

 

沈青海的视频教程Android Service初级应用讲解是用音乐播放器做为例子,同时也用到了BroadCastReceiver,这样就可以作为和Activity三者之间相互作用的最佳范例了。鄙人觉得视频看不清楚,贴出的代码又不全,所以加以补充,自己添加布局和按钮,编写Main.xml文件。这样工程就完整可用了,希望对您有所帮助。
感谢沈先生的视频和源码,非常值得仔细研究。
沈先生网站视频链接地址:http://www.3gqa.com/?p=1510
直接贴代码:
服务:MusicService.java

  1. package work.service;
  2. import java.io.IOException;   
  3. import android.app.Service;   
  4. import android.content.Intent;   
  5. import android.media.MediaPlayer;   
  6. import android.os.Binder;   
  7. import android.os.Bundle;   
  8. import android.os.IBinder;   
  9. import android.util.Log;
  10.   
  11. public class MusicService extends Service {   
  12.   
  13.     // MediaPlayer实例   
  14.     private MediaPlayer player;   
  15.   
  16.     // IBinder实例   
  17.     private final IBinder binder = new MyBinder();   
  18.   
  19.     /**  
  20.      * 绑定  
  21.      */  
  22.     @Override  
  23.     public IBinder onBind(Intent intent) {   
  24.         playMusic();   
  25.         return binder;   
  26.     }   
  27.   
  28.     /**  
  29.      * 声明Binder子类  
  30.      *   
  31.      * @author www.3gqa.com  
  32.      *   
  33.      */  
  34.     public class MyBinder extends Binder {   
  35.         MusicService getService() {   
  36.             return MusicService.this;   
  37.         }   
  38.   
  39.     }   
  40.   
  41.     /**  
  42.      * 创建服务  
  43.      */  
  44.     public void onCreate() {   
  45.         super.onCreate();
  46.         Log.e("TAG", "onCreate");
  47.         playMusic();   
  48.     }   
  49.   
  50.     /**  
  51.      * 播放  
  52.      */  
  53.     public void playMusic() {   
  54.         if (player == null) {
  55.                 Log.e("TAG", "playMusic");
  56.             player = MediaPlayer.create(this, R.raw.yuanlai);   
  57.         }   
  58.         if (!player.isPlaying()) {   
  59.             player.start();   
  60.         }   
  61.     }   
  62.   
  63.     /**  
  64.      * 暂停播放  
  65.      */  
  66.     public void pauseMusic() {   
  67.         if (player != null)   
  68.             if (player.isPlaying()) {   
  69.                     Log.e("TAG", "pauseMusic");
  70.                     player.pause();
  71.                
  72.             }   
  73.     }   
  74.   
  75.     /**  
  76.      * 停止播放  
  77.      */  
  78.     public void stopMusic() {   
  79.         if (player != null) {
  80.                 Log.e("TAG", "stopMusic");
  81.             player.stop();   
  82.             try {   
  83.                 // 在调用stop后如果需要再次通过start进行播放,需要之前调用prepare函数   
  84.                 player.prepare();   
  85.             } catch (IOException ex) {   
  86.                 ex.printStackTrace();   
  87.             }   
  88.         }   
  89.     }   
  90.   
  91.     /**  
  92.      * 开始播放  
  93.      */  
  94.     public void onStart(Intent intent, int startId) {   
  95.         super.onStart(intent, startId);   
  96.         Log.e("TAG", "onStart");
  97.         if (intent != null) {   
  98.             Bundle bundle = intent.getExtras();   
  99.             if (bundle != null) {   
  100.                 int op = bundle.getInt("op");   
  101.                 switch (op) {   
  102.                 case 1:   
  103.                     playMusic();   
  104.                     break;   
  105.                 case 2:   
  106.                     pauseMusic();   
  107.                     break;   
  108.                 case 3:   
  109.                     stopMusic();   
  110.                     break;   
  111.                 }   
  112.             }   
  113.         }   
  114.     }   
  115.   
  116.     /**  
  117.      * 销毁服务  
  118.      */  
  119.     public void onDestroy() {   
  120.         super.onDestroy();  
  121.         Log.e("TAG", "onDestroy");
  122.         if (player != null) {   
  123.             player.stop();   
  124.             player.release();   
  125.         }   
  126.     }   
  127.   
  128. }  
复制代码

广播接收器:MusicReceiver.java

  1. package work.service;
  2. import android.content.BroadcastReceiver;   
  3. import android.content.Context;   
  4. import android.content.Intent;   
  5. import android.os.Bundle;   
  6. import android.util.Log;
  7. /**  
  8. *   
  9. * @author 3gqa.com  
  10. *  
  11. */  
  12. public class MusicReceiver extends BroadcastReceiver {   
  13.     Context context;   
  14.   
  15.     @Override  
  16.     public void onReceive(Context context, Intent intent) {
  17.             Log.e("TAG", "onReceive");
  18.         this.context = context;   
  19.         Intent it = new Intent("work.service.MUSIC_SERVICE_SERVICE");   
  20.         Bundle bundle = intent.getExtras();   
  21.         it.putExtras(bundle);   
  22.         if (bundle != null) {   
  23.             int op = bundle.getInt("op");   
  24.             Log.e("TAG", "Receive"+op+"...........");
  25.             if (op == 4) {   
  26.                 context.stopService(it);   
  27.             } else {   
  28.                 context.startService(it);   
  29.                 // context.bindService(it, mConnection,   
  30.                 // Context.BIND_AUTO_CREATE);   
  31.             }   
  32.         }   
  33.     }   
  34. }  
复制代码

界面Activity类:ExampleServiceRequest.java

  1. package work.service;
  2. import android.app.Activity;   
  3. import android.content.ComponentName;
  4. import android.content.Intent;   
  5. import android.content.ServiceConnection;
  6. import android.os.Bundle;   
  7. import android.os.IBinder;
  8. import android.util.Log;
  9. import android.view.View;   
  10. import android.view.View.OnClickListener;   
  11. import android.widget.Button;   
  12. import android.widget.LinearLayout;
  13. /**  
  14. *   
  15. * @author 3gqa.com  
  16. *  
  17. */  
  18. public class ExampleServiceRequest extends Activity implements OnClickListener {   
  19.     Button btnStartservice;   
  20.     Button btnPlay;   
  21.     Button btnPause;   
  22.     Button btnStop;   
  23.     Button btnStopservice;   
  24.     Button btnExit;   
  25.   
  26.     /** Called when the activity is first created. */  
  27.     @Override  
  28.     public void onCreate(Bundle savedInstanceState) {   
  29.         super.onCreate(savedInstanceState);   
  30. //        setContentView(R.layout.main);   
  31.         //
  32.         LinearLayout l=new LinearLayout(this);
  33.         l.setOrientation(LinearLayout.VERTICAL);//垂直布局
  34.         LinearLayout.LayoutParams ll=new LinearLayout.LayoutParams(
  35.                         LinearLayout.LayoutParams.FILL_PARENT,
  36.                         LinearLayout.LayoutParams.WRAP_CONTENT
  37.         );
  38.         
  39.         
  40.         //
  41.         Button btnStartservice = new Button(this);
  42.         btnStartservice.setId(01);
  43.         btnStartservice.setText("开始服务");
  44.         btnStartservice.setOnClickListener(this);
  45.         l.addView(btnStartservice, ll);
  46.         //   
  47.         Button btnPlay = new Button(this);
  48.         btnPlay.setId(02);
  49.         btnPlay.setText("播放音乐");
  50.         btnPlay.setOnClickListener(this);
  51.         l.addView(btnPlay, ll);
  52.         //   
  53.         Button btnPause = new Button(this);
  54.         btnPause.setId(03);
  55.         btnPause.setText("暂停");
  56.         btnPause.setOnClickListener(this);
  57.         l.addView(btnPause, ll);
  58.         //   
  59.         Button btnStop =new Button(this);
  60.         btnStop.setId(04);
  61.         btnStop.setText("停止");
  62.         btnStop.setOnClickListener(this);
  63.         l.addView(btnStop, ll);
  64.         //   
  65.         Button btnStopservice =new Button(this);
  66.         btnStopservice.setId(05);
  67.         btnStopservice.setText("停止服务");
  68.         btnStopservice.setOnClickListener(this);
  69.         l.addView(btnStopservice, ll);
  70.         //   
  71.         Button btnExit =new Button(this);
  72.         btnExit.setId(06);
  73.         btnExit.setText("退出");
  74.         btnExit.setOnClickListener(this);
  75.         l.addView(btnExit, ll);
  76.         
  77.         
  78.         this.setContentView(l);
  79.     }   
  80.   
  81.     /**  
  82.      * 点击处理
  83.      */  
  84.     public void onClick(View v) {
  85.            
  86.               
  87.            
  88.         int op = -1;   
  89.         
  90.         if (v==(findViewById(01))){
  91.                
  92.             op = 0;  }
  93.         else if (v.equals(findViewById(02)))   
  94.             op = 1;   
  95.         else if (v.equals(findViewById(03)))   
  96.             op = 2;   
  97.         else if (v.equals(findViewById(04)))   
  98.             op = 3;   
  99.         else if (v.equals(findViewById(05)))   
  100.             op = 4;   
  101.         else if (v.equals(findViewById(06))) {   
  102.             this.finish();   
  103.             return;   
  104.         }   
  105.         Log.e("TAG", "onClick..."+op+"...........");
  106.         // 构造数据  
  107.         Bundle bundle = new Bundle();   
  108.         bundle.putInt("op", op);   
  109.         Intent intent = new Intent("work.service.MUSIC_SERVICE_BROADCAST");
  110.         intent.putExtras(bundle);   
  111.         // 发送广播   
  112.         sendBroadcast(intent);
  113.         
  114.         Log.e("TAG", "Broadcast"+op+"...........");
  115.     }
  116.    /*
  117.     *//**
  118.      *  服务实例
  119.      *//*
  120.     private MusicService serviceBinder;
  121.     *//**
  122.      * 当服务和Activity连接时调用函数
  123.      *
  124.      *//*
  125.     private ServiceConnection mConnection=new ServiceConnection(){
  126.                 public void onServiceConnected(ComponentName name, IBinder service) {
  127.                         serviceBinder=((MusicService.MyBinder)service).getService();//???
  128.                         if(serviceBinder!=null){
  129.                                 serviceBinder.playMusic();
  130.                         }
  131.                        
  132.                 }
  133.                 *//**
  134.                  * 当服务和Activity断开时调用
  135.                  *//*
  136.                 public void onServiceDisconnected(ComponentName name) {
  137.                         serviceBinder=null;
  138.                        
  139.                 }
  140.            
  141.     };*/
  142. }  
复制代码

主配置文件:AndroidManifest.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3.       package="work.service"
  4.       android:versionCode="1"
  5.       android:versionName="1.0">
  6.     <application android:icon="@drawable/icon" android:label="@string/app_name">
  7.     <activity android:name="ExampleServiceRequest">
  8.             <intent-filter>
  9.                 <action android:name="android.intent.action.MAIN" />
  10.                 <category android:name="android.intent.category.LAUNCHER" />
  11.         </intent-filter>
  12.    
  13.     </activity>
  14.    
  15.         <service android:name="MusicService">
  16.                 <intent-filter>
  17.                 <action android:name="work.service.MUSIC_SERVICE_SERVICE" />
  18.                 <category android:name="android.intent.category.defult" />
  19.                
  20.         </intent-filter>
  21.         </service>
  22.        
  23.         <receiver android:name="MusicReceiver">
  24.                 <intent-filter>
  25.                         <action android:name="work.service.MUSIC_SERVICE_BROADCAST"/>
  26.                 </intent-filter>
  27.        
  28.         </receiver>
  29. </application>
  30.     <uses-sdk android:minSdkVersion="7" />
  31. </manifest>
复制代码

工程文件,如果不会贴的就倒吧,其实不必破费呵呵
操,我的p3文件太大了,传不上来,算了,想要的都贴自己工程里吧,练练手,我没用其他的xml,都是自己在代码里布局的

 

[ZT]:http://www.eoeandroid.com/thread-13616-1-1.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值