第八堂 學習使用 service
TRANSCRIPT
課程內容• Service 服務
• Thread 和 Handler
• Toast
• AlertDialog
• Notification
• 利用 Service 組合做出 Timer 計時器
Jason 的 Android 快樂應用程式學習班
Service 服務• Service 是 Android 的主要建構單元之一 , 和
Activity 不同 , Service 不會有使用者介面 , 是背景執行一段程式碼
• Service 在背景執行 , 不受 Activity 影響
• Service 可分為 bound service 跟 unbound service 兩種
• unbound service 只有開始跟停止兩個狀態
Jason 的 Android 快樂應用程式學習班
IntentService
Jason 的 Android 快樂應用程式學習班
• IntentService 是另外開一條 Thread
• IntentService 同一時間只能有一個在跑
• 因為 IntentService 不在 main thread 上 , 可以用來下載網路資料
ex. 利用 Service 每隔一秒輸出文字
Jason 的 Android 快樂應用程式學習班
1. 建立一個 Project, 名稱為 ServiceTimer
2. 在 MainActivity 做一個開始 button 與一個停止 button
3. 新建一個 TimerService extends IntentService
4. 當按下開始 button 時 , 每隔一秒在 Log 輸出文字” still running”, 當按下停止 button 時 , 停止輸出文字
開始停止
Log
still running…still running…still running…
Thread 與 Handler
Jason 的 Android 快樂應用程式學習班
MainThread
Thread
報告 , 處理好了 , 需要更新
UI
Handler
交給我就好 ,我來處理
ex. 改變按鈕狀態
Jason 的 Android 快樂應用程式學習班
1. 將兩個 button 變成一個 button
2. 當 service 在跑時 , button 文字為停止
3. 當輸出十個 “ still running” 後 , 停止 Service, 並變更 button 文字為 開始
停止Log
still running…still running…
still running…
AlertDialog
Jason 的 Android 快樂應用程式學習班
still running…
• AlertDialog 是一個彈出的視窗 ( 對話框 ), 用意是讓使用者決定接下來的動作
setTitle()
setView()
setPositiveButton(),setNegativeButton()
ex. 建立一個 TextView, 點及時彈出設置秒數的 AlertDialog
Jason 的 Android 快樂應用程式學習班
1. 建立一個 AlertDialog 需要的 layout, 取名為 custom_dialog
2. 在 MainActivity 中 new AlertDialog.Builder()
3. 利用 LayoutInflater 取得 custom_dialog
4. setTitle(), setView(), setPositiveButton(), setNegativeButton()
ex. 當按下開始的時候 , 彈出 Notification, 倒數結束的時候 , 結束
Notification1. 按下開始 Button 時 , 產生 Notification
2. 在 TimerService 內 , startForeground()
3. 倒數結束時 , stopForeground()
P.S stopForeground() 表示移除 service 的 foreground state, allowing it to be killed if more memory is needed.
利用 Service 組合做出 Timer
• 想像 Timer 的狀態
• 取得系統的時間
• 開始計時時 , 彈出 Notification
• 比較經過了多少時間
• 不斷更新 TextView
• 時間結束時 , 彈出 Toast
Jason 的 Android 快樂應用程式學習班
Calendar c = Calendar.getInstance();int currentSeconds = (int) (c.getTimeInMillis()/1000);
完整程式碼
Jason 的 Android 快樂應用程式學習班
https://github.com/KosbrotherSchool/Teach_TimerService