編輯:Android 開發實例
做 Android 久了,會發現真正需要 mastering 的是四大元件加上串起它們的 Intent:Activity、Service、ContentProvider、BroadcastReceiver。Activity 大家都很熟,這個範例我們把焦點放在另外兩個——用 Service 讓音樂在背景持續播放,以及用 ContentProvider 取得裝置裡的媒體庫。
Service 沒有 UI、不能與使用者互動,跑在背景,離開 App 後只要行程沒被結束,它就還在。音樂播放器正是它的經典場景:使用者可能一邊聽歌一邊逛網頁,若播放邏輯寫在 Activity 裡,離開 App 音樂就停了。
另一個常被忽略的用途是週期性更新:某些資料需要定期從網路抓取,用 Service 排程更新,就不必每次開 App 都重新拉一次。
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>
關鍵概念是:透過 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 端刻意寫得很薄,因為所有播放邏輯都應該在 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 一定要在 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 之後音樂仍然持續。
這個範例的價值在於把 Service 與 ContentProvider 的組合講清楚,但如果要變成真正上架的播放器,還有幾個地方必須補強:
onDestroy 做 release(),但正式版本還要處理錯誤重試、音訊焦點(Audio Focus)被搶走、耳機拔出等情境,否則會出現「音樂自己停了」或「跟其他 App 搶喇叭」的問題。MediaStore.Audio.Media.DATA 取檔案路徑,而應改用 ContentResolver.openFileDescriptor() 搭配 MediaPlayer.setDataSource(FileDescriptor),並加上適當的 selection 過濾條件。close(),或用 MediaStore 的 query 包裝好並在 onDestroy 一併收尾。把 Service 當背景載體、把 ContentProvider 當資料來源,這個組合不只適用於音樂,影片播放、相簿瀏覽、下載管理都是同一套骨架。理解了它,四大元件裡最抽象的那兩個就不再難懂。
用 ListView 實作自適應表格:每格寬度都能不同
先前有文章談過用 GridView 做表格,這次換 ListView。兩者的取捨值得先講清楚: GridView:每格尺寸固定,但自適應表格結構容易,也能定位到「某一
Android 讀取通訊錄、撥打電話、發送短信與長按菜單綜合實戰
這是一個把多個基礎知識點串起來的小項目:用 ListView 展示手機通訊錄,單擊直接撥號,長按彈出菜單,菜單裡可以查看詳情或發送短信。適合拿來熟悉 ContentPro
Android 登入畫面實作:附三次錯誤就鎖定的安全機制
幾乎每個需要使用者帳號的 App,都得面對同一個問題:怎麼做一個既好用又不容易被暴力破解的登入畫面。本章會從最基礎的兩個輸入框開始,一路加上密碼遮蔽、錯誤提示,以及最關鍵
Android 開發實作:日曆專案(三)建立樣式與資源
接續日曆專案的進度,這一階段要把視覺資源整理乾淨:顏色、尺寸、Color State List、drawable 與 style 全部抽成獨立檔案。日曆的表格線以 Cel