Android 應用程式由四大核心組件構成,各司其職,透過 Intent (意圖) 進行鬆耦合通訊。每個組件擁有獨特生命週期,運行於獨立進程或共享進程中,由系統根據優先級管理記憶體。
| 組件 | 核心職責 | 生命週期關鍵方法 | 啟動方式 | 執行緒 |
|---|---|---|---|---|
| Activity | 使用者介面畫面、互動處理 | onCreate→onStart→onResume→onPause→onStop→onDestroy | startActivity(Intent) | 主執行緒 (UI Thread) |
| Service | 背景長時間任務、無 UI 作業 | onCreate→onStartCommand→onDestroy (或 onBind→onUnbind) | startService / bindService | 主執行緒 (需自行開啟背景執行緒) |
| BroadcastReceiver | 接收系統/應用廣播事件 | onReceive (單一進入點,執行限時 10s) | sendBroadcast / 系統發送 | 主執行緒 (靜態註冊在新進程) |
| ContentProvider | 跨應用資料共享、統一資料存取 | onCreate → query/insert/update/delete/batch | ContentResolver (Client 端) | Binder 執行緒池 (非主執行緒) |
// 顯式 Intent (指定目標組件)
Intent explicit = new Intent(this, TargetActivity.class);
explicit.putExtra("key", "value");
startActivity(explicit);
// 隱式 Intent (聲明動作,系統解析匹配組件)
Intent implicit = new Intent(Intent.ACTION_VIEW);
implicit.setData(Uri.parse("https://example.com"));
implicit.addCategory(Intent.CATEGORY_BROWSABLE);
if (implicit.resolveActivity(getPackageManager()) != null) {
startActivity(implicit);
}
// 標準動作常數
Intent.ACTION_VIEW // 檢視資料
Intent.ACTION_EDIT // 編輯資料
Intent.ACTION_SEND // 分享內容
Intent.ACTION_PICK // 選取資料 (回傳結果)
Intent.ACTION_MAIN // 入口點 (Launcher)
Intent.ACTION_DIAL // 撥號介面
Intent.ACTION_CALL // 直接撥打 (需權限)
onCreate()
│
▼
onStart() ◄──────────────┐
│ │
▼ │
onResume() ──────────────┤ (前台可見、可互動)
│ │
▼ │
onPause() ───────────────┤ (部分可見、失去焦點)
│ │
▼ │
onStop() ────────────────┤ (完全不可見)
│ │
▼ │
onDestroy() │
│ │
└───────────────────┘ (配置變更/finish)
// 1. Started Service (啟動型) - 無限期背景執行
public class DownloadService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String url = intent.getStringExtra("download_url");
// 必須在背景執行緒執行耗時操作
new Thread(() -> performDownload(url, startId)).start();
return START_STICKY; // 被殺後嘗試重啟
}
private void performDownload(String url, int startId) {
// 下載邏輯...
stopSelf(startId); // 完成後停止自己
}
@Nullable @Override public IBinder onBind(Intent intent) { return null; }
}
// 啟動方式
ContextCompat.startForegroundService(context, new Intent(context, DownloadService.class)
// Android 8+ 必須在 5 秒內呼叫 startForeground()
// 2. Bound Service (綁定型) - 客戶端-伺服器介面
public class MusicService extends Service {
private final IBinder binder = new MusicBinder();
private MediaPlayer player;
public class MusicBinder extends Binder {
MusicService getService() { return MusicService.this; }
}
@Nullable @Override public IBinder onBind(Intent intent) { return binder; }
public void play(String url) { /* 播放邏輯 */ }
public void pause() { /* 暫停 */ }
public void seekTo(int pos) { /* 跳轉 */ }
public LiveData getPlaybackState() { /* 狀態觀察 */ }
}
// 客戶端綁定
private ServiceConnection conn = new ServiceConnection() {
@Override public void onServiceConnected(ComponentName name, IBinder service) {
MusicService.MusicBinder binder = (MusicService.MusicBinder) service;
musicService = binder.getService();
// 現在可呼叫 musicService.play() 等方法
}
@Override public void onServiceDisconnected(ComponentName name) {
musicService = null;
}
};
bindService(new Intent(this, MusicService.class), conn, Context.BIND_AUTO_CREATE);
public class ForegroundDownloadService extends Service {
private static final int NOTIFICATION_ID = 1001;
private static final String CHANNEL_ID = "download_channel";
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
createNotificationChannel();
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("下載中...")
.setContentText("檔案: example.zip")
.setSmallIcon(R.drawable.ic_download)
.setProgress(100, 0, false)
.setOngoing(true)
.build();
startForeground(NOTIFICATION_ID, notification);
// 背景執行下載...
return START_NOT_STICKY;
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID, "下載服務", NotificationManager.IMPORTANCE_LOW);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
}
}
// 靜態註冊 (Manifest) - 適用:開機、套件變更、系統級事件
// 動態註冊 (程式碼) - 適用:UI 相關、暫時監聽、需權限控制
public class MainActivity extends AppCompatActivity {
private BroadcastReceiver networkReceiver = new BroadcastReceiver() {
@Override public void onReceive(Context context, Intent intent) {
// 處理網路變化
}
};
@Override protected void onStart() {
super.onStart();
registerReceiver(networkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
@Override protected void onStop() {
super.onStop();
unregisterReceiver(networkReceiver);
}
}
// 發送有序廣播 (優先級高者先收到,可中止傳遞)
Intent intent = new Intent("com.example.CUSTOM_EVENT");
intent.putExtra("data", "sensitive");
sendOrderedBroadcast(intent, "com.example.permission.RECEIVE_CUSTOM",
new BroadcastReceiver() {
@Override public void onReceive(Context context, Intent intent) {
// 最終接收者
String result = getResultData();
}
}, null, Activity.RESULT_OK, "initial", null);
// 接收端宣告優先級
ContentObserver 監聽資料變更// 授權臨時讀取權限給其他應用
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("content://com.example.provider/notes/123"));
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
// Provider 端在 Manifest 設定 grantUriPermissions="true"
// 或程式碼動態授權
grantUriPermission("com.other.app", uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
| 屬性 | Activity | Service | Receiver | Provider |
|---|---|---|---|---|
| 預設進程 | 主進程 (應用包名) | 主進程 | 靜態: 新進程 動態: 所在進程 | 主進程 |
| 自訂進程 | android:process=":remote" | android:process=":remote" | android:process=":remote" | android:process=":remote" |
| 多實例 | 標準/單頂/單任務/單實例 | 單實例 (預設) | 每次廣播新實例 | 單實例 |
| 跨應用啟動 | exported="true" + Intent Filter | exported="true" | exported="true" | exported="true" + authorities |
四大組件構成 Android 應用骨架。Activity 處理 UI,Service 處理背景,Receiver 處理事件,Provider 處理共享。現代開發強調關注點分離:組件僅作為系統進入點,核心邏輯下沉至 ViewModel/Repository/UseCase。正確理解生命週期、進程模型、通訊機制,是打造穩定、高效能、可維護 Android 應用的基石。