衆所周知,一般我們將播放的邏輯都放入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 songName
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;
}
@Override
public 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 {
@Override
protected void onDestroy() {
unbindService(mServiceConnection);
super.onDestroy();
}
@Override
protected 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() {
@Override
public void onServiceConnected(ComponentName name, IBinder binder) {
final ForgroundServiceBinder service = (ForgroundServiceBinder) binder;
findViewById(R.id.start).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
service.playMusic();
}
});
findViewById(R.id.stop).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
service.stopMusic();
}
});
}
@Override
public 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>