編輯:關於 Android 開發
這一篇我們把 Service 這個組件徹底講透,並用它做一個能後台播放的音樂播放器,順手把 MediaPlayer、Binder 通信、Handler 更新 UI 和屬性動畫串起來。
Service 是 Android 四大組件之一,主要用於在後台執行耗時邏輯或需要長期運行的任務。必要時,即使 Activity 已經退出,Service 仍然可以繼續運行。
所謂「後台」是相對前台而言的,指的是它的運行不依賴用戶可視的 UI 界面。因此適用場景通常具備兩個特徵:不依賴可視界面(前台 Service 配合 Notification 是例外),以及需要較長時間運行。
Service 可以分為 Started Service 和 Bound Service 兩類,無論哪一種都必須在清單文件中聲明,否則系統找不到它。
<service
android:enabled=["true" | "false"]
android:exported=["true" | "false"]
android:icon="drawable resource"
android:isolatedProcess=["true" | "false"]
android:label="string resource"
android:name="string"
android:permission="string"
android:process="string" >
. . .
</service>
其中 android:name 對應 Service 類名,android:permission 聲明訪問權限,android:process 指定運行進程。
有個容易被忽略的細節:忘記聲明 Service 時,它不會像 Activity 那樣直接崩潰,只會拋出一條 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");
}
}
調用順序值得記住:第一次 startService 時依次執行 onCreate → onStartCommand;此後每次 startService 只執行 onStartCommand,因為實例已經存在;無論啟動多少次,只需一次 stopService 就能終止,觸發 onDestroy。
onStartCommand 的返回值決定了 Service 被系統回收後的行為:
START_STICKY:被 kill 後,系統在內存允許時會嘗試重建,重建後回調 onStartCommand,但 Intent 為 null。
START_NOT_STICKY:被 kill 後不會重建,除非客戶端再次顯式啟動。
START_REDELIVER_INTENT:與 START_STICKY 類似,但重建時傳入的 Intent 是上一次啟動時的那個,適合不能丟失任務的場景。
此外要註意:Service 實例在同類型的範圍內永遠只有一個,與客戶端是不是同一個組件、是不是同一個進程無關。啟動之後,它的生命週期就與客戶端完全脫鉤,只有 stopService、stopSelf 或者系統回收才能結束。也正因如此,任何一個客戶端都可以調用 stopService 把它停掉,而且即使 Service 當前並未啟動也不會報錯。
Bound Service 的核心特徵是生命週期依附於客戶端,同時可以通過 Binder 對象方便地雙向通信。使用步驟如下:
1. 自定義 Service 繼承 Service 基類,重寫 onBind 返回具體的 Binder 對象;
2. 客戶端實現 ServiceConnection 接口,調用 bindService(intent, sc, flags) 綁定;
3. 在 onServiceConnected 中拿到 Binder 實例;
4. 通過 Binder 調用 Service 的公共方法完成通信;
5. 在合適的生命週期(如 onDestroy)調用 unbindService(sc) 解綁。
最常見的實現方式是繼承 Binder 類:
public class MyBindService extends Service {
private MyBinder mBinder = new MyBinder();
public class MyBinder extends Binder {
MyBindService getService() {
return MyBindService.this;
}
}
@Override
public void onCreate() {
super.onCreate();
Log.w(TAG, "in onCreate");
}
@Override
public IBinder onBind(Intent intent) {
Log.w(TAG, "in onBind");
return mBinder;
}
@Override
public boolean onUnbind(Intent intent) {
Log.w(TAG, "in onUnbind");
return super.onUnbind(intent);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.w(TAG, "in onDestroy");
}
}
客戶端:
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;
}
}
// 綁定
bindService(new Intent(BActivity.this, MyBindService.class),
sc, Context.BIND_AUTO_CREATE);
// 解綁
private void excuteUnbindService() {
if (mBound) {
unbindService(sc);
mBound = false;
}
}
回調順序上,首次綁定依次觸發 onCreate → onBind → onServiceConnected;重複綁定不會有任何回調;解綁時依次觸發 onUnbind → onDestroy。
這種方式的局限是客戶端與 Service 必須處於同一進程,否則會出現 BinderProxy cannot be cast to xxx 的錯誤。跨進程通信需要改用 AIDL 或 Messenger。
另外要記住一條規則:BroadcastReceiver 不能作為 Bound Service 的客戶端。它的生命週期太短,onReceive 執行完就結束了,而 Bound Service 依賴客戶端存在。有類似需求時應改用 startService。
Service 運行在主線程。如果它與客戶端同進程,那就是 UI 線程。因此 Service 裡做長期操作必須自己開子線程,否則 ANR 無法避免。這是很多人對 Service 最大的誤解——它並不是「自動在後台線程跑」。
Service 不會自己停止。所有寫操作都必須顯式終止,否則 Started Service 會一直運行,Bound Service 會拖累客戶端的生命週期。
IntentService 是系統封裝好的一個特殊子類,解決了「Service 裡要自己開線程」的麻煩:
默認實現了 onBind 返回 null,並提供抽象方法 onHandleIntent 供子類實現;onHandleIntent 運行在獨立的工作線程中,無需自己創建;任務執行完畢後 Service 會自動停止;多個任務按隊列順序依次處理,不是並發。
public class MyIntentService extends IntentService {
public static final String TAG = "MyIntentService";
public MyIntentService() {
super(TAG);
}
@Override
protected void onHandleIntent(Intent intent) {
Log.w(TAG, "in onHandleIntent");
Log.w(TAG, "thread name:" + Thread.currentThread().getName());
}
}
前面一直沒用到的 onBind 方法,正是建立兩者關聯的入口。在 Service 中定義 Binder:
public class MyService extends Service {
private MyBinder mBinder = new MyBinder();
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate() executed");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand() executed");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy() executed");
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
class MyBinder extends Binder {
public void startDownload() {
Log.d("TAG", "startDownload() executed");
// 執行具體的下載任務
}
}
}
Activity 拿到 Binder 之後,就能直接調用 startDownload() 這樣的業務方法,而不僅僅是「通知它啟動一下」。這比廣播方案精準得多。
功能要求:播放/暫停/停止/退出、後台播放、進度條顯示與拖動、播放時封面旋轉並顯示當前時間。

依次是:主界面、開始播放、暫停、停止。

核心幾個:create 創建並準備、setDataSource 指定數據源、prepare 同步準備、start 播放、pause 暫停、reset 重置、seekTo 跳轉、getDuration 獲取總時長、getCurrentPosition 獲取當前位置。
打開 Android Device Monitor,把 mp3 文件通過 File Explorer 推送到設備的存儲目錄。

使用真機調試時,拷到內置存儲會比外置 SD 卡方便一些;如果必須用外置卡,要注意路徑獲取方式的差異。內置存儲路徑可以寫作 Environment.getExternalStorageDirectory() + "/data/music.mp3"。
關鍵點是在清單文件中註冊 Service,並通過 Binder 暴露控制方法。

Activity 啟動時綁定:

退出時必須解綁:

這樣一來,點擊退出按鈕程序關閉、音樂停止;按返回鍵回到桌面,音樂則繼續播放——這正是後台播放的效果。
Handler 與 UI 同線程,用它來刷新 SeekBar 是最直接的方案。

思路是在 Handler 的 runnable 中讀取 getCurrentPosition() 更新進度條,同時用 SimpleDateFormat 把毫秒格式化為 mm:ss 顯示;再通過 postDelayed 讓自己每隔一段時間重新執行,形成循環。SeekBar 還需要設置 OnSeekBarChangeListener,在用戶拖動時調用 seekTo。
用 ObjectAnimator 實現最省事:
ObjectAnimator animator = ObjectAnimator.ofFloat(
imageView, "rotation", 0f, 360f);
animator.setDuration(10000);
animator.setRepeatCount(ObjectAnimator.INFINITE);
播放時 start(),暫停時 pause(),停止時 end()。這裡有個實戰技巧:給播放按鈕設置 tag 來記錄當前狀態,由 tag 的值決定下一次點擊該執行播放還是暫停,避免維護多個布爾變量導致的狀態錯亂。

一個容易漏掉的細節:按返回鍵後 Activity 進入後台,再回到前台時界面必須與當前播放狀態一致。所以需要重寫返回處理,在離開前保存狀態,在 onResume 中恢復按鈕文案與動畫狀態。

開發過程中遇到了 mediaPlayer error (-38,0) 的報錯。查閱資料後確認了原因:調用 reset() 之後、還沒設置數據源就調用了 getDuration(),此時這個方法是不合法的。
排查時先確認數據源是怎麼設置的:
如果用 MediaPlayer.create() 創建,方法內部已經完成 prepare,此時不能再調用 prepare(),否則報錯。
如果是用構造函數 new 出來再 setDataSource,則必須在 start() 之前顯式調用一次 prepare(),這樣才能避免 (-38, 0)。

操作系統 Windows 10;開發工具 Android Studio 2.2.1;虛擬設備 Nexus_5X;API 23。
最後小結一句:Service 本身只管「活着」,線程模型要自己想清楚,通信方式要按場景選對,停止時機更是必須顯式管理。把這三件事弄明白,Service 就不再是一個容易失控的組件。
百度地圖地址搜索與可視化定位
百度地圖地址搜索與可視化定位百度地圖可先定位目前位置,再透過 GeoCoder 將使用者輸入的城市與街道轉換為座標。畫面可由上方輸入列與下方 MapView 組成。Jav
把語音搜尋接進 Google Now:讓「OK Google」直接呼叫你的 App
把語音搜尋接進 Google Now:讓「OK Google」直接呼叫你的 App 原文標題:Use Voice Search to integrate with Goo
設計精美的閱讀指讀應用「指讀」開源源碼分享
設計精美的閱讀指讀應用「指讀」開源源碼分享 今天要介紹的是一款名為「指讀」的應用。它走的是 Material Design 風格,整體設計簡約、UI 清新,相當耐看,個人
DataBinding 實戰:打造通用 Adapter 並搭配 ListView 與點擊事件
DataBinding 實戰:打造通用 Adapter 並搭配 ListView 與點擊事件 2015 年 Google IO 大會發布了 DataBinding 庫,能