Android学习笔记(21)---使用Service后台播放MediaPlayer的音乐

来源:互联网 发布:网络配线架 编辑:程序博客网 时间:2024/05/29 07:07

1、Service介绍

官方解释:Service is an application component that can perform long-running operations in the background and does not provide a user interface. Another application component can start a service and it will continue to run in the background even if the user switches to another application

也就是说Service是一个没有提供用户界面而能够提供在后台运行的构件,其他应用能启动一个Service,即使是切换到其他的应用它还能在后台运行。

2、Service的生命周期

Android Service的生命周期并不像Activity那么复杂,它只继承了onCreate(),onStart(),onDestroy()三个方法,当我们第一次启动Service时,先后调用了onCreate(),onStart()这两个方法,当停止Service时,则执行onDestroy()方法,这里需要注意的是,如果Service已经启动了,当我们再次启动Service时,不会在执行onCreate()方法,而是直接执行onStart()方法。

3、下面举个播放音乐的例子:

首先在res创建目录raw,然后在里面添加MP3文件

继承一个Service类:

package com.Moruna.studys;import android.app.Service;import android.content.Intent;import android.media.MediaPlayer;import android.os.IBinder;public class MyService extends Service {private MediaPlayer mp;@Overridepublic void onCreate() {// TODO Auto-generated method stub// 初始化音乐资源try {System.out.println("create player");// 创建MediaPlayer对象mp = new MediaPlayer();mp = MediaPlayer.create(MyService.this, R.raw.alarm);// mp.prepare();} catch (IllegalStateException e) {// TODO Auto-generated catch blocke.printStackTrace();}super.onCreate();}@Overridepublic void onStart(Intent intent, int startId) {// TODO Auto-generated method stub// 开始播放音乐mp.start();// 音乐播放完毕的事件处理mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {public void onCompletion(MediaPlayer mp) {// TODO Auto-generated method stub// 循环播放try {mp.start();} catch (IllegalStateException e) {// TODO Auto-generated catch blocke.printStackTrace();}}});// 播放音乐时发生错误的事件处理mp.setOnErrorListener(new MediaPlayer.OnErrorListener() {public boolean onError(MediaPlayer mp, int what, int extra) {// TODO Auto-generated method stub// 释放资源try {mp.release();} catch (Exception e) {e.printStackTrace();}return false;}});super.onStart(intent, startId);}@Overridepublic void onDestroy() {// TODO Auto-generated method stub// 服务停止时停止播放音乐并释放资源mp.stop();mp.release();super.onDestroy();}@Overridepublic IBinder onBind(Intent intent) {// TODO Auto-generated method stubreturn null;}}
在Activity中调用MyService启动音乐或关闭音乐,这时就算退出应用,如果没有关闭Service,它还会在后台播放直至关闭

在Alarm这个Activity继承类中启动音乐:

// 播放闹铃Intent intentSV = new Intent(Alarm.this, MyService.class);startService(intentSV);

在Alarm这个Activity继承类中关闭音乐:

//关闭闹铃声Intent intentSV = new Intent(Alarm.this, MyService.class);stopService(intentSV);

这样就能实现Service在后台播放所要播放的音乐,当然,在哪里需要启动或关闭音乐看你自己个人需求。

另需要注意一点的是,别忘了注册:

在AndroidManifest.xml中的Application中加入:

<service android:name=".MyService" />






原创粉丝点击