Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 應用實例:結合 Service 與 ContentProvider 打造音樂播放器

編輯:Android 開發實例

這個範例想解決的兩個問題

做 Android 久了,會發現真正需要 mastering 的是四大元件加上串起它們的 Intent:Activity、Service、ContentProvider、BroadcastReceiver。Activity 大家都很熟,這個範例我們把焦點放在另外兩個——用 Service 讓音樂在背景持續播放,以及用 ContentProvider 取得裝置裡的媒體庫。

Service:讓音樂不中斷

Service 沒有 UI、不能與使用者互動,跑在背景,離開 App 後只要行程沒被結束,它就還在。音樂播放器正是它的經典場景:使用者可能一邊聽歌一邊逛網頁,若播放邏輯寫在 Activity 裡,離開 App 音樂就停了。

另一個常被忽略的用途是週期性更新:某些資料需要定期從網路抓取,用 Service 排程更新,就不必每次開 App 都重新拉一次。

ContentProvider:一個 URI 打通媒體庫

ContentProvider 讓你能透過一個 URL 跨應用取得資料(底層通常是 SQLite)。這個設計在處理媒體時特別好用——想抓 sdcard 裡所有的音訊、影片、圖片,不需要自己遞迴掃目錄,只要查詢對應的 URI 就好。

更厲害的是,Android 在開機或插入 sdcard 時,media scanner 會自動建立資料庫,把卡裡所有音訊、影片、圖片的資訊寫進對應的資料表。用 DDMS 打開 data/data 目錄,就能看到目前這張卡對應的媒體資料庫檔案(不同裝置、不同卡會有各自的庫)。把這個 .db 檔拉出來,用任何 SQLite 工具打開,就能直接看到音訊表裡的完整欄位與你手機裡的每一首歌。

這個範例原本是我拿來寫桌面 Widget 的程式碼,因為版面太繁瑣,這裡簡化成一個四顆按鈕的 Demo。

第一步:版面配置

新增專案 MusicDemo,res/layout/main.xml 放四顆按鈕:上一首、播放、下一首、暫停。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Welcome to Mr Wei's blog." />

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <Button android:id="@+id/previous"
            android:layout_height="fill_parent"
            android:layout_width="wrap_content"
            android:layout_weight="1"
            android:text="上一首" />

        <Button android:id="@+id/play"
            android:layout_height="fill_parent"
            android:layout_width="wrap_content"
            android:layout_weight="1"
            android:text="播放" />

        <Button android:id="@+id/next"
            android:layout_height="fill_parent"
            android:layout_width="wrap_content"
            android:layout_weight="1"
            android:text="下一首" />

        <Button android:id="@+id/pause"
            android:layout_height="fill_parent"
            android:layout_width="wrap_content"
            android:layout_weight="1"
            android:text="暫停" />
    </LinearLayout>
</LinearLayout>

第二步:MusicService —— 播放邏輯全在這裡

關鍵概念是:透過 MediaStore.Audio.Media.EXTERNAL_CONTENT_URI 這個 URI 查詢媒體庫,取得 Cursor,再用 MediaPlayer 依位置播放。

package com.tutor.music;

import java.io.IOException;
import android.app.Service;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.IBinder;
import android.provider.MediaStore;
import android.widget.Toast;

public class MusicService extends Service {

    String[] mCursorCols = new String[]{
            "audio._id AS _id",   // 索引必須與下面的 IDCOLIDX 對應
            MediaStore.Audio.Media.ARTIST,
            MediaStore.Audio.Media.ALBUM,
            MediaStore.Audio.Media.TITLE,
            MediaStore.Audio.Media.DATA,
            MediaStore.Audio.Media.MIME_TYPE,
            MediaStore.Audio.Media.ALBUM_ID,
            MediaStore.Audio.Media.ARTIST_ID,
            MediaStore.Audio.Media.DURATION
    };

    private MediaPlayer mMediaPlayer;
    private Cursor mCursor;
    private int mPlayPosition = 0;

    // 用四個 action 區分不同的操作指令
    public static final String PLAY_ACTION     = "com.tutor.music.PLAY_ACTION";
    public static final String PAUSE_ACTION    = "com.tutor.music.PAUSE_ACTION";
    public static final String NEXT_ACTION     = "com.tutor.music.NEXT_ACTION";
    public static final String PREVIOUS_ACTION = "com.tutor.music.PREVIOUS_ACTION";

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mMediaPlayer = new MediaPlayer();

        // 透過這個 URI 就能取得所有音訊檔
        Uri MUSIC_URL = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;

        // 過濾:我機器裡有些遊戲音效不到一秒,這裡只取 duration > 10 秒的
        mCursor = getContentResolver().query(
                MUSIC_URL, mCursorCols, "duration > 10000", null, null);
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);

        String action = intent.getAction();
        if (action.equals(PLAY_ACTION)) {
            play();
        } else if (action.equals(PAUSE_ACTION)) {
            pause();
        } else if (action.equals(NEXT_ACTION)) {
            next();
        } else if (action.equals(PREVIOUS_ACTION)) {
            previous();
        }
    }

    public void play() {
        inite();
    }

    // 暫停時直接結束服務
    public void pause() {
        stopSelf();
    }

    public void previous() {
        if (mPlayPosition == 0) {
            mPlayPosition = mCursor.getCount() - 1;
        } else {
            mPlayPosition--;
        }
        inite();
    }

    public void next() {
        if (mPlayPosition == mCursor.getCount() - 1) {
            mPlayPosition = 0;
        } else {
            mPlayPosition++;
        }
        inite();
    }

    // 依目前位置載入並播放
    public void inite() {
        mMediaPlayer.reset();
        String dataSource = getDateByPosition(mCursor, mPlayPosition);
        String info = getInfoByPosition(mCursor, mPlayPosition);
        Toast.makeText(getApplicationContext(), info, Toast.LENGTH_SHORT).show();
        try {
            mMediaPlayer.setDataSource(dataSource);
            mMediaPlayer.prepare();
            mMediaPlayer.start();
        } catch (IllegalArgumentException e1) {
            e1.printStackTrace();
        } catch (IllegalStateException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

    // 依位置取得歌曲的實際檔案路徑
    public String getDateByPosition(Cursor c, int position) {
        c.moveToPosition(position);
        int dataColumn = c.getColumnIndex(MediaStore.Audio.Media.DATA);
        return c.getString(dataColumn);
    }

    // 取得目前歌曲的歌手與歌名
    public String getInfoByPosition(Cursor c, int position) {
        c.moveToPosition(position);
        int titleColumn = c.getColumnIndex(MediaStore.Audio.Media.TITLE);
        int artistColumn = c.getColumnIndex(MediaStore.Audio.Media.ARTIST);
        return c.getString(artistColumn) + " " + c.getString(titleColumn);
    }

    // 服務結束時務必釋放 MediaPlayer
    public void onDestroy() {
        super.onDestroy();
        mMediaPlayer.release();
    }
}

幾個設計意圖值得說明。用 action 字串做指令分派,是早期 Android 常見的 Service 對外介面寫法,好處是 Activity 端不需要持有 Service 實例,只要送 Intent 即可。而 duration > 10000 這個過濾條件是很實際的經驗——媒體庫裡混著大量遊戲音效、通知音,不做篩選的話「下一首」會跳到各種奇怪的短音效上。

第三步:Activity 只負責發指令

Activity 端刻意寫得很薄,因為所有播放邏輯都應該在 Service 裡:

package com.tutor.music;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MusicDemo extends Activity implements OnClickListener {

    private Button mPrevious, mPlay, mNext, mPause;
    private ComponentName component;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        setupViews();
    }

    public void setupViews() {
        component = new ComponentName(this, MusicService.class);

        mPrevious = (Button) findViewById(R.id.previous);
        mPlay     = (Button) findViewById(R.id.play);
        mNext     = (Button) findViewById(R.id.next);
        mPause    = (Button) findViewById(R.id.pause);

        mPrevious.setOnClickListener(this);
        mPlay.setOnClickListener(this);
        mNext.setOnClickListener(this);
        mPause.setOnClickListener(this);
    }

    public void onClick(View v) {
        if (v == mPrevious) {
            sendCommand(MusicService.PREVIOUS_ACTION);
        } else if (v == mPlay) {
            sendCommand(MusicService.PLAY_ACTION);
        } else if (v == mNext) {
            sendCommand(MusicService.NEXT_ACTION);
        } else {
            sendCommand(MusicService.PAUSE_ACTION);
        }
    }

    // 把四段重複的程式碼收斂成一個方法
    private void sendCommand(String action) {
        Intent mIntent = new Intent(action);
        mIntent.setComponent(component);
        startService(mIntent);
    }
}

第四步:註冊 Service

Service 一定要在 manifest 宣告,否則啟動時會報錯:

<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.tutor.music"
    android:versionCode="1"
    android:versionName="1.0">

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".MusicDemo" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name=".MusicService" android:exported="true" />
    </application>

    <uses-sdk android:minSdkVersion="7" />
</manifest>

第五步:執行驗證

啟動後會看到四顆按鈕的首頁。按「播放」開始播放,Toast 會顯示目前歌曲的歌手與歌名;「上一首/下一首」會在清單中循環切換。到 Settings → Applications → Running services 可以確認多了一個 MusicService——這也證明了離開 App 之後音樂仍然持續。

這個 Demo 距離「正式可用」還有多遠

這個範例的價值在於把 Service 與 ContentProvider 的組合講清楚,但如果要變成真正上架的播放器,還有幾個地方必須補強:

  • READ_EXTERNAL_STORAGE 權限。 查詢媒體庫需要讀取權限,Android 6.0 以上還要在執行期動態向使用者申請。少了這步,Cursor 會是空的。
  • MediaPlayer 資源釋放。 這裡只在 onDestroy 做 release(),但正式版本還要處理錯誤重試、音訊焦點(Audio Focus)被搶走、耳機拔出等情境,否則會出現「音樂自己停了」或「跟其他 App 搶喇叭」的問題。
  • 前景服務 + 通知。 從 Android 8.0 起,App 進入背景後背景服務會被限制,音樂播放器必須改用前景服務並搭配常駐通知,才能穩定持續播放。
  • MediaSession / MediaBrowserService。 這是官方為媒體播放設計的標準架構,能一次解決通知控制、鎖定畫面、藍牙與車機控制、播放狀態同步等問題。自訂 Service 能做到,但工時與 bug 風險都遠高於用標準元件。
  • MediaStore 的 API 演進。 新版 Android 已不建議直接用 MediaStore.Audio.Media.DATA 取檔案路徑,而應改用 ContentResolver.openFileDescriptor() 搭配 MediaPlayer.setDataSource(FileDescriptor),並加上適當的 selection 過濾條件。
  • Cursor 生命週期。 這裡的 Cursor 一路存活到 Service 結束,實務上應在不需要時確實 close(),或用 MediaStore 的 query 包裝好並在 onDestroy 一併收尾。

把 Service 當背景載體、把 ContentProvider 當資料來源,這個組合不只適用於音樂,影片播放、相簿瀏覽、下載管理都是同一套骨架。理解了它,四大元件裡最抽象的那兩個就不再難懂。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved