編輯:關於 Android 程式設計
用 MediaPlayer 做一個本地音樂播放器並不難,難的是「播放不能停」。當用戶按了 Home 鍵,Activity 進入後台,如果播放邏輯寫在 Activity 裡,音樂就會跟著一起沉默。所以必須把播放任務搬到 Service 中,讓它脫離界面獨立存活。
本文的重點在於 Activity 與 Service 的交互方式。這裡要先澄清一個常見誤解:Activity 並不能直接調用 Service 對象裡的方法。二者運行在不同的上下文,直接引用既不安全也不可靠。正確做法是通过 bindService() 建立連接,拿到一個 IBinder,再由它間接獲取 Service 實例。

四個按鈕:快退、開啟、關閉、快進,橫向等分排列。
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="開啟後台服務播放音頻" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="50dp">
<Button
android:id="@+id/fastBackward"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="快退" />
<Button
android:id="@+id/startServiceButton"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="開啟" />
<Button
android:id="@+id/stopServiceButton"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="關閉" />
<Button
android:id="@+id/fastForward"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="快進" />
</LinearLayout>
</LinearLayout>package com.multimediademo6audioservice;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener {
private Button startServiceButton, stopServiceButton, fastBackward, fastForward;
private Intent intentService;
private SimpleAudioService simpleAudioService;
boolean flag = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
startServiceButton = (Button) findViewById(R.id.startServiceButton);
stopServiceButton = (Button) findViewById(R.id.stopServiceButton);
fastBackward = (Button) findViewById(R.id.fastBackward);
fastForward = (Button) findViewById(R.id.fastForward);
startServiceButton.setOnClickListener(this);
stopServiceButton.setOnClickListener(this);
fastBackward.setOnClickListener(this);
fastForward.setOnClickListener(this);
intentService = new Intent(this, SimpleAudioService.class);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.startServiceButton:
// 先啟動,再綁定。兩者缺一不可
startService(intentService);
bindService(intentService, serviceConnection, Context.BIND_AUTO_CREATE);
flag = true;
break;
case R.id.stopServiceButton:
if (flag) {
unbindService(serviceConnection); // 先解綁
stopService(intentService); // 再停止
flag = false;
}
break;
case R.id.fastBackward:
if (flag) {
simpleAudioService.backwardFun();
}
break;
case R.id.fastForward:
if (flag) {
simpleAudioService.forwardFun();
}
break;
default:
break;
}
}
/** 監聽綁定服務的狀態 */
private ServiceConnection serviceConnection = new ServiceConnection() {
/**
* 綁定成功後回調。sasBinder 由 Service 端創建並提交,
* 實際類型是 SimpleAudioServiceBinder。
* 通過它的 getService() 才能拿到真正的 Service 實例。
*/
@Override
public void onServiceConnected(ComponentName name, IBinder sasBinder) {
simpleAudioService = ((SimpleAudioService.SimpleAudioServiceBinder) sasBinder)
.getService();
}
@Override
public void onServiceDisconnected(ComponentName name) {
simpleAudioService = null;
}
};
}這裡有幾個坑必須交代清楚。
為什麼 startService 和 bindService 都要調?兩種啟動方式的生命週期語義不同。startService 讓服務「持續運行」,直到有人顯式 stop;bindService 只是建立訪問通道,所有綁定者都解綁後服務就會銷毀。只用 bind,Activity 一退出音樂就停;只用 start,Activity 拿不到 Service 實例也就無法控制播放。所以兩者並用。
為什麼用 flag 標誌?重複 bind 會拋 IllegalArgumentException,重複 unbind 會拋 IllegalArgumentException,重複 start/stop 雖不崩但語義混亂。用一個布爾量把狀態管住,是最省事的做法。
解綁和停止的順序。先 unbind 再 stopService,避免服務在還有綁定關係時被強制銷毀引發額外回調。
package com.multimediademo6audioservice;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
public class SimpleAudioService extends Service implements OnCompletionListener {
private String TAG = "zhongyao";
private MediaPlayer player;
/** Binder 的作用:把 Service 自己交出去 */
public class SimpleAudioServiceBinder extends Binder {
SimpleAudioService getService() {
return SimpleAudioService.this;
}
}
private final IBinder sasBinder = new SimpleAudioServiceBinder();
@Override
public IBinder onBind(Intent intent) {
return sasBinder;
}
/** startService 啟動時依次回調 onCreate 與 onStartCommand */
@Override
public void onCreate() {
super.onCreate();
Log.v(TAG, "onCreate");
player = MediaPlayer.create(this, R.raw.good);
player.setOnCompletionListener(this);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand");
if (!player.isPlaying()) {
player.start();
}
return super.onStartCommand(intent, flags, startId);
}
/** stopService 時回調,記得釋放資源 */
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy");
if (player.isPlaying()) {
player.stop();
}
player.release();
}
@Override
public void onCompletion(MediaPlayer mp) {
stopSelf();
}
/** 快退 2.5 秒 */
public void backwardFun() {
if (player.isPlaying()) {
player.seekTo(player.getCurrentPosition() - 2500);
}
}
/** 快進 2.5 秒 */
public void forwardFun() {
if (player.isPlaying()) {
player.seekTo(player.getCurrentPosition() + 2500);
}
}
}Binder 模式的精髓就一句:return SimpleAudioService.this。Service 通過 Binder 把自身引用交給客戶端,客戶端強轉回 Binder 類型再調 getService(),就獲得了可以直接調用業務方法的對象。之所以要繞這一層,是因為 Binder 機制本身就要求跨進程通信有一個代理端點,順便也把哪些方法對外暴露的控制權收攏到了 Service 手裡。
seekTo 傳入負值會拋異常,所以快退時嚴格說應該做下限保護:Math.max(0, position - 2500)。示例裡為了簡潔省略了,實際代碼不要省。
onCompletion 裡調 stopSelf() 是必要的。如果播放完不主動停止,Service 會一直掛在系統裡佔著內存。
别忘了在 AndroidManifest.xml 中注册 Service,同時加上 <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>(Android 9 起)並通過 startForeground() 配一條通知——後台播放音頻在高版本系統上是必須有前台通知的,否則會被系統直接殺掉。這是示例代碼在現代 Android 上運行時最需要補的一塊。
Android 網絡編程實戰:手把手做一個簡易新聞客戶端
前面講過的知識該綜合運用一下了——XML 的 PULL 解析、ListView 的通用適配器,再加上一個好用的圖片加載庫,就能拼出一個完整的新聞客戶端。 一、智能圖片加
Android 7.0 PackageManagerService 深度解析:APK 安裝流程
從 adb install 開始 APK 安裝可由多種入口觸發,本文以 adb install 為起點,說明 PackageManagerService 在安裝過程中的關
Android Graphics(五):drawText() 原點與基線完全解析
前言:但行好事,莫問前程,只需努力每一天。 一、從四線格說起 1、四線格與基線 小時候剛學寫字母,本子都是四線格的,字母必須按規則寫在格子裡。 Canvas 用 dr
Android 自定義 ListView 載入 JSON 與網路圖片
本篇說明如何建立自定義 ListView,從伺服器取得 JSON 資料,並在背景執行緒中下載圖片,最後把文字與圖片一起顯示在清單中。整體流程使用 AsyncTask 或背