編輯:關於 Android 程式設計
Service 常被稱為「後台服務」,這裡的「後台」是相對於前台可視界面而言——它自身的運行不依賴用戶可見的 UI。從業務角度看,適合使用 Service 的場景通常具備兩個特徵:一是需要長期運行,二是不依賴用戶可視界面(前台 Service 是個例外,它需要與通知欄配合)。
從啟動方式看,Service 分為 Started Service 與 Bound Service。無論哪種,都通過繼承 Service 基類自定義,並且必須在清單中聲明:
<service
android:enabled="true"
android:exported="false"
android:icon="drawable resource"
android:isolatedProcess="false"
android:label="string resource"
android:name="string"
android:permission="string"
android:process="string" >
. . .
</service>
其中 android:name 對應類名,android:permission 是訪問權限,android:process 指定運行進程。Service 能否獨立於一個進程,與其啟動方式有關。
易錯點:自定義 Service 若忘記聲明,不會像 Activity 那樣直接崩潰。顯式 Intent 啟動時只會打印一條 warning:IllegalArgumentException: Service not registered,不容易察覺,排查問題時容易繞彎路。
通過 context.startService(intent) 啟動,context.stopService(intent) 停止;Service 內部也可以調用 stopSelf(...) 自行停止。
public class MyService extends Service {
public static final String TAG = "MyService";
@Override
public IBinder onBind(Intent intent) {
return null; // Started Service 直接返回 null
}
@Override
public void onCreate() {
super.onCreate();
Log.w(TAG, "in onCreate");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.w(TAG, "in onStartCommand");
String name = intent.getStringExtra("name");
Log.w(TAG, "name: " + name);
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Log.w(TAG, "in onDestroy");
}
}
onBind() 是 Service 基類唯一的抽象方法,子類必須實現;但對 Started Service 而言,直接返回 null 即可。onCreate、onStartCommand、onDestroy 分別對應生命週期的三個階段。
onCreate (首次 startService)
→ onStartCommand
→ onStartCommand (可多次)
→ onDestroy (stopService)
startService 時依次執行 onCreate 與 onStartCommand;之後每次調用只執行 onStartCommand,因為 Service 已創建。參數 flags 默認為 0(START_STICKY_COMPATIBILITY),startId 是本次請求的唯一標識,多次啟動時遞增。返回值決定 Service 被系統回收後的行為:
極易誤解的一點:以上行為僅在「系統因內存不足而回收」時生效。如果是用戶主動 kill 進程,那麼無論返回值設為什麼,Service 都不會重啟。
廠商定制差異:部分定制系統(如 MIUI)有「自啟動管理」列表,默認只允許少數應用自啟動。用戶手動加入白名單後,若 onStartCommand 返回 START_STICKY 或 START_REDELIVER_INTENT,結束 App 後 Service 仍可按上述規則重啟;但在「設置 → 應用 → 強制停止」中結束的,不會重啟。
需要獨立進程時,在清單中通過 android:process 指定進程名,並在需要對外開放時把 android:exported 設為 true(有 intent-filter 時默認即為 true):
<service
android:name=".MyService"
android:exported="true"
android:process=":MyCorn" />
參數傳遞:啟動時可通過 Intent 直接帶參數;Service 執行中若需回傳數據給客戶端,通常借助發送廣播(客戶端需註冊廣播接收器)。同進程時推薦顯式 Intent,跨應用時只能使用隱式 Intent。
Bound Service 的核心特徵是:生命週期依附於客戶端。所有客戶端都解綁後,Service 銷毀。它通過 Binder 對象提供便捷的雙向通信能力。
onBind() 返回具體的 Binder 對象。ServiceConnection 接口,調用 bindService(intent, sc, flags) 綁定。onServiceConnected(name, binder) 中拿到 Binder 實例。unbindService(sc) 解綁。最常見也最簡單的一種。
局限:客戶端與 Service 必須處於同一進程,無法跨進程通信,否則會出現 android.os.BinderProxy cannot be cast to xxx 錯誤。
public class MyBindService extends Service {
private MyBinder mBinder = new MyBinder();
public class MyBinder extends Binder {
MyBindService getService() {
return MyBindService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public boolean onUnbind(Intent intent) {
return super.onUnbind(intent);
}
}
public class BActivity extends Activity {
private ServiceConnection sc = new MyServiceConnection();
private MyBinder mBinder;
private MyBindService mBindService;
private boolean mBound;
private class MyServiceConnection implements ServiceConnection {
@Override
public void onServiceConnected(ComponentName name, IBinder binder) {
mBinder = (MyBinder) binder;
mBindService = mBinder.getService();
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName name) {
mBound = false; // 進程意外崩潰時調用
}
}
private void bind() {
bindService(new Intent(this, MyBindService.class),
sc, Context.BIND_AUTO_CREATE);
}
private void unbind() {
if (mBound) {
unbindService(sc);
mBound = false;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unbind();
}
}
首次綁定的回調順序:onCreate → onBind → onServiceConnected。再次綁定不會有任何回調。解綁時:onUnbind → onDestroy。
注意:BroadcastReceiver 不能作為 Bound Service 的客戶端,因為它的生命週期太短,onReceive 執行完即結束。有此需求時應改用 startService。
Messenger 可以理解為「信使」。通過它返回 Binder,不必關心客戶端與 Service 是否同進程,並且能實現雙向通信。
局限:不支持嚴格意義的多線程並發,實際以隊列串行處理。
public class MyMessengerService extends Service {
public static final int MSG_FROM_CLIENT_TO_SERVER = 1;
public static final int MSG_FROM_SERVER_TO_CLIENT = 2;
private Messenger mClientMessenger;
private Messenger mServerMessenger = new Messenger(new ServerHandler());
@Override
public IBinder onBind(Intent intent) {
return mServerMessenger.getBinder();
}
class ServerHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_FROM_CLIENT_TO_SERVER:
mClientMessenger = msg.replyTo; // 取出客戶端信使
Message toClient = Message.obtain(
null, MSG_FROM_SERVER_TO_CLIENT);
try {
mClientMessenger.send(toClient);
} catch (RemoteException e) {
e.printStackTrace();
}
break;
default:
super.handleMessage(msg);
}
}
}
}
public class CActivity extends Activity {
private ServiceConnection sc = new MyServiceConnection();
private boolean mBound;
private Messenger mServerMessenger;
private Messenger mClientMessenger =
new Messenger(new MyClientHandler());
private class MyClientHandler extends Handler {
@Override
public void handleMessage(Message msg) {
if (msg.what == MyMessengerService.MSG_FROM_SERVER_TO_CLIENT) {
Log.w(TAG, "receive msg from server");
}
}
}
private class MyServiceConnection implements ServiceConnection {
@Override
public void onServiceConnected(ComponentName name, IBinder binder) {
mServerMessenger = new Messenger(binder);
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName name) {
mBound = false;
}
}
public void sayHello() {
if (!mBound) return;
Message msg = Message.obtain(null,
MyMessengerService.MSG_FROM_CLIENT_TO_SERVER, 0, 0);
msg.replyTo = mClientMessenger; // 把自己的信使帶過去
try {
mServerMessenger.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
關鍵環節:Service 端通過 new Messenger(new ServerHandler()) 創建信使並在 onBind 中返回其 Binder;客戶端在 onServiceConnected 中用 new Messenger(binder) 還原;發消息時通過 msg.replyTo 把自己的信使傳過去,Service 便能反向推送。雙向通信由此建立。
Messenger 通常足以勝任,AIDL 則更加靈活——真正的並發調用、支持多種數據類型。做法是自定義 .aidl 文件,構建系統會在 gen 目錄生成接口類,後續流程與 Messenger 類似。
通用注意:無論哪種 Bound Service,執行 unbind 前都必須判斷當前是否處於已綁定狀態,重複解綁會導致崩潰。這與 Started Service 形成鮮明對比——stopService 無需判斷。
IntentService 是系統提供的特殊 Service 子類,它解決了「Service 中要開線程」的痛點:
onBind() 返回 null,並定義抽象方法 onHandleIntent() 供子類實現。onHandleIntent() 運行在系統自動創建的工作線程中,無需自己開線程。
public class MyIntentService extends IntentService {
public static final String TAG = "MyIntentService";
public MyIntentService() {
super(TAG);
}
public MyIntentService(String name) {
super(name);
}
@Override
protected void onHandleIntent(Intent intent) {
Log.w(TAG, "in onHandleIntent");
Log.w(TAG, "thread name: " + Thread.currentThread().getName());
}
}
(順序處理的特性決定了它適合離線上報、下載隊列這類串行任務;並發場景應改用 JobIntentService 或 WorkManager。)
通過 startForeground(int id, Notification notification) 可以把 Service 提升為前台 Service。在 UI 上它表現為一條持續狀態的通知,同時讓 Service 擁有更高的進程優先級,降低被系統回收的概率。
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Notification notification = new Notification(
R.drawable.ic_launcher, "test", System.currentTimeMillis());
Intent notificationIntent = new Intent(this, DActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, "title", "content", pendingIntent);
startForeground(1, notification);
return START_REDELIVER_INTENT;
}
重要提醒:從 Android 8.0(API 26)開始,後台限制收緊,普通後台 Service 會很快被系統停止,長期任務必須使用前台 Service,且需要配套的 FOREGROUND_SERVICE 權限與通知渠道(NotificationChannel)。Notification.setLatestEventInfo 與 startForeground 的舊用法在高版本上均已廢棄或受限,應改用 Notification.Builder 構建通知。IntentService 也在 API 30 中被標註為 deprecated,新項目應遷移到 WorkManager。
Android 頂部+底部雙導航界面實作(FragmentTabHost + ViewPager)
一直想試試雙層導航,翻了不少資料總算跑通了,這篇就当筆記記錄下來。 底部導航:FragmentTabHost + Fragment 底部我用 FragmentTabH
Android 崩潰防護:全域 UncaughtException 捕捉與日誌落地
實專案裡,導致 App 閃退的異常多到數不完。開發階段我們可以靠 logcat 逐一 debug,但有些問題藏得很深——裝置碎片化、系統版本差異、各家 ROM 的客製行為
Android Studio 基本設定整理
Android Studio 的設定看似瑣碎,卻會直接影響日常開發手感。以下整理幾個最常被調整的項目,方便快速建立適合自己的開發環境。進入設定頁面可以從選單進入 Sett
Android AsyncTask 異步任務機制詳解:用法、注意事項與原始碼原理
AsyncTask 是 Android 早期常用的異步任務工具,封裝了 Thread 與 Handler,讓開發者能在背景執行工作,再把結果回传到主線程更新 UI。 基