Re: [問題] Service直接 call Service onDestroy()方

看板AndroidDev作者 (風中行者時空旅人)時間11年前 (2012/07/25 14:45), 編輯推噓1(100)
留言1則, 1人參與, 最新討論串2/2 (看更多)
※ 引述《s86097john (鍋子)》之銘言: : 這個標題可能有點聳動 : 因為翻過API是說不要直接這樣CALL : 但是心裡對於Service的Lifecycle還是有點好奇 : 例如: : 如果我今天在這邊這樣寫(這邊是Service的onDestroy) : @Override : public void onDestroy() : { : Log.d("MyService", "onDestroy"); : Toast.makeText(this, "跑到onDestroy", Toast.LENGTH_LONG).show(); : super.onDestroy(); : } : 然後我在在Service另外的地方先後使用 : onDestroy(); : stopSelf(); : 則去log看的結果是兩個"onDestroy",也就是說直接使用的onDestroy()是有跑進去的, : 然後使用stopSelf()的時候因為把整個Service停掉了所以也會跑進去一次(這邊的理解 : 可能有問題,希望有人可以指正)。 : 那如果照onDestroy()api的定義: : Called by the system to notify a Service that it is no longer used : and is being removed. The service should clean up any resources : it holds (threads, registered receivers, etc) at this point. : Upon return, there will be no more calls in to this Service object : and it is effectively dead. Do not call this method directly. : 為什麼直接使用onDestroy()後還可以使用stopSelf()呢?(因為東西不是都已經 : 被清空了?)還是說關鍵在 Called bt the system 這句話?因為好奇既然都有使用 : 為什麼不會發生上述問題?或是我對於繼承還有甚麼地方沒有搞清楚的呢? "當一個 service component 要被殺掉的時候系統會 call Service.onDestroy()" 而不是 "call Service.onDestroy() 會把 service component 殺掉" 此外 "call Service.stopSelf() 會把 service component 殺掉" 所以說你的 log 裡面會有兩個 onDestroy 希望這樣有回答到你的問題 順便提一下 你的 code 裡面 call 到的 super.onDestroy() 內容其實是空的 系統 runtime 也不會去檢查他有沒有被 call 到所以拔掉也沒差 -- ╔═══╗╔══╮╗╔═══╗╭═══╮╔═══╮ ║ ║║ ║║║ ║║ ║║ ║ ╚═╗╔╝║ ║║║ ═╣║ ╭╮║║ ═ ║ ╔═╝╚╗║ ║ ║║ ╔═╝║ ╰╯║║ ╔╮╯ ╚═══╝╚═╰═╝╚═╝ ╰═══╯╚═╝╚╝ -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.112.29.235 ※ 編輯: Azarc 來自: 140.112.29.235 (07/25 15:28)

07/25 21:38, , 1F
感謝Az大實在是太威了~
07/25 21:38, 1F
文章代碼(AID): #1G3vOb8y (AndroidDev)
文章代碼(AID): #1G3vOb8y (AndroidDev)