編輯:關於 Android 程式設計
Service 常被形容為「在後台運行的 Activity」,但它並不是獨立進程,也不具備界面。你只要告訴它要做什麼,它便老老實實執行;若需要與用戶互動,得靠通知欄或發送廣播由 UI 呈現。它適用於不打擾用戶的後台工作,比如下載、網絡請求、播放音樂,可以通過 Intent 啟動,也可以綁定到宿主對象(如 Activity)上使用。
每個 Service 都必須在 AndroidManifest.xml 中用 <service> 標籤聲明,可以透過 Context.startService() 或 Context.bindService() 啟動。需要特別注意:Service 運行在宿主進程的主線程上,它並不等於一個新線程。
按使用範圍:
按運行方式:

本地服務中,onStart 已被 onStartCommand 取代。Service 與 Activity 均由 Context 派生,可以透過 getApplicationContext() 獲取上下文,但兩者的回調過程並不相同。
流程:context.startService() → onCreate() → onStartCommand() → 服務運行 → context.stopService() → onDestroy()。
也就是 onCreate(僅創建時回呼一次)→ onStartCommand(可多次回呼)→ onDestroy。onStartCommand 返回一個整數標識啟動請求,可取 START_STICKY、START_STICKY_COMPATIBILITY、START_NOT_STICKY、START_REDELIVER_INTENT 等,標誌位則有 START_FLAG_REDELIVERY、START_FLAG_RETRY。
這種方式下服務不會隨綁定組件銷毀而銷毀,而是自我結束,特別適合文件下載、上傳等自主運行場景。
public class MyService extends Service {
@Override
public void onCreate() { }
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// 在這裡接收 Intent 攜帶的數據並處理
return START_STICKY;
}
@Override
public void onDestroy() { }
}
清單註冊並啟動:
<service android:name=".MyService" /> Intent intent = new Intent(getApplicationContext(), MyService.class); startService(intent);
流程:context.bindService() → onCreate() → onBind() → 服務運行 → onUnbind() → onDestroy(),簡化即 onCreate → onBind → onUnbind → onDestroy。
這種方式不會回呼 onStartCommand(),且只有在所有客戶端都解綁後服務才會停止。onBind() 返回的 IBinder 是客戶端與服務通信的橋樑,客戶端可藉此拿到 Service 實例並調用其方法。一旦宿主 Context 銷毀,服務便依序 onUnbind → onDestroy 退出。
注意:綁定服務的組件在銷毀前必須解綁,否則會造成內存洩漏。
public class LocalService extends Service {
private final IBinder mBinder = new LocalBinder();
public class LocalBinder extends Binder {
LocalService getService() {
return LocalService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public boolean onUnbind(Intent intent) {
return super.onUnbind(intent);
}
}
綁定時需要提供 ServiceConnection 與標誌位:
bindService(Intent service, ServiceConnection conn, int flags)
常用標誌位:
Context.BIND_AUTO_CREATE:收到綁定請求時若服務尚未創建則立即創建;系統內存不足需回收時,只有在駐留該服務的進程成為回收對象時服務才被銷毀。Context.BIND_DEBUG_UNBIND:通常用於調試,判斷綁定的服務是否正確,但容易引起內存洩漏,非調試場景不建議使用。Context.BIND_NOT_FOREGROUND:阻止駐留該服務的進程獲得前台優先級,僅在後台運行(Froyo 引入)。boolean mIsBound = false;
public void doBindService() {
bindService(new Intent(MainActivity.this, LocalService.class),
mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
}
public void doUnbindService() {
if (mIsBound) {
unbindService(mConnection);
mIsBound = false;
}
}
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mBoundService = ((LocalService.LocalBinder) service).getService();
Toast.makeText(MainActivity.this, "服務連接", Toast.LENGTH_SHORT).show();
}
@Override
public void onServiceDisconnected(ComponentName name) {
mBoundService = null;
Toast.makeText(MainActivity.this, "服務未連接", Toast.LENGTH_SHORT).show();
}
};
流程與 bindService 一致,只是在綁定基礎上改用 AIDL 描述接口,實現真正的跨進程調用。前提條件是客戶端必須持有與服務端完全一致的 AIDL 文件,且服務端已在目標設備上安裝運行過一次。
服務端步驟:新建工程 AidlServer,在 Activity 所在包下建立 AIDL 文件(ADT 會自動在 gen 目錄生成同名 Java 文件),再實現 Service。

// IAidlService.aidl
package com.example.aidlserver;
interface IAidlService {
String getValue();
}
public class AidlService extends Service {
private class MyBinder extends IAidlService.Stub {
@Override
public String getValue() throws RemoteException {
return "test remote service";
}
}
@Override
public IBinder onBind(Intent intent) {
Log.i("AidlService", "service on bind");
return new MyBinder();
}
}
清單中需指定進程與完整的 AIDL 動作名:
<service
android:name=".AidlService"
android:enabled="true"
android:process=":remote">
<intent-filter>
<action android:name="com.example.aidlserver.IAidlService" />
</intent-filter>
</service>
客戶端步驟:新建工程 AidlClient,把服務端的 AIDL 生成的接口文件複製進來,然後綁定調用。

public class MainActivity extends Activity {
private TextView show;
private IAidlService iservice;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
show = (TextView) findViewById(R.id.show);
}
/** 第一次點擊只是完成綁定,此時 iservice 仍為空,需點第二次才能取到值 */
public void onGetAidlServerDataBtnClick(View v) {
Intent service = new Intent(IAidlService.class.getName());
bindService(service, connection, BIND_AUTO_CREATE);
if (iservice != null) {
try {
show.setText(iservice.getValue());
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
private ServiceConnection connection = new ServiceConnection() {
public void onServiceConnected(ComponentName name, IBinder service) {
iservice = IAidlService.Stub.asInterface(service);
}
public void onServiceDisconnected(ComponentName name) {
iservice = null;
}
};
}
若同時用廣播做雙向交互,記得在服務退出時調用 unregisterReceiver() 反註冊接收器。
查詢後台服務是否在運行,可以借助 ActivityManager.getRunningServices:
private boolean isServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (com.example.MyService.class.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
為什麼不直接用 Thread 代替 Service?關鍵差異有兩點:
Thread 的問題在於它獨立於 Activity:Activity finish 之後,若沒有主動停止,線程仍在跑,而你也不再持有它的引用;不同 Activity 之間無法共享控制同一個 Thread。设想一個需要週期性與服務器同步的任務,你在新啟動的 Activity 裡根本拿不到之前那個 Thread 的句柄。
而 Service 更像一種「消息服務」:任何持有 Context 的地方都能用 startService、stopService、bindService、unbindService 控制它,也可以在 Service 內註冊 BroadcastReceiver,從各處發廣播來驅動它——這些都是裸 Thread 做不到的。系統保證同一 Service 只有一個實例,這正是它適合承載長任務的原因。
Qt on Android 實踐:通過 JNI 調用系統原生分享菜單
原文《Sharing with Qt on Android》發表於 2014 年 12 月 12 日。當時我寫的遊戲 GiraffPanic(一款用 Qt & Q
淺談 Android 透過 ADB Wireless 無線除錯應用
用數據線除錯應用總是不太方便,本篇就來介紹如何使用 ADB Wireless 工具,在手機與電腦處於同一網路的情況下,實現無線除錯應用。 ADB Wireless 能讓手
Android Service 完全解析:從啟動模式到 AIDL 跨進程通訊
一、先認清 Service 的真面目 很多初學者會把 Service 和 Thread 混為一談,這是個常見誤解。Service 與 Activity 一樣,預設都跑在應
使用 Android Studio 建立第一個 Hello World App
建立第一個 Android 專案 幾乎所有程式語言的第一個範例都是 Hello World,Android 也不例外。使用 Android Studio 建立新專案後,輸