編輯:關於 Android 程式設計
Android 要掌握的知識點實在不少,唯有持續動手才能內化。前陣子我決定拿 MP3 播放器來練功——這個題目幾乎涵蓋了 Android 開發中相當一部分核心概念:ListView 資料綁定、Service 常駐、MediaPlayer 控制、Handler 與多線程的 UI 更新。做完一遍,對整個架構的理解會踏實很多。
於是有了這一系列開發日誌。第一階段目標先定得務實一些:做出一個能讀取本機音樂的播放器。
主畫面用 ListView 列出裝置內所有音檔,左側是序號,右側兩行分別顯示檔名與歌手,最右邊預留了一顆按鈕(功能尚未實作)。

點進播放頁後,可以看到歌曲資訊、播放/暫停鍵、上一首下一首,以及一條可拖動的進度條。


先把一首歌需要的屬性收攏到一個實體類裡,後續無論是清單顯示還是播放控制都靠它傳遞。
public class Mp3Info {
private String name;
private long ID;
private String title; // 音樂標題
private String artist; // 演出者
private long duration; // 時長
private long size; // 檔案大小
private String url; // 檔案路徑
// 各欄位的 getter / setter 略
}
Android 的媒體庫由 MediaStore 統一維護,透過 ContentResolver 查詢 EXTERNAL_CONTENT_URI 就能拿到裝置內的媒體清單,再用 IS_MUSIC 這個欄位過濾出真正的音樂。
public List<Mp3Info> getMp3Infos() {
Cursor cursor = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
null, null, null,
MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
List<Mp3Info> mp3Infos = new ArrayList<Mp3Info>();
for (int i = 0; i < cursor.getCount(); i++) {
Mp3Info mp3Info = new Mp3Info();
cursor.moveToNext();
long id = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media._ID));
String title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
long duration = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));
long size = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.SIZE));
String url = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
int isMusic = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.IS_MUSIC));
if (isMusic != 0) {
mp3Info.setID(id);
mp3Info.setTitle(title);
mp3Info.setArtist(artist);
mp3Info.setDuration(duration);
mp3Info.setSize(size);
mp3Info.setUrl(url);
mp3Infos.add(mp3Info);
}
}
return mp3Infos;
}
這段邏輯本質上就是查一次系統媒體資料庫,再把每筆紀錄攤平成我們自己的結構。實務上要記得補上 READ_EXTERNAL_STORAGE 權限,並在較新版本的 Android 上處理執行期權限申請。
播放能力為什麼要放進 Service?因為使用者離開播放頁之後音樂還得繼續響,而 Service 的生命週期不受 Activity 消亡影響,正是為此而生。
public class MusicService extends Service {
String path; // mp3 絕對路徑
MediaPlayer mediaPlayer; // 播放引擎
IBinder musicBinder = new MyBinder();
private String TAG = "MyService";
class MyBinder extends Binder {
public Service getService() {
return MusicService.this;
}
}
@Override
public IBinder onBind(Intent arg0) {
return musicBinder;
}
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate() executed");
}
// 每次被啟動時呼叫,這裡接收歌曲路徑並初始化播放器
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
path = intent.getStringExtra("url");
init();
if (mediaPlayer.isPlaying()) {
pause();
}
return super.onStartCommand(intent, flags, startId);
}
void init() {
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(path);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.prepareAsync(); // 非同步載入媒體資源,避免阻塞主線程
} catch (Exception e) {
e.printStackTrace();
}
}
// 播放進度以百分比回傳
public double getProgress() {
int position = mediaPlayer.getCurrentPosition();
int time = mediaPlayer.getDuration();
return (double) position / (double) time;
}
// 由 Activity 拖動進度條時呼叫
public void setProgress(int max, int dest) {
int time = mediaPlayer.getDuration();
mediaPlayer.seekTo(time * dest / max);
}
public void play() {
if (mediaPlayer != null) {
mediaPlayer.start();
}
}
public void pause() {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
mediaPlayer.pause();
}
}
@Override
public void onDestroy() {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
super.onDestroy();
}
}
這裡有兩個值得留意的細節:prepareAsync 讓載入不阻塞 UI;onDestroy 中務必 stop 加 release,否則 MediaPlayer 佔用的原生資源不會被回收。
Activity 透過 bindService 建立連接,並實作 ServiceConnection 取得 Service 實例。取得實例之後,播放、暫停、跳進度都能直接呼叫對應方法。
進度條的即時更新則是另一個問題。主線程的等待不能超過五秒,否則會觸發 ANR 與畫面卡頓,因此每 100 毫秒輪詢一次播放進度的動作必須放到子線程,再把結果用 Handler 丟回主線程更新 SeekBar。
public class MusicActivity extends Activity {
private ImageView MusicPlay;
private ImageView MusicNext;
private ImageView MusicPrevious;
boolean mBound = false;
boolean flag = false;
MusicService mService;
SeekBar seekBar;
Thread myThread;
boolean playStatus = true;
// 接收子線程捎來的進度訊息
Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
double progress = msg.getData().getDouble("progress");
int max = seekBar.getMax();
seekBar.setProgress((int) (max * progress));
break;
default:
break;
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.musicplay);
MusicPlay = (ImageView) findViewById(R.id.Musicplay);
MusicNext = (ImageView) findViewById(R.id.musicnext);
MusicPrevious = (ImageView) findViewById(R.id.musicprevious);
myThread = new Thread(new UpdateProgress());
Intent serviceIntent = new Intent(MusicActivity.this, MusicService.class);
if (!mBound) {
// 第三個參數表示服務不存在時自動建立
bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
}
seekBar = (SeekBar) findViewById(R.id.MusicProgress);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
int dest = seekBar.getProgress();
int max = seekBar.getMax();
mService.setProgress(max, dest); // 放手後才真正跳轉
}
@Override
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) { }
@Override
public void onStartTrackingTouch(SeekBar arg0) { }
});
MusicPlay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
if (mBound && flag) {
MusicPlay.setImageDrawable(getResources().getDrawable(R.drawable.musicpause));
mService.pause();
flag = false;
} else {
MusicPlay.setImageDrawable(getResources().getDrawable(R.drawable.musicplay));
mService.play();
flag = true;
}
}
});
}
// 後台更新進度條
public class UpdateProgress implements Runnable {
Bundle data = new Bundle();
int milliseconds = 100;
double progress;
@Override
public void run() {
while (playStatus) {
try {
if (mBound) {
Message msg = new Message();
data.clear();
progress = mService.getProgress();
msg.what = 0;
data.putDouble("progress", progress);
msg.setData(data);
mHandler.sendMessage(msg);
}
Thread.sleep(milliseconds);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder binder) {
MusicService.MyBinder myBinder = (MusicService.MyBinder) binder;
mService = (MusicService) myBinder.getService();
mBound = true;
myThread.start();
MusicPlay.setImageDrawable(getResources().getDrawable(R.drawable.musicplay));
mService.play();
flag = true;
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
@Override
public void onDestroy() {
playStatus = false; // 讓子線程的 while 迴圈得以退出
super.onDestroy();
}
}
playStatus 這個旗標是子線程的收尾開關,Activity 銷毀時必須把它設為 false,否則線程會持續空轉。這也是前面 Service 篇提到的「引用失控」問題在實作層面的具體防範。
MainActivity 用 SimpleAdapter 把 Mp3Info 清單映射到自訂的 listmusic 版面,點擊項目時先檢查服務是否已在跑(避免重複啟動造成狀態錯亂),再帶上歌曲路徑啟動 Service,最後跳轉播放頁。
public class MainActivity extends Activity implements AdapterView.OnItemClickListener {
private ListView MusicList;
ArrayList<HashMap<String, Object>> MusiclistData = new ArrayList<HashMap<String, Object>>();
private SimpleAdapter MusicListAdapter;
List<Mp3Info> mp3Infos;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MusicList = (ListView) findViewById(R.id.listviewmusic);
mp3Infos = getMp3Infos();
GetData(mp3Infos);
MusicListAdapter = new SimpleAdapter(this, MusiclistData, R.layout.listmusic,
new String[]{"ID", "Title", "Artist", "Icon"},
new int[]{R.id.MusicID, R.id.Musictitle, R.id.MusicArtist, R.id.MusicIcon});
MusicList.setAdapter(MusicListAdapter);
MusicList.setOnItemClickListener(MusiclistListen);
}
AdapterView.OnItemClickListener MusiclistListen = new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView adapterView, View view, int i, long l) {
if (isServiceRunning(getBaseContext(), "com.flashmusic.MusicService")) {
stopService(new Intent(MainActivity.this, MusicService.class));
}
Intent intent = new Intent();
intent.putExtra("url", mp3Infos.get(i).getUrl());
intent.setClass(MainActivity.this, MusicService.class);
startService(intent);
startActivity(new Intent(MainActivity.this, MusicActivity.class));
}
};
public static boolean isServiceRunning(Context mContext, String className) {
ActivityManager activityManager =
(ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningServiceInfo> serviceList = activityManager.getRunningServices(50);
if (serviceList.size() == 0) {
return false;
}
for (int i = 0; i < serviceList.size(); i++) {
if (serviceList.get(i).service.getClassName().equals(className)) {
return true;
}
}
return false;
}
private void GetData(List<Mp3Info> mp3Infos) {
for (int i = 0; i < mp3Infos.size(); i++) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("ID", i + 1);
map.put("Title", mp3Infos.get(i).getTitle());
map.put("Artist", mp3Infos.get(i).getArtist());
map.put("Icon", R.drawable.musicicon);
MusiclistData.add(map);
}
}
}
activity_main.xml 只放一個 ListView:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="@+id/listviewmusic"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
musicplay.xml 負責播放頁,底部一列是五顆功能圖示,上方是進度條:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#d8e4f3">
<LinearLayout
android:id="@+id/linearLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="50dp"
android:background="#295b75"
android:orientation="horizontal">
<ImageView
android:id="@+id/imageView"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_margin="10dp"
android:layout_weight="1" />
<ImageView
android:id="@+id/musicprevious"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_margin="10dp"
android:layout_weight="1"
android:src="@drawable/musicprevious" />
<ImageView
android:id="@+id/Musicplay"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_margin="10dp"
android:layout_weight="1"
android:src="@drawable/musicpause" />
<ImageView
android:id="@+id/musicnext"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_margin="10dp"
android:layout_weight="1"
android:src="@drawable/musicnext" />
<ImageView
android:id="@+id/musicmenu"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_margin="10dp"
android:layout_weight="1" />
</LinearLayout>
<SeekBar
android:id="@+id/MusicProgress"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/linearLayout"
android:layout_marginBottom="20dp"
android:max="100" />
</RelativeLayout>
listmusic.xml 是清單項目的自訂版面,序號、標題、演出者三段文字加一張右側圖示:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="60dp">
<TextView
android:id="@+id/MusicID"
android:layout_width="70dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="@+id/Musictitle"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="10dp"
android:layout_toRightOf="@+id/MusicID"
android:ellipsize="end"
android:singleLine="true"
android:textSize="15dp" />
<TextView
android:id="@+id/MusicArtist"
android:layout_width="220dp"
android:layout_height="wrap_content"
android:layout_below="@+id/Musictitle"
android:layout_marginTop="7dp"
android:layout_toRightOf="@+id/MusicID"
android:ellipsize="end"
android:singleLine="true"
android:textColor="#878383"
android:textSize="12dp" />
<ImageView
android:id="@+id/MusicIcon"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="30dp" />
</RelativeLayout>
目前能做到:點擊項目開始播放、播放與暫停切換、拖動進度條快進或倒退。
尚未完成:上一首、下一首,以及播放模式(單曲循環、清單循環、隨機)的切換。這些會在下篇整理,屆時會一併處理播放列表的定位邏輯與通知列控制。
邊做邊記錄,是為了讓踩過的坑留下痕跡。技術這條路沒有捷徑,一起加油。
Android 沉浸式狀態欄實戰:從原理到 API 21 完全透明
前言 這裡不打算爭論「沉浸式」這個詞用得準不準確,大家聽得懂就好。本文整理自實際專案中的經驗,歡迎一起探討。由於實習期間長期處於高強度加班狀態,一直沒時間做總結,直到某天
Android IntentService 使用詳解:異步任務與工作隊列
IntentService 是什麼 IntentService 是 Android 中專門用來處理異步請求的服務類型。它繼承自 Service,但會在內部建立獨立的工作線
手機全網通 3.0 和 2.0 有什麼區別?全網通 3.0 是什麼意思?
以往手機常見分為移動版、移動聯通雙 4G 版與電信 4G 版三種網路版本,現在多數新機都支援全網通,也就是同時吃下移動、聯通、電信三大運營商的所有網路。而不少機型還進一步
Activity 生命週期詳解:七個回呼、四種狀態與實際驗證
用實驗把生命週期跑出來 研究 Activity 生命週期,最直接的方式就是把每個回呼都加上日誌,然後逐一操作、觀察 LogCat。測試用的程式碼相當簡單: package