編輯:關於 Android 程式設計
要做一個音樂播放器的第一個畫面,通常就是「歌曲清單」。好消息是 Android 內建的媒體掃描機制已經把 SD 卡與內部儲存中的音訊整理成資料庫,透過 MediaStore 就能直接取到歌名、歌手、時長、專輯資訊,不必自己遞迴搜尋檔案系統。
先用最簡單的 ListView 把清單框起來,記得加上 cacheColorHint="#00000000",讓自訂背景在捲動時不會出現黑影:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ListView
android:id="@+id/music_list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/listbg"
android:cacheColorHint="#00000000" />
</LinearLayout>
整個流程可以拆成兩步:先查詢資料庫拿到 Cursor,再自訂 Adapter 把資料渲染到每一列。
public class SongsActivity extends Activity {
private ListView listView;
private Cursor cursor;
private MusicListAdapter musicListAdapter;
/** 要查詢的欄位:標題、時長、歌手、ID、顯示名稱、路徑、專輯ID */
private static final String[] MUSIC_INFO = new String[] {
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.DURATION,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.ALBUM_ID
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_songs);
listView = (ListView) findViewById(R.id.music_list);
listView.setOnItemClickListener(new MusicListOnClickListener());
showMusicList();
}
private void showMusicList() {
cursor = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
MUSIC_INFO, null, null,
MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
musicListAdapter = new MusicListAdapter(this, cursor);
listView.setAdapter(musicListAdapter);
listView.setOnCreateContextMenuListener(new ContextMenuListener());
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
// 回到主畫面前記得回收注册的廣播接收器
finish();
}
return true;
}
}
如果清單裡還需要用到「目前播放位置」這類狀態,可以另外用 int[] _ids、String[] _titles、String[] _artists 把常用欄位快取成陣列,避免在 Adapter 中反覆 moveToPosition。不過更直覺的做法是直接在 Adapter 內操作 Cursor。
public class MusicListAdapter extends BaseAdapter {
private Context myContext;
private Cursor myCursor;
private int pos = -1; // 目前播放中的項目位置
public MusicListAdapter(Context context, Cursor cursor) {
myContext = context;
myCursor = cursor;
}
@Override public int getCount() { return myCursor.getCount(); }
@Override public Object getItem(int position) { return position; }
@Override public long getItemId(int position) { return position; }
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
View vi = convertView;
if (convertView == null) {
holder = new ViewHolder();
vi = LayoutInflater.from(myContext).inflate(R.layout.musiclist, null);
holder.tv_music = (TextView) vi.findViewById(R.id.music1);
holder.tv_singer = (TextView) vi.findViewById(R.id.singer);
holder.tv_time = (TextView) vi.findViewById(R.id.time);
holder.img = (ImageView) vi.findViewById(R.id.listitem);
vi.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
myCursor.moveToPosition(position);
// 標題太長就截斷加省略號
String title = myCursor.getString(0).trim();
holder.tv_music.setText(title.length() > 15
? title.substring(0, 12) + "..."
: title);
// 未知歌手
String artist = myCursor.getString(2);
holder.tv_singer.setText("".equals(artist) ? "未知藝術家" : artist);
// 時長格式化
holder.tv_time.setText(toTime(myCursor.getInt(1)));
if (position == pos) {
holder.img.setImageResource(R.drawable.isplaying);
} else {
Bitmap bm = getArtwork(myContext,
myCursor.getInt(3),
myCursor.getInt(myCursor.getColumnIndex(
MediaStore.Audio.Media.ALBUM_ID)), true);
holder.img.setImageBitmap(bm);
}
return vi;
}
public void setItemIcon(int position) { pos = position; }
/** 毫秒轉 mm:ss */
public String toTime(int time) {
time /= 1000;
int minute = time / 60;
int second = time % 60;
return String.format("%02d:%02d", minute, second);
}
static class ViewHolder {
TextView tv_music, tv_singer, tv_time;
ImageView img;
}
}
ViewHolder 搭配 setTag 是 ListView 效能的關鍵:避免每一列被繪製時重複 findViewById,長清單捲動明顯順暢。
封面是這份程式最麻煩的部分。內嵌圖片不在檔案系統裡,得透過 content://media/external/audio/albumart 這個 URI 向 MediaStore 索取;若已取得過的縮圖被清掉,還要回頭從原始音訊檔解析。
private static final Uri sArtworkUri =
Uri.parse("content://media/external/audio/albumart");
public static Bitmap getArtwork(Context context, long song_id,
long album_id, boolean allowdefault) {
if (album_id < 0) {
// 不在媒體資料庫中,直接從檔案取
if (song_id >= 0) {
Bitmap bm = getArtworkFromFile(context, song_id, -1);
if (bm != null) return bm;
}
return allowdefault ? getDefaultArtwork(context) : null;
}
ContentResolver res = context.getContentResolver();
Uri uri = ContentUris.withAppendedId(sArtworkUri, album_id);
if (uri == null) return null;
InputStream in = null;
try {
// 先量尺寸,再決定縮放比例,避免大圖直接吃爆記憶體
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
in = res.openInputStream(uri);
BitmapFactory.decodeStream(in, null, options);
options.inSampleSize = computeSampleSize(options, 30);
options.inJustDecodeBounds = false;
options.inDither = false;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
in = res.openInputStream(uri);
return BitmapFactory.decodeStream(in, null, options);
} catch (FileNotFoundException ex) {
// 縮圖不存在,退回原始檔案解析
Bitmap bm = getArtworkFromFile(context, song_id, album_id);
if (bm != null && bm.getConfig() == null) {
bm = bm.copy(Bitmap.Config.RGB_565, false);
}
if (bm == null && allowdefault) bm = getDefaultArtwork(context);
return bm;
} finally {
if (in != null) {
try { in.close(); } catch (IOException ignored) {}
}
}
}
static int computeSampleSize(BitmapFactory.Options options, int target) {
int w = options.outWidth;
int h = options.outHeight;
int candidate = Math.max(w / target, h / target);
if (candidate == 0) return 1;
if (candidate > 1 && w > target && w / candidate < target) candidate -= 1;
if (candidate > 1 && h > target && h / candidate < target) candidate -= 1;
return candidate;
}
private static Bitmap getDefaultArtwork(Context context) {
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inPreferredConfig = Bitmap.Config.RGB_565;
return BitmapFactory.decodeStream(
context.getResources().openRawResource(R.drawable.item), null, opts);
}
若要從原始檔案取,則用 openFileDescriptor 打開 content://media/external/audio/media/<songid>/albumart,再以 BitmapFactory.decodeFileDescriptor 解碼,同樣先 inJustDecodeBounds = true 量一次尺寸再決定 inSampleSize。
mCachedBit 之類的靜態快取,同一張封面不要每捲一次就解碼一次。onDestroy 中關閉 Cursor,並在返回上一頁時反註冊掃描廣播接收器,避免記憶體洩漏。
用 android-async-http 實作登入:GET 與 POST 兩種寫法完整示範
在〈android-async-http 開源庫介紹與用法〉一文中,我們已經認識了這個庫的基本結構。本文直接進入實戰,用「登入」這個最常見的場景,把 AsyncHttpC
Android 訊息提示 BadgeView:為檢視加上未讀紅點
在聊天、通知或購物應用中,常需要在某個檢視上顯示未讀數量或提示紅點。BadgeView 就是一種常見的實作方式,可將文字標籤疊加在任意 View 上。 基本概念 Bad
ListView 多視圖實現:一個 Adapter 應對多種 item 佈局
資訊流類的列表裡,item 樣式往往不止一種:普通圖文、純文字提問、帶封面的案例、三圖並排的卡片……如果為每種樣式寫一個 Adapter 再拼進 ListView,代碼很
Android Shader 渲染入門:五種子類與三種平鋪模式一次講透
Paint 除了純色,還能填「材質」。這件事由 Shader 家族負責——把一個 Shader 設給 Paint,之後所有用這個 Paint 進行的繪製(Bitmap