這個實例的重點是 Service 的管理:啟動服務,並在退出應用時把它關掉(Stop)。它模擬了一個電蚊香——打開就開始播放防蚊鈴聲並在通知欄顯示狀態,關掉則全部收尾。
界面上只有兩個元件:一個 ImageView 顯示狀態圖,一個 ImageButton 用來控制服務的運行與關閉。點擊按鈕後程式開始運作,通知欄也會出現對應的提示。
package irdc.ex10_08;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.IBinder;
/* 自訂 MyService 繼承 Service */
public class MyService extends Service
{
private String MY_PREFS = "MosPre";
private NotificationManager notiManager;
private int mosStatus;
private int notiId = 99;
private MediaPlayer myPlayer;
@Override
public void onCreate()
{
try
{
/* 取得 NotificationManager */
notiManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
/* 建立 MediaPlayer */
myPlayer = new MediaPlayer();
myPlayer = MediaPlayer.create(MyService.this, R.raw.killmosall);
/* 讀取防蚊服務狀態(1: 啟動,0: 關閉) */
SharedPreferences pres = getSharedPreferences(MY_PREFS, Context.MODE_PRIVATE);
if (pres != null) {
mosStatus = pres.getInt("status", 0);
}
if (mosStatus == 1) {
/* 加上一個 Notification */
setNoti(R.drawable.antimos, notiId, "防蚊服務啟動");
/* 播放防蚊鈴聲 */
if (!myPlayer.isPlaying()) {
myPlayer.seekTo(0);
myPlayer.setLooping(true);
myPlayer.start();
}
} else if (mosStatus == 0) {
/* 刪除 Notification */
deleteNoti(notiId);
/* 關閉防蚊鈴聲 */
if (myPlayer.isPlaying()) {
myPlayer.setLooping(false);
myPlayer.pause();
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
super.onCreate();
}
@Override
public void onDestroy()
{
try
{
/* Service 關閉時釋放 MediaPlayer,並刪除 Notification */
myPlayer.release();
deleteNoti(notiId);
}
catch (Exception e)
{
e.printStackTrace();
}
super.onDestroy();
}
/* 新增 Notification */
public void setNoti(int iconImg, int iconId, String icontext)
{
/* 點選通知條時要執行的 Activity */
Intent notifyIntent = new Intent(this, EX10_08.class);
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
/* 建立 PendingIntent 作為遞延執行的 Intent */
PendingIntent appIntent = PendingIntent.getActivity(this, 0, notifyIntent, 0);
/* 建立 Notification 並設定相關參數 */
Notification myNoti = new Notification();
myNoti.icon = iconImg; // status bar 顯示的圖示
myNoti.defaults = Notification.DEFAULT_SOUND; // 發生時播放預設聲音
myNoti.setLatestEventInfo(this, "防蚊服務啟動", icontext, appIntent);
/* 送出 Notification */
notiManager.notify(iconId, myNoti);
}
/* 刪除 Notification */
public void deleteNoti(int iconId)
{
notiManager.cancel(iconId);
}
@Override
public IBinder onBind(Intent arg0)
{
return null;
}
}
它示範了 Service 生命週期中最一組實用的搭配:onCreate() 初始化資源、onDestroy() 釋放資源,中間用 MediaPlayer 持續播放。而 onBind() 回傳 null,代表這是一個「只啟動、不綁定」的 started service——元件之間不互相溝通,只由 Activity 負責下指令。
另外它把狀態存在 SharedPreferences 裡,讓服務被系統重啟時還能恢復上次的開關狀態,是個很實用的小技巧。
版本提醒:setLatestEventInfo() 與直接指派 Notification.icon 的寫法在 API 20 之後已不能用,取而代之的是 Notification.Builder 搭配 NotificationChannel(Android 8.0 起強制要求)。而長時間播放的服務,也必須改為前台服務並顯示常駐通知。