Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android學習指南之十四:Service組件詳解與音樂播放實戰

編輯:關於 Android 開發

上一節我們聊了Gallery畫廊,這一節把焦點轉向Android四大基礎組件之一的Service。本篇會帶大家理清Service的概念、生命周期,並通過一個後台播放音樂的實例,把知識真正用起来。

一、Service是什麼

Service和Activity同屬Context的子類,但最大的不同在於它沒有用戶界面,是在後台默默工作的組件。它常被用來處理不需要交互的持續性任務,比如播放音樂、下載文件等。

二、Service的生命周期

Service無法自行啟動,必須借助Activity、其他Service或任意Context對象來拉動。啟動方式有兩種:Context.startService()和Context.bindService(),二者對應的生命周期截然不同。

採用startService方式:

啟動時:startService → onCreate() → onStart()

停止時:stopService → onDestroy()

採用bindService方式:

綁定時:bindService → onCreate() → onBind()

解綁時:unbindService → onUnbind() → onDestroy()

三、Service實戰:控制音樂播放

下面我們動手做一個能在後台播放音樂的例子。做完你會直觀地發現:通過綁定方式啟動的Service,會隨着綁定對象被銷毀而一同銷毀。

編寫步驟如下:

第一步,新建項目Lesson14_HelloService,Activity命名為MainHelloService.java。

第二步,在res/layout/main.xml中放置四個按鈕,分別對應開啟、停止、綁定與解綁定服務。

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <linearlayout xmlns:android="https://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent">
  3. <textview android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="音樂播放服務" android:textsize="25sp" android:layout_margintop="10dp">
  4. <button android:text="開啟音樂播放服務" android:textsize="20sp" android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margintop="10dp"></button>
  5. <button android:text="停止音樂播放服務" android:textsize="20sp" android:id="@+id/Button02" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margintop="10dp"></button>
  6. <button android:text="綁定音樂播放服務" android:textsize="20sp" android:id="@+id/Button03" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margintop="10dp"></button>
  7. <button android:text="解綁定音樂播放服務" android:textsize="20sp" android:id="@+id/Button04" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margintop="10dp"></button>
  8. </textview></linearlayout>

第三步,在res目錄下新建raw目錄,把音樂文件babayetu.mp3拷貝進去。

第四步,在Activity同目錄新建MusicService.java,這是我們的核心服務類。它在各個生命周期回調裡都加入了Toast與Log輸出,方便我們觀察執行順序。

  1. package android.basic.lesson14;
  2. import android.app.Service;
  3. import android.content.Intent;
  4. import android.media.MediaPlayer;
  5. import android.os.IBinder;
  6. import android.util.Log;
  7. import android.widget.Toast;
  8. public class MusicService extends Service {
  9.     String tag ="MusicService";
  10.     MediaPlayer mPlayer;
  11.     //通過bindService綁定時回調
  12.     @Override
  13.     public IBinder onBind(Intent intent) {
  14.         Toast.makeText(this,"MusicService onBind()",Toast.LENGTH_SHORT).show();
  15.         Log.i(tag, "MusicService onBind()");
  16.         mPlayer.start();
  17.         return null;
  18.     }
  19.     //通過unbindService解綁時回調
  20.     @Override
  21.     public boolean onUnbind(Intent intent){
  22.         Toast.makeText(this, "MusicService onUnbind()", Toast.LENGTH_SHORT).show();
  23.         Log.i(tag, "MusicService onUnbind()");
  24.         mPlayer.stop();
  25.         return false;
  26.     }
  27.     //服務首次被創建時回調,無論startService還是bindService都會先走這裡
  28.     @Override
  29.     public void onCreate(){
  30.         Toast.makeText(this, "MusicService onCreate()", Toast.LENGTH_SHORT).show();
  31.         mPlayer=MediaPlayer.create(getApplicationContext(),R.raw.babayetu);
  32.         mPlayer.setLooping(true);
  33.         Log.i(tag, "MusicService onCreate()");
  34.     }
  35.     //使用startService時,onCreate之後回調
  36.     @Override
  37.     public void onStart(Intent intent,int startid){
  38.         Toast.makeText(this, "MusicService onStart", Toast.LENGTH_SHORT).show();
  39.         Log.i(tag, "MusicService onStart()");
  40.         mPlayer.start();
  41.     }
  42.     //服務被銷毀時回調
  43.     @Override
  44.     public void onDestroy(){
  45.         Toast.makeText(this, "MusicService onDestroy()", Toast.LENGTH_SHORT).show();
  46.         mPlayer.stop();
  47.         Log.i(tag, "MusicService onDestroy()");
  48.     }
  49. }

第五步,編寫MainHelloService.java。通過四個按鈕分別觸發startService、stopService、bindService、unbindService,並借助ServiceConnection監聽綁定狀態。

  1. package android.basic.lesson14;
  2. import android.app.Activity;
  3. import android.content.ComponentName;
  4. import android.content.Context;
  5. import android.content.Intent;
  6. import android.content.ServiceConnection;
  7. import android.os.Bundle;
  8. import android.os.IBinder;
  9. import android.util.Log;
  10. import android.view.View;
  11. import android.view.View.OnClickListener;
  12. import android.widget.Button;
  13. import android.widget.Toast;
  14. public class MainHelloService extends Activity {
  15.     String tag = "MusicService";
  16.     @Override
  17.     public void onCreate(Bundle savedInstanceState) {
  18.         super.onCreate(savedInstanceState);
  19.         setContentView(R.layout.main);
  20.         Toast.makeText(MainHelloService.this, "MainHelloService onCreate", Toast.LENGTH_SHORT).show();
  21.         Log.i(tag, "MainHelloService onCreate");
  22.         Button b1=(Button)findViewById(R.id.Button01);
  23.         Button b2=(Button)findViewById(R.id.Button02);
  24.         Button b3=(Button)findViewById(R.id.Button03);
  25.         Button b4=(Button)findViewById(R.id.Button04);
  26.         //服務連接對象,監聽綁定與斷開
  27.         final ServiceConnection conn = new ServiceConnection(){
  28.             @Override
  29.             public void onServiceConnected(ComponentName name, IBinder service) {
  30.                 Toast.makeText(MainHelloService.this, "ServiceConnection onServiceConnected", Toast.LENGTH_SHORT).show();
  31.                 Log.i(tag, "ServiceConnection onServiceConnected");
  32.             }
  33.             @Override
  34.             public void onServiceDisconnected(ComponentName name) {
  35.                 Toast.makeText(MainHelloService.this, "ServiceConnection onServiceDisconnected", Toast.LENGTH_SHORT).show();
  36.                 Log.i(tag, "ServiceConnection onServiceDisconnected");
  37.             }
  38.         };
  39.         OnClickListener ocl=new OnClickListener(){
  40.             @Override
  41.             public void onClick(View v) {
  42.                 Intent intent = new Intent(MainHelloService.this,android.basic.lesson14.MusicService.class);
  43.                 switch(v.getId()){
  44.                     case R.id.Button01: startService(intent); break;
  45.                     case R.id.Button02: stopService(intent); break;
  46.                     case R.id.Button03: bindService(intent,conn,Context.BIND_AUTO_CREATE); break;
  47.                     case R.id.Button04: unbindService(conn); break;
  48.                 }
  49.             }
  50.         };
  51.         b1.setOnClickListener(ocl);
  52.         b2.setOnClickListener(ocl);
  53.         b3.setOnClickListener(ocl);
  54.         b4.setOnClickListener(ocl);
  55.     }
  56.     @Override
  57.     public void onDestroy(){
  58.         super.onDestroy();
  59.         Toast.makeText(MainHelloService.this, "MainHelloService onDestroy", Toast.LENGTH_SHORT).show();
  60.         Log.i(tag, "MainHelloService onDestroy");
  61.     }
  62. }

一路跟着做下來,加上對Service概念與生命周期的理解,相信你一定已經能熟練使用Service了。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved