編輯:關於 Android 程式設計
一般我們會將播放邏輯放入 Service 中,以實現背景持續播放音樂的功能。背景 Service 被系統回收的機率相對較低,但這種情況確實存在。此時可改用「前台服務」。
前台服務是被認為用戶知情、且在記憶體不足時不允許系統殺死的服務。它必須在狀態列提供一個通知,置於「進行中(Ongoing)」之下,直到服務被終止或從前台移除通知才能解除。例如音樂播放器服務應設為前台運行,因為用戶明確知道其操作,狀態列通知可指明當前歌曲,並可啟動與播放器互動的 Activity。
要讓服務在前台運行,需呼叫 startForeground(),該方法需要兩個參數:一個唯一標識通知的整數,以及給狀態列的通知:
Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text), System.currentTimeMillis()); Intent notificationIntent = new Intent(this, ExampleActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); notification.setLatestEventInfo(this, getText(R.string.notification_title), getText(R.string.notification_message), pendingIntent); startForeground(ONGOING_NOTIFICATION, notification);
要從前台移除服務,需呼叫 stopForeground(),其布林參數指示是否刪除狀態列通知,該方法不會終止服務。註:startForeground() 與 stopForeground() 自 Android 2.0(API Level 5)引入,較舊版本需使用 setForeground()。
完整示例:
public class ForgroundService extends Service {
private static final int NOTIFICATION_ID = 100;
private static final Uri mMusicUri = Uri.fromFile(new File("/sdcard/sound_file_1.mp3"));
private MediaPlayer mMediaPlayer = null;
public class ForgroundServiceBinder extends Binder {
public void playMusic() {
stopCurrentMediaPlayer();
mMediaPlayer = MediaPlayer.create(getApplicationContext(), mMusicUri);
mMediaPlayer.start();
String songName = "Test Music";
PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0,
new Intent(getApplicationContext(), ForgroundServiceActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new Notification();
notification.tickerText = "Forground Service";
notification.icon = R.drawable.icon;
notification.flags |= Notification.FLAG_ONGOING_EVENT;
notification.setLatestEventInfo(getApplicationContext(), "MusicPlayerSample", "Playing: " + songName, pi);
startForeground(NOTIFICATION_ID, notification);
}
public void stopMusic() {
stopCurrentMediaPlayer();
stopForeground(true);
}
}
private ForgroundServiceBinder mBinder = new ForgroundServiceBinder();
@Override
public IBinder onBind(Intent arg0) {
return mBinder;
}
private void stopCurrentMediaPlayer() {
if (mMediaPlayer != null) {
mMediaPlayer.stop();
mMediaPlayer.release();
mMediaPlayer = null;
}
}
}
Activity 端透過 bindService 綁定服務,並在 onServiceConnected 中取得 Binder 呼叫播放與停止:
bindService(serviceIntent, mServiceConnection, BIND_AUTO_CREATE);
透過前台服務搭配通知,即可讓音樂播放服務在記憶體緊張時仍優先存活,提升播放體驗的穩定性。
Android 事件總線(一):EventBus 3.0 用法全解析
EventBus 是 Android 中常見的發布訂閱事件總線,主要用於簡化元件之間的通信。它能降低耦合,讓訊息發送者與接收者不需要直接互相依賴。 三要素與 Thread
Android 4.4 NotificationListenerService 使用詳解與原理分析(一)
概況 Android 在 4.3(API 18)中引入了 NotificationListenerService。根據官方開發者文檔的說法,當系統收到新通知或通知被刪除時
用 PopupWindow 自定義 Android ActionBar Overflow 菜單
為什麼使用 PopupWindow 實作 Overflow當 ActionBar 上的操作按鈕過多時,系統會自動將部分項目收進 Overflow 選單。若想做出更客製化的
Android WebView 入門:打造一個能上網、能讀本地頁面的簡易瀏覽器
想把網頁內容直接嵌進 App,最省力的方式就是使用 WebView。本文示範一個堪用的小瀏覽器,它做到三件事:開啟指定網址、載入 assets 目錄下的離線頁面,以及用實