Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 多媒體:播放多媒體時的前台服務

編輯:關於 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);

透過前台服務搭配通知,即可讓音樂播放服務在記憶體緊張時仍優先存活,提升播放體驗的穩定性。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved