編輯:關於 Android 程式設計
Service 是 Android 四大元件之一(Activity、Service、BroadcastReceiver、ContentProvider),地位與 Activity 相當,但它沒有使用者介面,只在後台運行,同時能與其他元件互動。
典型場景包括:使用者離開播放器 Activity 後仍要繼續播放音樂、監聽 SD 卡上的檔案變化、在後台記錄地理位置的改變,或者處理網路事務、執行檔案 I/O、與 ContentProvider 交互。
這裡有個常見誤解必須先澄清:Service 的「後台」不等於子執行緒。Service 跑在主執行緒上,只是沒有畫面而已。因此它一樣會有 ANR 風險,耗時操作同樣必須另開子執行緒。
反過來說,只要 UI 或後台其中一邊還在跑,這個應用對系統而言就仍處於運行狀態。
繼承 Service 時必須實作 onBind(),可以在其中處理傳入的 Intent 資料:
public class MyService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
System.out.println("MyService.onBind");
return null;
}
}
註冊寫在 AndroidManifest 中,一般只需要 name 屬性:
<service android:name=".MyService" />
註冊是四大元件中最簡單的一步,但若有特殊需求(例如需要獨立行程),仍要設定其他屬性。
Service 有兩條啟動路徑:Context.startService() 與 Context.bindService()。
首次呼叫 startService() 時,系統先呼叫 onCreate(),接著呼叫 onStartCommand()。若服務已存在,重複呼叫 startService() 不會重複建立服務,但會導致 onStartCommand() 被多次呼叫。
這種方式啟動的服務只能用 stopService() 結束。若呼叫者直接離開而沒有停止服務,Service 會一直在後台運行——注意,關掉 UI 並不等於關掉服務。
綁定後呼叫者與服務連在一起,呼叫者退出時系統會依序呼叫 onUnbind() 與 onDestroy()。若服務已綁定,重複呼叫 bindService() 不會造成重複建立或綁定。
有個容易踩的細節:綁定狀態下呼叫 stopService() 是停不掉服務的,必須先 unbindService() 才會走到銷毀流程。
bindService 的三個參數分別是:Intent 物件、ServiceConnection 物件(需實作 onServiceConnected() 與 onServiceDisconnected() 來判斷連線狀態),以及建立模式,一般傳 Service.BIND_AUTO_CREATE。
onCreate()、onStartCommand()、onBind()、onUnbind()、onDestroy()。

各方法的意義:onCreate() 代表服務第一次被建立;onStartCommand() 代表服務開始工作;onBind() 代表已綁定;onUnbind() 代表已解除綁定;onDestroy() 代表服務已停止。
若先用 startService() 啟動、再用 bindService() 綁定,回呼順序會是 onCreate() → onStartCommand() → onBind()。
普通 Service 若要跑耗時任務,得自己開執行緒並手動停止。IntentService 繼承自 Service,內部自帶工作執行緒,啟動方式與傳統 Service 相同,但任務執行完會自動停止,不必手動控制。
它可以被啟動多次,每個任務會以工作佇列的方式在 onHandleIntent() 中依序執行,一次只跑一個,而且都在單一執行緒上,不會阻塞 UI 執行緒。
好處很直接:省掉手動開執行緒的麻煩,也省掉手動停止服務的判斷。
用四個按鈕分別觸發啟動、停止、綁定、解綁,就能把整個流程看清楚。
public class MyService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
System.out.println("MyService.onBind");
return null;
}
@Override
public void onCreate() {
System.out.println("MyService.onCreate");
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
System.out.println("MyService.onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
System.out.println("MyService.onDestroy");
super.onDestroy();
}
@Override
public boolean onUnbind(Intent intent) {
System.out.println("MyService.onUnbind");
return super.onUnbind(intent);
}
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void startService(View view) {
startService(new Intent(this, MyService.class));
}
public void stopService(View view) {
stopService(new Intent(this, MyService.class));
}
public void bindService(View view) {
bindService(new Intent(this, MyService.class), conn, flags);
}
public void unBindService(View view) {
try {
unbindService(conn); // 未綁定時解除會拋異常,包一層保護
} catch (Exception e) {
System.out.println("MainActivity.unBindService" + e);
}
}
private ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) { }
@Override
public void onServiceDisconnected(ComponentName name) { }
};
// BIND_AUTO_CREATE:綁定時一併啟動 Service
private int flags = Service.BIND_AUTO_CREATE;
}
版面只需四個按鈕,分別掛上 android:onClick。

點「啟動服務」會觸發 onCreate 與 onStartCommand:

點「停止服務」只觸發 onDestroy,回到剛啟動程式的狀態:

點「綁定服務」會先啟動再綁定,兩個回呼都會跑:

服務已啟動或已綁定的情況下再點啟動,只會回呼 onStartCommand——也就是 onCreate 在一個生命週期內只會跑一次。
點「解綁服務」則觸發 onUnbind 與 onDestroy:

需求是把手機 SD 卡中的所有圖片找出來並顯示在界面上。這裡有個關鍵問題:IntentService 的工作在子執行緒,資料要怎麼送回 UI 執行緒?我用動態廣播來解決。
版面很簡單,一個 ListView:
<RelativeLayout
xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="@+id/main_lv"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
遞迴遍歷的工具類:
public class FileUtils {
/** 取得指定目錄下的所有圖片 */
public static final ArrayList<File> getAllPicture(File dir) {
ArrayList<File> files = getAllFile(dir);
ArrayList<File> imgList = new ArrayList<>();
for (File file : files) {
if (file.getName().endsWith(".png") || file.getName().endsWith(".jpg")) {
imgList.add(file);
}
}
return imgList;
}
/** 遞迴遍歷資料夾 */
public static final void getFileFromDir(File dir, List<File> fileList) {
File[] files = dir.listFiles();
if (files == null) return;
for (File file : files) {
if (file.isDirectory()) getFileFromDir(file, fileList);
fileList.add(file);
}
}
/** 取得根目錄下的所有圖片 */
public static final ArrayList<File> getAllPicture() {
return getAllPicture(Environment.getExternalStorageDirectory());
}
}
IntentService 本身:
public class MyIntentService extends IntentService {
// 必須保留無參數建構子
public MyIntentService() {
super("myService");
}
/** 在子執行緒中執行 */
@Override
protected void onHandleIntent(Intent intent) {
Log.e("TAG", "子執行緒開始工作");
ArrayList<File> list = FileUtils.getAllPicture();
// 用廣播把結果送回 UI 執行緒
Intent broadcast = new Intent("filefinish");
broadcast.putExtra("file", list);
sendBroadcast(broadcast);
}
@Override
public void onCreate() {
super.onCreate();
Log.e("TAG", "onCreate");
}
@Override
public void onDestroy() {
super.onDestroy();
Log.e("TAG", "onDestroy");
}
}
MainActivity 動態註冊廣播接收者,收到資料後刷新 Adapter 並停止服務:
public class MainActivity extends AppCompatActivity {
ListView listView;
static ArrayList<File> fileList;
static MyBaseAdapter adapter;
MyBroadcastReceiver mbcr;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mbcr = new MyBroadcastReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("filefinish");
registerReceiver(mbcr, filter);
adapter = new MyBaseAdapter(this, fileList);
listView = (ListView) findViewById(R.id.main_lv);
listView.setAdapter(adapter);
startService(new Intent(this, MyIntentService.class));
}
class MyBaseAdapter extends ListItemAdapter<File> {
MyBaseAdapter(Context context, List<File> list) {
super(context, list);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView image;
if (convertView == null) {
image = new ImageView(getBaseContext());
convertView = image;
} else {
image = (ImageView) convertView;
}
image.setImageURI(Uri.fromFile(fileList.get(position)));
image.setScaleType(ImageView.ScaleType.FIT_XY);
image.setAdjustViewBounds(true);
return image;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
stopService(new Intent(MainActivity.this, MyIntentService.class)); // 重複停止不會報錯
unregisterReceiver(mbcr);
}
class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
fileList = (ArrayList<File>) intent.getSerializableExtra("file");
adapter.notifyDataSetChanged();
stopService(new Intent(MainActivity.this, MyIntentService.class));
}
}
}
記得補上 SD 卡的讀取權限。另外,遍歷檔案其實算不上耗時操作,這裡只是示範 IntentService 的用法;實務上更常見的耗時任務是網路下載或搬移大檔案。
Activity 端放入 extra 後啟動服務:
Intent intent = new Intent(this, MyService.class);
intent.putExtra("msg", "activity 向 service 傳遞一個 hello service");
startService(intent);
Service 端在 onStartCommand() 中接收(若用 bindService() 啟動,則在 onBind() 中接收):
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("onStartCommand", intent.getStringExtra("msg"));
return super.onStartCommand(intent, flags, startId);
}
Service 端先把自己交給一個靜態變數:
private static MyService instance;
public static MyService getInstance() {
return instance;
}
@Override
public void onCreate() {
super.onCreate();
instance = this;
}
public void print(String msg) {
Log.e("service", msg);
}
Activity 端就能直接呼叫 Service 的方法:
// 必須確認 instance 不為 null,且用完手動釋放(設為 null)
if (MyService.getInstance() != null) {
MyService.getInstance().print("使用單例從 activity 中呼叫 service 的方法");
}
前提是服務已經啟動過,因為 instance 是在 onCreate() 中才賦值的。
雙方各自動態註冊接收者,互相發送。Service 端:
@Override
public void onCreate() {
super.onCreate();
IntentFilter filter = new IntentFilter("service");
registerReceiver(serviceReceiver, filter);
}
BroadcastReceiver serviceReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.e("service", "接收到了 activity 發送的廣播:" + intent.getStringExtra("msg"));
sendBroadcast(new Intent("activity").putExtra("msg", "發送給 activity 的訊息"));
}
};
Activity 端:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter filter = new IntentFilter("activity");
registerReceiver(activityReceiver, filter);
}
public void sendBroadcast(View view) {
Intent intent = new Intent("service");
intent.putExtra("msg", "activity 向廣播傳遞一個 hello broadcast");
sendBroadcast(intent);
}
BroadcastReceiver activityReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.e("activity", intent.getStringExtra("msg"));
}
};
這是最靈活但也最繞的一種。重點是:被呼叫的方法其實是 Service 內部介面的抽象方法,由 Activity 實作,但實際執行位置在 Service 進程(或行程)內。
// Service 端
public interface Callback {
void call();
void start();
}
private Callback callback;
class MyBinder extends Binder {
public MyService getService() {
return MyService.this;
}
public void setCallback(Callback callback) {
MyService.this.callback = callback;
}
}
public void startMusic() {
Toast.makeText(this, "音樂開始播放", Toast.LENGTH_SHORT).show();
callback.start(); // 回呼 Activity 中實作的邏輯
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return new MyBinder();
}
Activity 端在 onServiceConnected() 中取得 Binder、取出 Service 實例,並注入回呼實作:
private MyService myService;
public void bindService(View view) {
bindService(new Intent(this, MyService.class), conn, BIND_AUTO_CREATE);
myService.startMusic();
}
ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
MyService.MyBinder bind = (MyService.MyBinder) service;
myService = bind.getService();
bind.setCallback(new MyService.Callback() {
@Override
public void call() {
Log.e("activity", "Service 回呼 Activity");
}
@Override
public void start() {
Log.e("action", "正在播放音樂");
finish();
}
});
}
@Override
public void onServiceDisconnected(ComponentName name) { }
};
以上是 Service 各個面向的整理。它還能進一步做跨行程資料傳遞,那會牽涉到 AIDL(Android Interface Definition Language),複雜度更高,值得另外整理一篇。
百度地圖開發實戰:自定義縮放、覆蓋物與路線規劃
本文整理在專案中常見的百度地圖自定義需求,包含自定義縮放按鈕、自定義定位按鈕、文字覆蓋物、覆蓋物縮放效果、只顯示當前屏幕內覆蓋物、駕車路線規劃與最近站點搜尋。 自定義縮放
Android Studio 下 NDK 開發全流程踩坑記錄
以前做 NDK 開發都是在 Eclipse 環境下。今天試著用 Android Studio 配置了一遍,結果處處是坑,特此記錄一下。 一、開發步驟 1. 首先創建 Ma
Android 自定義控件:進度條的四種實現方式
近來我一直在鑽研自定義控件,翻閱了不少前輩分享的教程,也在 GitHub 上找了一些類似控件來學習,只是讀起來都不太易懂,於是索性寫一篇學習筆記記錄下來。 一、控件介紹
用 SwipeListView 實作類 QQ 的滑動刪除效果
QQ 的滑動刪除互動相當順手,想做出類似效果,可以借助 SwipeListView 這個開源庫。 1. 下載 com.fortysevendeg.swipelistvie