Thursday, April 12, 2012

SurfaceView 的onSurfaceDestroy()的系統呼叫時機

一開始以為surfaceDestroy()這個SurfaceView.callback實作函式一定會在Activity onPause()呼叫後被執行,結果發現不然。

基本上SurfaceView的callback函式與Activity5大進程之間的運行過程為︰
onCreate()-->onStart()-->onResume()-->surfaceCreated()-->onPause()-->surfaceDestroy()-->onStop-->onDestroy()

如果不能掌握surfaceDestroy()被呼叫的時間點,
就很難確保下次該Activity有沒有重新執行surfaceCreate(),
這會造成程式執行上很重大的問題…

查了一下倒底surfaceDestroy()的呼叫時間點為何?
後來在Android Developer看到了一段話︰
The way SurfaceView works is that its Surface is created when the view
is attached to a window, and destroyed when it is detached.  There is
no provision for you to do destroy it at other points, nor is that a
good idea because if the system ever needs to show that part of your
window you will end up with a big hole in the window (where the
SurfaceView exists, but without a Surface to display).

原來SurfaceView的運作時機是建構在Activity的View是否有"黏(attached)"到window上判定。
我們知道,
window是Android最底層的視窗管理元件(看一下我之前PO的這篇),
view是後來才黏上去的產物,
當系統判定當下的Activity的view"擺脫(detached)"了window後,
SurfaceView的surfaceDestroy()函式才會被呼叫。

想半天為什麼Intent另一個Activity出來時,
畫SurfaceView的這個Activity為什麼onPause()後沒有呼叫surfaceDestroy()
原來是這個原因=.=||

No comments: