編輯:關於 Android 程式設計
走到第八篇,播放器的骨架其實已經搭得差不多了:本地掃歌、網絡歌單、播放服務、通知欄樣樣不缺。但每次殺掉進程再進來,用戶又得從第一首歌重新開始聽,播放模式也退回默認值,這種「失憶」的體驗顯然說不過去。這一篇就來補上兩塊拼圖——狀態存取與播放頁的橫向滑動切換。
退出應用時,把「當前播到第幾首」與「用戶選的播放模式(順序/隨機/單曲循環)」寫進本地;下次進入應用時再把這兩個值讀回來。同時,獨立播放界面 PlayActivity 要支持手勢滑動:主屏是專輯封面,向左滑出歌詞頁,向右滑回封面。
需要提前說明的是,本階段的歌詞頁只完成了容器與切換手勢,歌詞文本的解析與填充留到後續篇目再補。
實現效果如圖:

滑動中...

滑動後

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 承接了 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();
}
寫入點選在 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 循環會一直空轉。
滑動這塊沒有直接用 ViewPager,而是拿了一個仿 Gallery 思路的自定義 ViewGroup——FlingGalleryView。它的核心套路值得記一下:
onLayout 裡把每個 child 依次向右排開,並給 child 掛一個直接返回 true 的 OnTouchListener,讓父容器能在 onInterceptTouchEvent 中截獲 move/up。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 手工接管觸摸分發;歌詞頁先搭殼、後填肉。把這三件事理清,播放器的用戶體驗就從「能用」邁向了「順手」。
歡迎移動開發的朋友一起交流探討。
Weex 與原生頁面互動:用 runtime 動態跳轉並傳遞參數
在混合式 App 中,Weex 頁面常需要跳轉到原生頁面。若頁面名稱與所需參數固定,直接寫死即可;但若希望通用,可讓原生提供一個動態跳轉方法,接收類別名稱與參數字典。實作
AutoCompleteTextView 自動補全輸入框實作教學
我們幾乎每天都在用百度或 Google 搜索:鍵入一兩個字,候選詞就自動跳出來。這種效果在 Android 裡並不需要自己寫過濾算法——AutoCompleteTextV
Android 百分比適配方案:PercentFrameLayout 與 PercentRelativeLayout 解析
在 Android 屏幕適配問題中,百分比方案一直備受關注。相比固定 dp 值,百分比佈局能夠更好地適應不同屏幕尺寸。Google 提供的 Percent Support
Android 內存洩露常見原因大盤點與總結
本文系統梳理了 Android 開發過程中經常遇到的內存洩露問題,並給出相應的規避建議。 集合類洩漏 如果一個集合類只有添加元素的方法,卻沒有相應的刪除機制,就會導致內