上一節我們聊了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中放置四個按鈕,分別對應開啟、停止、綁定與解綁定服務。
- <?xml version="1.0" encoding="utf-8"?>
- <linearlayout xmlns:android="https://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent">
- <textview android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="音樂播放服務" android:textsize="25sp" android:layout_margintop="10dp">
- <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>
- <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>
- <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>
- <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>
- </textview></linearlayout>
第三步,在res目錄下新建raw目錄,把音樂文件babayetu.mp3拷貝進去。
第四步,在Activity同目錄新建MusicService.java,這是我們的核心服務類。它在各個生命周期回調裡都加入了Toast與Log輸出,方便我們觀察執行順序。
- package android.basic.lesson14;
- import android.app.Service;
- import android.content.Intent;
- import android.media.MediaPlayer;
- import android.os.IBinder;
- import android.util.Log;
- import android.widget.Toast;
- public class MusicService extends Service {
- String tag ="MusicService";
- MediaPlayer mPlayer;
- //通過bindService綁定時回調
- @Override
- public IBinder onBind(Intent intent) {
- Toast.makeText(this,"MusicService onBind()",Toast.LENGTH_SHORT).show();
- Log.i(tag, "MusicService onBind()");
- mPlayer.start();
- return null;
- }
- //通過unbindService解綁時回調
- @Override
- public boolean onUnbind(Intent intent){
- Toast.makeText(this, "MusicService onUnbind()", Toast.LENGTH_SHORT).show();
- Log.i(tag, "MusicService onUnbind()");
- mPlayer.stop();
- return false;
- }
- //服務首次被創建時回調,無論startService還是bindService都會先走這裡
- @Override
- public void onCreate(){
- Toast.makeText(this, "MusicService onCreate()", Toast.LENGTH_SHORT).show();
- mPlayer=MediaPlayer.create(getApplicationContext(),R.raw.babayetu);
- mPlayer.setLooping(true);
- Log.i(tag, "MusicService onCreate()");
- }
- //使用startService時,onCreate之後回調
- @Override
- public void onStart(Intent intent,int startid){
- Toast.makeText(this, "MusicService onStart", Toast.LENGTH_SHORT).show();
- Log.i(tag, "MusicService onStart()");
- mPlayer.start();
- }
- //服務被銷毀時回調
- @Override
- public void onDestroy(){
- Toast.makeText(this, "MusicService onDestroy()", Toast.LENGTH_SHORT).show();
- mPlayer.stop();
- Log.i(tag, "MusicService onDestroy()");
- }
- }
第五步,編寫MainHelloService.java。通過四個按鈕分別觸發startService、stopService、bindService、unbindService,並借助ServiceConnection監聽綁定狀態。
- package android.basic.lesson14;
- 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.util.Log;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.Toast;
- public class MainHelloService extends Activity {
- String tag = "MusicService";
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- Toast.makeText(MainHelloService.this, "MainHelloService onCreate", Toast.LENGTH_SHORT).show();
- Log.i(tag, "MainHelloService onCreate");
- Button b1=(Button)findViewById(R.id.Button01);
- Button b2=(Button)findViewById(R.id.Button02);
- Button b3=(Button)findViewById(R.id.Button03);
- Button b4=(Button)findViewById(R.id.Button04);
- //服務連接對象,監聽綁定與斷開
- final ServiceConnection conn = new ServiceConnection(){
- @Override
- public void onServiceConnected(ComponentName name, IBinder service) {
- Toast.makeText(MainHelloService.this, "ServiceConnection onServiceConnected", Toast.LENGTH_SHORT).show();
- Log.i(tag, "ServiceConnection onServiceConnected");
- }
- @Override
- public void onServiceDisconnected(ComponentName name) {
- Toast.makeText(MainHelloService.this, "ServiceConnection onServiceDisconnected", Toast.LENGTH_SHORT).show();
- Log.i(tag, "ServiceConnection onServiceDisconnected");
- }
- };
- OnClickListener ocl=new OnClickListener(){
- @Override
- public void onClick(View v) {
- Intent intent = new Intent(MainHelloService.this,android.basic.lesson14.MusicService.class);
- switch(v.getId()){
- case R.id.Button01: startService(intent); break;
- case R.id.Button02: stopService(intent); break;
- case R.id.Button03: bindService(intent,conn,Context.BIND_AUTO_CREATE); break;
- case R.id.Button04: unbindService(conn); break;
- }
- }
- };
- b1.setOnClickListener(ocl);
- b2.setOnClickListener(ocl);
- b3.setOnClickListener(ocl);
- b4.setOnClickListener(ocl);
- }
- @Override
- public void onDestroy(){
- super.onDestroy();
- Toast.makeText(MainHelloService.this, "MainHelloService onDestroy", Toast.LENGTH_SHORT).show();
- Log.i(tag, "MainHelloService onDestroy");
- }
- }
一路跟着做下來,加上對Service概念與生命周期的理解,相信你一定已經能熟練使用Service了。