1. 主要 引用 这个类(AudioService.java)
1 public class AudioService extends Service implements 2 MediaPlayer.OnCompletionListener { 3 // 实例化MediaPlayer对象 4 MediaPlayer player; 5 private final IBinder binder = new AudioBinder(); 6 7 @Override 8 public IBinder onBind(Intent intent) { 9 return binder; 10 } 11 12 public void onCreate() { 13 super.onCreate(); 14 // 从raw文件夹中获取一个应用自带的mp3文件 15 player = MediaPlayer.create(this, R.raw.qq); 16 player.setOnCompletionListener(this); 17 player.setLooping(true); 18 } 19 20 @Override 21 public int onStartCommand(Intent intent, int flags, int startId) { 22 super.onStartCommand(intent, flags, startId); 23 if (!player.isPlaying()) { 24 new MusicPlayThread().start(); 25 } 26 else player.isPlaying(); 27 return START_STICKY; 28 } 29 30 31 /** 32 * 当Audio播放完的时候触发该动作 33 */ 34 public void onCompletion(MediaPlayer mp) { 35 stopSelf();// 结束了,则结束Service 36 } 37 38 public void onDestroy() { 39 super.onDestroy(); 40 if (player.isPlaying()) { 41 player.stop(); 42 } 43 player.release(); 44 } 45 46 // 为了和Activity交互,我们需要定义一个Binder对象 47 public class AudioBinder extends Binder { 48 // 返回Service对象 49 public AudioService getService() { 50 return AudioService.this; 51 } 52 } 53 54 private class MusicPlayThread extends Thread { 55 public void run() { 56 if (!player.isPlaying()) { 57 player.start(); 58 } 59 } 60 } 61 62 }
AudioService.java
2.自动播放 功能用了 SharedPreferences
3. 在AndroidManifest.xml中的</activity>下面加上
<service android:name="com.example.musicServer.AudioService" ></service>
4.界面运行图
时间: 2024-11-13 05:18:54