利用Service实现背景音乐的播放
2015-06-30 21:42
447 查看
在android应用程序里,有一种没有UI的类(android.app.Service)——Service。简单来说,Service是一个 background process(背景程序),通过背景程序,可以实现一些不需要UI的功能,比如播放背景音乐。
当然,首先要在资源文件夹中添加一首MP3歌曲:
<strong>1、Activity类
[java]
</strong> <pre name="code" class="html">package demo.camera; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.view.View;
/** * 演示Activity如何利用Service来完成后台Audio的播放功能 * 同时如何将Service和Activity进行绑定 * @author Administrator * */ public class BackgroundAudioDemo extends Activity { private AudioService audioService; //使用ServiceConnection来监听Service状态的变化 private ServiceConnection conn =
new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { // TODO Auto-generated method stub audioService = null; } @Override public void onServiceConnected(ComponentName name, IBinder binder) { //这里我们实例化audioService,通过binder来实现
audioService = ((AudioService.AudioBinder)binder).getService(); } }; public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.back_audio); } public void onClick(View v){ int id = v.getId(); Intent intent
= new Intent(); intent.setClass(this, AudioService.class); if(id == R.id.btn_start){ //启动Service,然后绑定该Service,这样我们可以在同时销毁该Activity,看看歌曲是否还在播放 startService(intent); bindService(intent, conn, Context.BIND_AUTO_CREATE); finish(); }else if(id == R.id.btn_end){
//结束Service unbindService(conn); stopService(intent); finish(); }else if(id == R.id.btn_fun){ audioService.haveFun(); } } }
当然,首先要在资源文件夹中添加一首MP3歌曲:
<strong>1、Activity类
[java]
</strong> <pre name="code" class="html">package demo.camera; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.view.View;
/** * 演示Activity如何利用Service来完成后台Audio的播放功能 * 同时如何将Service和Activity进行绑定 * @author Administrator * */ public class BackgroundAudioDemo extends Activity { private AudioService audioService; //使用ServiceConnection来监听Service状态的变化 private ServiceConnection conn =
new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { // TODO Auto-generated method stub audioService = null; } @Override public void onServiceConnected(ComponentName name, IBinder binder) { //这里我们实例化audioService,通过binder来实现
audioService = ((AudioService.AudioBinder)binder).getService(); } }; public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.back_audio); } public void onClick(View v){ int id = v.getId(); Intent intent
= new Intent(); intent.setClass(this, AudioService.class); if(id == R.id.btn_start){ //启动Service,然后绑定该Service,这样我们可以在同时销毁该Activity,看看歌曲是否还在播放 startService(intent); bindService(intent, conn, Context.BIND_AUTO_CREATE); finish(); }else if(id == R.id.btn_end){
//结束Service unbindService(conn); stopService(intent); finish(); }else if(id == R.id.btn_fun){ audioService.haveFun(); } } }
<strong>新建一个AudioService 类,<span style="font-family: Arial, Helvetica, sans-serif;">AudioService 类</span><span style="font-family: Arial, Helvetica, sans-serif;">继承 android.app.Service,几个有关Service 的重要概念如下:</span> 1. Service 对象以 separated process 的方式执行,这表示 Service 与 UI(Activity)并不在同一个 process 里执行,而是各自在不同的 process 执行。 2. Android应用程序是在 Activity 启动与停止 Service。 3. 重载(override)onStart() 方法(method)在 Service 被启动,执行我们想要的背景功能。 4. 重载 onDestroy() 方法在 Service 被停止时,停止执行中的背景功能。</strong>
<pre name="code" class="html"><strong>2、AudioService类 [java] </strong> package demo.camera; import android.app.Service; import android.content.Intent; import android.media.MediaPlayer; import android.os.Binder; import android.os.IBinder; import android.widget.MediaController.MediaPlayerControl; /** * 为了可以使得在后台播放音乐,我们需要Service * Service就是用来在后台完成一些不需要和用户交互的动作 * @author Administrator * */ public class AudioService extends Service implements MediaPlayer.OnCompletionListener{ MediaPlayer player; private final IBinder binder = new AudioBinder(); @Override public IBinder onBind(Intent arg0) { // TODO Auto-generated method stub return binder; } /** * 当Audio播放完的时候触发该动作 */ @Override public void onCompletion(MediaPlayer player) { // TODO Auto-generated method stub stopSelf();//结束了,则结束Service } //在这里我们需要实例化MediaPlayer对象 public void onCreate(){ super.onCreate(); //我们从raw文件夹中获取一个应用自带的mp3文件 player = MediaPlayer.create(this, R.raw.eason); player.setOnCompletionListener(this); } /** * 该方法在SDK2.0才开始有的,替代原来的onStart方法 */ public int onStartCommand(Intent intent, int flags, int startId){ if(!player.isPlaying()){ player.start(); } return START_STICKY; } public void onDestroy(){ //super.onDestroy(); if(player.isPlaying()){ player.stop(); } player.release(); } //为了和Activity交互,我们需要定义一个Binder对象 class AudioBinder extends Binder{ //返回Service对象 AudioService getService(){ return AudioService.this; } } //后退播放进度 public void haveFun(){ if(player.isPlaying() && player.getCurrentPosition()>2500){ player.seekTo(player.getCurrentPosition()-2500); } } }
<pre name="code" class="html">至此,一个完整的服务生成,接下来是在Activity中启动服务。 <strong>修改 AndroidManifest.xml: 在 Package Explorer 视窗里找到目前 Android 项目的资讯描述档,名称为 AndroidManifest.xml。这是一个用來描述 Android 应用程序「整体资讯」的文件,每个 Android 应用程序项目都会有一个。在这里修改 Androidmanifest.xml 的目的是为了「 Android 应用程序加入一个 Service 类别」,这样才有办法驱动 Service。</strong> [html]
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.android" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="10" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:name=".WebTestActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service <pre name="code" class="html"> android:name=".AudioService"android:exported="true" android:process=":remote"> </service> </application> </manifest>
相关文章推荐
- iOS网络请求简单封装
- 欢迎使用CSDN-markdown编辑器
- vector2D向量实例
- 黑马程序员——单例设计模式
- 【GC】Grid Control Agent完整删除方法
- 千山万水之Hibernate(十一)——懒加载(占位)
- 大数据的几个方面
- 单元最短路
- #pragma pack(n) 的作用
- MDS(multidimensional scaling)多维尺度分析
- Java实现简单的二分法查找int数组中的某值
- DWZ(三):常用组件了解
- XML(五)dom4j增删改查
- 链式栈(c++实现)
- (HTML)写导航感悟
- 设计模式之简单工厂模式
- json数据解析
- NSString和NSMutableString的相关总结
- Java常用对象
- PHP学习笔记1:基础知识快速浏览