网站首页 > Android开发

Android Service 音乐播放实例

  Service翻译成中文是服务,熟悉Windows 系统的同学一定很熟悉了。Android里的Service跟Windows里的Service功能差不多,就是一个不可见的进程在后台执行。   Android中的服务,它与Activity不同,它是不能与用户交互的,不能自己启动的,运行在后台的程序,如果我们退出应用时,Service进程并没有结束,它仍然在后台运行,例如我们打开一个音乐播放器来听音乐,在听音乐的同时也想做下其它的事情,比如上网聊Q、或者上网浏览新闻之类的事情。这样的话,我们就需要用到Service服务了。下面我们以一个简单的音乐播放器的实例来说明下Service的生命周期和Service的使用。
下面是音乐播放器Demo的程序结构图:

Android Service 的生命周期:
Android中Service的生命周期并不是很复杂,只是继承了onCreate(), onStart(), onDestory()三个方法。当我们第一次启动Service服务时,调用onCreate() --> onStart()两个方法,当停止Service服务时,调用onDestory()方法。如果Service已经启动了,第二次再启动同一个服务时,就只是调用 onStart() 这个方法了。
Android Service 的使用:
[1] 参照上面的程序结构图,我们可以创建一个Android程序,在src目录下创建一个Activity,一个继承自Service类的服务类;同时在资源文件夹res目录下创建一个raw的文件夹存放音频文件,如把music.mp3音乐文件放在该目录下。该程序的主界面如下:

[2] layout目录下的main.xml文件的源码:
 
view plain
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="fill_parent"  
  5.     android:layout_height="fill_parent"  
  6.     >  
  7.     <TextView    
  8.        android:layout_width="fill_parent"   
  9.        android:layout_height="wrap_content"   
  10.        android:text="Welcome to Andy's blog!"  
  11.        android:textSize="16sp"/>     
  12.     <TextView    
  13.        android:layout_width="fill_parent"   
  14.        android:layout_height="wrap_content"   
  15.        android:text="音乐播放服务"/>  
  16.     <Button  
  17.        android:id="@+id/startMusic"   
  18.        android:layout_width="wrap_content"  
  19.        android:layout_height="wrap_content"  
  20.        android:text="开启音乐播放服务"/>  
  21.     <Button  
  22.        android:id="@+id/stopMusic"   
  23.        android:layout_width="wrap_content"  
  24.        android:layout_height="wrap_content"  
  25.        android:text="停止音乐播放服务"/>  
  26.    <Button  
  27.       android:id="@+id/bindMusic"   
  28.       android:layout_width="wrap_content"  
  29.       android:layout_height="wrap_content"  
  30.       android:text="绑定音乐播放服务"/>  
  31.    <Button  
  32.       android:id="@+id/unbindMusic"   
  33.       android:layout_width="wrap_content"  
  34.       android:layout_height="wrap_content"  
  35.       android:text="解除 ——绑定音乐播放服务"/>  
  36. </LinearLayout>  
 

发表评论

验证码: 点击验证码
  • 手机软件开发
    专业手机软件开发|手机客户端开发
    j2me手机软件开发|Android开发
  • 手机游戏开发
    手机游戏开发|symbian游戏开发
    Android开发|j2me手机游戏开发
  • windows phone开发
    windows phone软件开发,windows phone游戏开发
  • Android开发
    Android手机软件开发,Android游戏开发,android 软件开发
  • symbian开发
    symbian手机软件开发,symbian游戏开发,塞班手机软件开发

信息化系统集成

定制解决方案

手机软件定制