Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 音樂播放器實戰(八):播放狀態持久化與歌詞頁滑動

編輯:關於 Android 程式設計

走到第八篇,播放器的骨架其實已經搭得差不多了:本地掃歌、網絡歌單、播放服務、通知欄樣樣不缺。但每次殺掉進程再進來,用戶又得從第一首歌重新開始聽,播放模式也退回默認值,這種「失憶」的體驗顯然說不過去。這一篇就來補上兩塊拼圖——狀態存取與播放頁的橫向滑動切換。

一、本輪要交付的功能清單

退出應用時,把「當前播到第幾首」與「用戶選的播放模式(順序/隨機/單曲循環)」寫進本地;下次進入應用時再把這兩個值讀回來。同時,獨立播放界面 PlayActivity 要支持手勢滑動:主屏是專輯封面,向左滑出歌詞頁,向右滑回封面。

需要提前說明的是,本階段的歌詞頁只完成了容器與切換手勢,歌詞文本的解析與填充留到後續篇目再補。

實現效果如圖:

滑動中...

滑動後

二、狀態存取:用 SharedPreferences 開一個全局入口

Android 自帶的 SharedPreferences 是個極輕量的鍵值存儲類,非常適合放這類「應用偏好」級別的小數據。做法是自己繼承 Application,在 onCreate 裡提前把 sp 實例化好,全局都能直接取用,省得每個組件各自 new 一份。

public class DRMPlayerApp extends Application {
    // SharedPreferences 是 Android 平台上一個輕量級的存儲類,用來保存應用的常用配置
    public static SharedPreferences sp;

    @Override
    public void onCreate() {
        super.onCreate();
        // 存儲名稱為 SP_NAME,存儲模式為私有
        sp = getSharedPreferences(Contant.SP_NAME, Context.MODE_PRIVATE);
    }
}

切記:自定義 Application 之後,必須回到 AndroidManifest 把 <application android:name> 指向 DRMPlayerApp,否則 onCreate 根本不會被執行。

三、清單文件

<manifest package="com.iwanghang.drmplayer"
    xmlns:android="https://schemas.android.com/apk/res/android">

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.INTERNET"/>

    <application android:name=".DRMPlayerApp">
        <activity android:name=".SplashActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>

        <service android:name=".PlayService"
            android:enabled="true"
            android:exported="true"/>
    </application>
</manifest>

四、寫入:在 MainActivity 的 onDestroy 落盤

MainActivity 承接了 BaseActivity 的播放監聽接口,退出時由它負責把服務裡的當前狀態撈出來存好。這裡順帶提一句 UI 同步的思路:本地音樂的播放界面實際上位於 MyMusicListFragment,所以 change() 回調要先判斷當前停留在哪一頁,再轉發給對應 Fragment 去刷新按鈕與歌名。

@Override
protected void onDestroy() {
    super.onDestroy();
    DRMPlayerApp app = (DRMPlayerApp) getApplication();
    SharedPreferences.Editor editor = app.sp.edit();
    // 保存當前正在播放的歌曲位置
    editor.putInt("currentPosition", playService.getCurrentPosition());
    // 保存播放模式
    editor.putInt("play_mode", playService.getPlay_mode());
    editor.commit();
}

五、讀取:在 PlayService 的 onCreate 恢復

寫入點選在 MainActivity 的銷毀,讀取點則放在 PlayService 的創建,一進一出正好閉環。恢復時要給 getInt 準備好默認值,避免首次安裝沒有歷史數據時拿到髒值。

@Override
public void onCreate() {
    super.onCreate();
    DRMPlayerApp app = (DRMPlayerApp) getApplication();
    currentPosition = app.sp.getInt("currentPosition", 0);
    play_mode = app.sp.getInt("play_mode", PlayService.ORDER_PLAY);

    mPlayer = new MediaPlayer();
    mPlayer.setOnCompletionListener(this);
    mPlayer.setOnErrorListener(this);
    mp3Infos = MediaUtils.getMp3Infos(this);
    es.execute(updateSteatusRunnable);
}

播放模式的三個常量與切換分支長這樣,一首放完該怎麼走,全看 play_mode 的走向:

public static final int ORDER_PLAY  = 1; // 順序播放
public static final int RANDOM_PLAY = 2; // 隨機播放
public static final int SINGLE_PLAY = 3; // 單曲循環

@Override
public void onCompletion(MediaPlayer mp) {
    switch (play_mode) {
        case ORDER_PLAY:  next(); break;
        case RANDOM_PLAY: play(random.nextInt(mp3Infos.size())); break;
        case SINGLE_PLAY: play(currentPosition); break;
    }
}

另外別忘了在 onDestroy 中回收那個用來刷進度的單線程池:es.shutdown(),否則線程裡的 while 循環會一直空轉。

六、界面滑動:自研 FlingGalleryView

滑動這塊沒有直接用 ViewPager,而是拿了一個仿 Gallery 思路的自定義 ViewGroup——FlingGalleryView。它的核心套路值得記一下:

  • 橫向平鋪子 View:在 onLayout 裡把每個 child 依次向右排開,並給 child 掛一個直接返回 true 的 OnTouchListener,讓父容器能在 onInterceptTouchEvent 中截獲 move/up。
  • 方向判定:攔截時比較 X 與 Y 的位移比例,只有接近水平(斜率小於 1)才進入 TOUCH_STATE_SCROLLING,避免與縱向滾動打架。
  • 速度拋擲:用 VelocityTracker 計算 X 方向速度,超過 SNAP_VELOCITY(1000 px/s)就直接翻頁,否則按「是否越過半屏」決定落點。
  • 邊界阻尼:第一屏右拉、最後一屏左拉時,最多只能拽出屏寬的四分之一,給出一點橡皮筋手感。
  • 滾動動畫:交給 Scroller,在 computeScroll 裡持續 scrollTo 直到結束。
@Override
public void computeScroll() {
    if (mScroller.computeScrollOffset()) {
        scrollTo(mScroller.getCurrX(), 0);
        if (isEveryScreen) singleScrollToScreen();
        postInvalidate();
    }
}

private void snapToScreen(int whichScreen, boolean isJump) {
    whichScreen = Math.max(0, Math.min(whichScreen, getChildCount() - 1));
    if (getScrollX() != whichScreen * getWidth()) {
        final int delta = whichScreen * getWidth() - getScrollX();
        mScroller.startScroll(getScrollX(), 0, delta, 0, Math.abs(delta) * 2);
        mCurrentScreen = whichScreen;
        invalidate();
    }
}

坦白說,這段代碼目前是「老老實實先用起來」的狀態,裡頭的切屏事件去重(count / defaultScreen 那套判斷)還值得日後再細細啃一遍。

七、布局:一個容器裝兩頁

activity_music_play 的結構很直白:上半部放 FlingGalleryView,裡面 include 兩個 layout——album_image_layout 與 lrc_layout;下半部是進度條與播放控制按鈕區。

<com.iwanghang.drmplayer.custom.FlingGalleryView
    android:id="@+id/fgv_player_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerInParent="true">

    <include android:id="@+id/album_image_layout" layout="@layout/album_image_layout"/>
    <include android:id="@+id/lrc_layout" layout="@layout/lrc_layout"/>
</com.iwanghang.drmplayer.custom.FlingGalleryView>

封面頁 album_image_layout 由歌名、方形專輯圖、倒影圖與一行提示文字「向右滑動查看歌詞 →」組成;歌詞頁 lrc_layout 則先用一個佔位 TextView 頂著,並在底部寫上「← 向左滑動查看專輯封面」,等歌詞解析那篇再把它換成真正的滾動歌詞列表。

八、小結

這一輪的關鍵點其實只有三句話:狀態存取的分工是「Application 建倉、MainActivity 存、PlayService 取」;播放頁的滑動靠自定義 ViewGroup 手工接管觸摸分發;歌詞頁先搭殼、後填肉。把這三件事理清,播放器的用戶體驗就從「能用」邁向了「順手」。

歡迎移動開發的朋友一起交流探討。

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