標籤:多媒體 前台服務
眾所周知,一般我們將播放的邏輯都放入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()方法是在Android2.0(API Level 5)中引入的。為了在比較舊的平台版本中運行你的服務,你必須使用以前的setForeground()方法---關於如何提供向後的相容性,請看startForeground()方法文檔。
範例程式碼如下:
ForgroundService.java
import java.io.File;import android.app.Notification;import android.app.PendingIntent;import android.app.Service;import android.content.Intent;import android.media.MediaPlayer;import android.net.Uri;import android.os.Binder;import android.os.IBinder;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";// assign the song name to songNamePendingIntent 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();@Overridepublic IBinder onBind(Intent arg0) {return mBinder;}@Overridepublic void onDestroy() {stopCurrentMediaPlayer();super.onDestroy();}private void stopCurrentMediaPlayer() {if (mMediaPlayer != null) {mMediaPlayer.stop();mMediaPlayer.release();mMediaPlayer = null;}}}
ForgroundServiceActivity.java
import ForgroundService.ForgroundServiceBinder;import android.app.Activity;import android.content.ComponentName;import android.content.Intent;import android.content.ServiceConnection;import android.os.Bundle;import android.os.IBinder;import android.view.View;import android.view.View.OnClickListener;public class ForgroundServiceActivity extends Activity {@Overrideprotected void onDestroy() {unbindService(mServiceConnection);super.onDestroy();}@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.layout_forground_service);final Intent serviceIntent = new Intent(this, ForgroundService.class);//startService(serviceIntent);bindService(serviceIntent, mServiceConnection, BIND_AUTO_CREATE);}private ServiceConnection mServiceConnection = new ServiceConnection() {@Overridepublic void onServiceConnected(ComponentName name, IBinder binder) {final ForgroundServiceBinder service = (ForgroundServiceBinder) binder;findViewById(R.id.start).setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {service.playMusic();}});findViewById(R.id.stop).setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {service.stopMusic();}});}@Overridepublic void onServiceDisconnected(ComponentName name) {}};}
layout_forground_service.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Button android:id="@+id/start" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Play" /> <Button android:id="@+id/stop" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Stop" /></LinearLayout>