編輯:關於 Android 程式設計
Service 是 Android 四大元件之一。本文結合實際寫作,說明 Service 的基本概念、生命週期,以及啟動、停止、綁定、解除綁定等常見操作。
可以把 Service 理解為一個「沒有介面的隱形 Activity」——它的級別與 Activity 相當,但用戶看不到、也無法直接互動。
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>
布局效果圖:

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 播放音樂,讓服務啟動時開始播放等。
與 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 的關鍵。
Android 聯絡人字母索引表實作:自訂 View 與定位
效果與應用場景 字母索引表常見於聯絡人、城市選擇、購物分類等列表。使用者可以透過右側字母快速跳轉,也能在滑動時看到目前字母提示。這種互動能提升長列表的操作效率,也是許多
為 Android RecyclerView 添加 FootView 與 HeadView
前言: 上一篇已經介紹過 RecyclerView 的基本用法(原文:android RecyclerView 佈局真的只是那麼簡單!),本篇則是更深入的應用。 Foo
Android 布局效能優化:從層級檢查到 Lint 建議
布局為什麼會影響效能 布局是使用者體驗的重要環節。若布局設計不良,可能造成測量、配置與繪製成本過高,尤其是在 ListView 或 RecyclerView 中重複加載大
Android 自動化構建之 Ant 多渠道打包實踐(上)
前言 Ant 是一款歷史悠久的自動化構建工具,Android 開發者可以透過它實現自動化構建,也能完成多渠道打包。關於 apk 打包的方式一般有 Ant、Python、G