iT邦幫忙

2021 iThome 鐵人賽

DAY 23
0
自我挑戰組

Android Studio 初學者的30天筆記系列 第 23

DAY23:Service背景服務之實作

這次的實作主要就是凸顯Service的功能,畫面設計上會相對簡單許多,這次是利用Service來啟動另一個Activity,按下啟動鍵後,在Service中透過Thread延遲三秒,啟動Main2Activity。
首先,我們要先建立兩個畫面以及一個Service,第一個畫面只需要一個Button,也就是讓我們按下後啟動Service的按鈕。畫面如下:
https://ithelp.ithome.com.tw/upload/images/20211007/20140488Gfc3LRN5ir.png
https://ithelp.ithome.com.tw/upload/images/20211007/20140488d8hDX7VjnZ.png
接著是,啟動Service之後啟動Main2Activity的畫面,畫面成功出現也就代表成功了,只會用到TextView來告知成功。畫面如下:
https://ithelp.ithome.com.tw/upload/images/20211007/20140488gb5siC2fVP.png
https://ithelp.ithome.com.tw/upload/images/20211007/201404889eXdA6xmON.png
接著我們要在MainActivity中對按鈕加入監聽事件,使用StartService啟動Service,從目前的Activity來啟動MyService元件,最後關閉Service。
https://ithelp.ithome.com.tw/upload/images/20211007/20140488AqiHM2aSsM.png
再來,編寫MyService,使用Thread去執行耗時的工作,且使用Sleep()來延遲五秒,再來宣告Intent從MyService啟動Main2Activity,當Service啟動Activity則加入flag去定義新的Activity。最後的最後,利用上篇說到的使用START_NOT_STICKY完全結束Service。
https://ithelp.ithome.com.tw/upload/images/20211007/20140488WLG3jApJa0.png
執行畫面如下:
在最一開始按下按鈕。
https://ithelp.ithome.com.tw/upload/images/20211007/20140488oU32auZXQp.png
接著,Service會啟動並用Toast顯示。
https://ithelp.ithome.com.tw/upload/images/20211007/20140488PkrjVAN3E1.png
最後,成功執行後會在第二個畫面顯示成功了!
https://ithelp.ithome.com.tw/upload/images/20211007/20140488DAVy38Xpop.png


上一篇
DAY22:Service背景服務之簡介
下一篇
DAY24:Broadcast receiver之簡介
系列文
Android Studio 初學者的30天筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言