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

Android 入門:Service 元件用法詳解

編輯:關於 Android 程式設計

Service 是 Android 四大元件之一。本文結合實際寫作,說明 Service 的基本概念、生命週期,以及啟動、停止、綁定、解除綁定等常見操作。

可以把 Service 理解為一個「沒有介面的隱形 Activity」——它的級別與 Activity 相當,但用戶看不到、也無法直接互動。

Service 的生命週期方法

onBind(...) 是必須實作的方法,回傳一個綁定介面給 Service
onCreate():Service 第一次被建立時由系統呼叫
onStart(...):透過 startService() 啟動 Service 時被呼叫
onDestroy():Service 不再使用時由系統呼叫

版面配置

先用四顆按鈕做測試介面:

 <?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="Service測試" android:gravity="center_horizontal" /> <Button android:id="@+id/startButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Start Service" /> <Button android:id="@+id/stopButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Stop Service" /> <Button android:id="@+id/bindButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Bind Service" /> <Button android:id="@+id/unBindButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Unbind Service" /> </LinearLayout> 

布局效果圖:

MyService:繼承 Service

 public class MyService extends Service { final static String TAG = "MyService"; @Override public IBinder onBind(Intent intent) { Log.i(TAG,"OnBind()......"); showInfo("Onbind()......"); return null; } // Setvice創建時被調用 @Override public void onCreate() { Log.i(TAG,"onCreate()......"); showInfo("onCreate()......"); super.onCreate(); } //當客戶調用startService()啟動Service時被調用 @Override public void onStart(Intent intent, int startId) { Log.i(TAG,"onStart()........"); showInfo("onStart()........"); super.onStart(intent, startId); } @Override public void onDestroy() { Log.i(TAG,"onDestroy()........"); showInfo("onDestroy()........"); super.onDestroy(); } @Override public boolean onUnbind(Intent intent) { Log.i(TAG,"onUnbind()........"); showInfo("onUnbind()........"); return super.onUnbind(intent); } public void showInfo(String str) { Toast.makeText(this, str, Toast.LENGTH_SHORT).show(); } } 

上面主要是 Service 的幾個週期函數。實際應用時,可以在 onStart(...) 中建立 MediaPlayer 播放音樂,讓服務啟動時開始播放等。

在 Manifest 註冊 Service

與 Activity 一樣,Service 也必須在 Manifest 中註冊:

 <!-- 增加的Service --> <service android:name=".MyService"> <intent-filter > <action android:name="com.study.android.action.MY_SERVICE"/> </intent-filter> </service> 

啟動、停止與綁定

 package com.study.android; import android.app.Activity; import android.app.Service; import android.content.ComponentName; 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 MainActivity extends Activity { final static String ACTION = "com.study.android.action.MY_SERVICE"; private Button startButton,stopButton; private Button bindButton,unbindButton; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); startButton = (Button)findViewById(R.id.startButton); stopButton = (Button)findViewById(R.id.stopButton); bindButton = (Button)findViewById(R.id.bindButton); unbindButton = (Button)findViewById(R.id.unBindButton); // 開啟服務 startButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // 啟動服務 startService(buildIntent()); } }); //startButton按下後 周期函數執行順序 onCreate()----->onStart() /******************************************/ // 停止服務 stopButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { stopService(buildIntent()); } }); //stopButton按下後 周期函數執行順序 onDestroy() /******************************************/ // 綁定服務 bindButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { bindService(buildIntent(),conn,Service.BIND_AUTO_CREATE); /*第三個參數:如何創建service 一般是制定綁定時自動創建*/ } }); // bindButton 被按下後(當前服務已經stop掉)周期函數執行順序 onCreate()------->onBind() /******************************************/ // 接觸綁定Service unbindButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { unbindService(conn); } }); //unbindButton按下後 周期函數執行順序onUnbind()------->onDestroy() } // 連接對象 private ServiceConnection conn = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { Log.i("SERVICE","連接服務成功!"); showInfo("連接服務成功!"); } @Override public void onServiceDisconnected(ComponentName name) { Log.i("SERVICE","服務連接斷開!"); showInfo("服務連接斷開!"); } }; public Intent buildIntent() { Intent intent = new Intent(); // 設置Intent屬性 注意:這裡action屬性要與Manifest裡服務對應 intent.setAction(ACTION); return intent; } public void showInfo(String str) { Toast.makeText(this, str, Toast.LENGTH_SHORT).show(); } } 

透過上面的按鈕操作,可以清楚觀察到不同觸發方式對應的生命週期執行順序:startService 會依序觸發 onCreate→onStart;bindService 則是 onCreate→onBind;解除綁定後則走 onUnbind→onDestroy。理解這些順序,是掌握 Service 的關鍵。

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