編輯:關於 Android 程式設計
Service 是 Android 四大組件之一,應用範圍很廣。本文從最基礎的生命週期談起,並依序說明本地 Service、可通訊 Service、前台 Service 與遠端 Service 四種型態的實作方式。



這是最普遍、最常用的一種背景服務形式。
步驟一:建立子類別繼承 Service,並重新實作 onCreate()、onStartCommand()、onDestroy() 與 onBind()。
步驟二:建立用來啟動 Service 的 Intent 物件。
步驟三:呼叫 startService() 啟動服務,呼叫 stopService() 停止服務。
步驟四:在 AndroidManifest.xml 註冊 Service。
建議先下載 Demo 再閱讀(Carson.ho 的 GitHub):Demo_for_Service
MyService.java
public class MyService extends Service {
// 啟動 Service 之後,就可以在 onCreate() 或 onStartCommand() 裡執行具體邏輯
@Override
public void onCreate() {
super.onCreate();
System.out.println("執行了 onCreate()");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
System.out.println("執行了 onStartCommand()");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
System.out.println("執行了 onDestroy()");
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
在主版面配置兩個 Button,分別用於啟動與停止 Service:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="scut.carson_ho.demo_service.MainActivity">
<Button
android:id="@+id/startService"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="啟動服務" />
<Button
android:id="@+id/stopService"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/startService"
android:layout_centerInParent="true"
android:text="停止服務" />
</RelativeLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button startService;
private Button stopService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService = (Button) findViewById(R.id.startService);
stopService = (Button) findViewById(R.id.stopService);
startService.setOnClickListener(this);
stopService.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.startService:
Intent startIntent = new Intent(this, MyService.class);
startService(startIntent);
break;
case R.id.stopService:
Intent stopIntent = new Intent(this, MyService.class);
stopService(stopIntent);
break;
}
}
}
AndroidManifest.xml
<manifest package="scut.carson_ho.demo_service"
xmlns:android="https://schemas.android.com/apk/res/android">
<application>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- 註冊 Service -->
<service android:name=".MyService" />
</application>
</manifest>
AndroidManifest 中 Service 常見屬性說明
android:name:Service 的類別名稱。
android:label:Service 顯示名稱,不設定則預設為類別名。
android:icon:Service 的圖示。
android:permission:宣告此 Service 的權限,只有具備該權限的 App 才能控制或連線此服務。
android:process:表示該服務是否在另一個行程中執行(遠端服務)。不設定則預設為本地服務。
android:enabled:預設為 true,表示系統會啟動此 Service。
android:exported:該服務是否能被其他 App 控制或連線,不設定則預設為 false。
測試結果:

Demo 位置:Carson.ho 的 GitHub:Demo_for_Service
前面介紹的是最基礎的形式,但只能單向使用,無法與 Activity 雙向溝通。接下來在原本基礎上加上「與 Activity 通訊」的能力,做法是綁定 Service,用到 Binder 類別、bindService()、onBind()、unbindService() 與 onUnbind()。
建議先下載 Demo 再閱讀:Carson.ho 的 GitHub Demo_for_Service
MyService.java
public class MyService extends Service {
private MyBinder mBinder = new MyBinder();
@Override
public void onCreate() {
super.onCreate();
System.out.println("執行了 onCreate()");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
System.out.println("執行了 onStartCommand()");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
System.out.println("執行了 onDestroy()");
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
System.out.println("執行了 onBind()");
// 回傳實例
return mBinder;
}
@Override
public boolean onUnbind(Intent intent) {
System.out.println("執行了 onUnbind()");
return super.onUnbind(intent);
}
// 建立繼承自 Binder 的內部類別
class MyBinder extends Binder {
public void service_connect_Activity() {
System.out.println("Service 關聯了 Activity,並在 Activity 執行了 Service 的方法");
}
}
}
版面配置再加上「綁定服務」與「解綁服務」兩個按鈕:
<Button
android:id="@+id/bindService"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/stopService"
android:layout_centerInParent="true"
android:text="綁定服務" />
<Button
android:id="@+id/unbindService"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/bindService"
android:layout_centerInParent="true"
android:text="解綁服務" />
在 Activity 中透過呼叫 MyBinder 的 public 方法,就能實現 Activity 指揮 Service 做事的效果。
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button startService;
private Button stopService;
private Button bindService;
private Button unbindService;
private MyService.MyBinder myBinder;
// 建立 ServiceConnection 匿名類別
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) { }
// Activity 與 Service 建立關聯時呼叫
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// 向下轉型取得 MyBinder 實例
myBinder = (MyService.MyBinder) service;
// 在 Activity 中呼叫 Service 的方法
myBinder.service_connect_Activity();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService = (Button) findViewById(R.id.startService);
stopService = (Button) findViewById(R.id.stopService);
bindService = (Button) findViewById(R.id.bindService);
unbindService = (Button) findViewById(R.id.unbindService);
startService.setOnClickListener(this);
stopService.setOnClickListener(this);
bindService.setOnClickListener(this);
unbindService.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.startService:
startService(new Intent(this, MyService.class));
break;
case R.id.stopService:
stopService(new Intent(this, MyService.class));
break;
case R.id.bindService:
Intent bindIntent = new Intent(this, MyService.class);
// 參數一:Intent 物件
// 參數二:ServiceConnection 實例
// 參數三:標誌位,BIND_AUTO_CREATE 表示建立關聯後自動建立 Service
// 此時 onCreate() 會執行,但 onStartCommand() 不會執行
bindService(bindIntent, connection, BIND_AUTO_CREATE);
break;
case R.id.unbindService:
unbindService(connection);
break;
default:
break;
}
}
}
Demo:Carson.ho 的 GitHub Demo_for_Service
前台 Service 與後台 Service(一般形式)最大的差別在於:前台 Service 會在下拉通知欄顯示通知,後台 Service 不會。

用法很簡單,只需稍微修改原本的 onCreate() 方法即可:
@Override
public void onCreate() {
super.onCreate();
System.out.println("執行了 onCreate()");
// 建立「點擊通知後開啟 MainActivity」的 Intent 物件
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
// 建立 Notification Builder 物件
Notification.Builder builer = new Notification.Builder(this);
builer.setContentTitle("前台服務通知的標題");
builer.setContentText("前台服務通知的內容");
builer.setSmallIcon(R.mipmap.ic_launcher);
builer.setContentIntent(pendingIntent);
Notification notification = builer.getNotification();
// 讓 Service 變成前台 Service,並在系統狀態欄顯示出來
startForeground(1, notification);
}
測試結果:執行後點擊「啟動服務」或「綁定服務」,Service 就會以前台模式啟動,通知欄上會出現通知。

具體實作請參考另一篇文章:Android:遠端服務 Service(含 AIDL & IPC 講解)。
搞懂了各型別的用法之後,接下來的問題是:什麼時候該用哪一種?各類 Service 的適用場景可參考下圖。

React Native 實戰:手把手打造自定義頂部導航欄
經過前幾篇的學習積累,我們已經具備了實現一個自定義導航欄的能力,最終效果如下: 整體思路是:創建一個 NaviBar.js 用於渲染頂部導航欄,再準備四個頁面(Page
Android 效能優化:如何避免 ANR 並保持介面流暢
ANR 是什麼 ANR 是 Application Not Responding 的縮寫。當應用無法在時限內回應輸入或廣播時,系統會顯示對話框,讓使用者選擇等待或關閉。
美團 Android DEX 自動拆包與動態加載實踐全解析
問題的起點 對 Android 開發者而言,隨著業務規模不斷擴張,新功能與新類庫層出不窮,程式碼急遽膨脹,APK 體積也水漲船高。終有一天,你會迎面撞上這類錯誤: 打包
Android Studio 使用小結:環境、版本控制、jar 與第三方庫的引用
一、搭建環境 安裝 Android Studio 並配置好 SDK。官方教學寫得相當完整(https://developer.android.com/sdk/instal