android native activity編程解疑記錄

1 java層的camera 預覽回調onPreviewFrame是在哪個線程調用的?

答案是在調用open camera的這個線程,前提是這個線程要有關聯的looper,如果沒有,就會在main thread上面。底層在獲取到相機原始數據後,會把onPreviewFrame消息送到looper關聯的消息隊列裏。

2 疑問,android_main入口中,裏面實現如果不進行消息處理,也就是不調用 source->process(state, source);  爲什麼會造成app死機?也就是main thread不處理其相關的looer,這會導致相機onpreviewframe不被調用。

android_main是有別於UI主線程的單獨線程,由pthread_create創建,測試發現如果不調用source->process(state, source); ,會導致main thread阻塞,調用這個後,mainThread會正常處理消息,就像主線程打開的camera,如果不source->process(state, source),onPreviewFrame是不能被調用的,如果source->process(state, source);,onPreviewFrame仍舊在main Thread調用。好像android_main的線程的looper會優先處理所有事件,他會把屬於main thread的事件發放給他。

另外一個奇怪的現象是,android_main中open camera,onpreviewframe仍舊會在main thread的線程裏面調用。

相關參考http://www.ikerhurtado.com/android-ndk-native-activity-app-glue-lib-lifecycle-threads

pp glue lib implementation

I put some high level notes about the implementation.

The following diagram indicates how the main and background thread work together to create the multi-threaded native activity:

At startup the main thread creates a unidirectional pipe for communication between the main UI thread and the background thread.

When an activity lifecycle or UI event occurs, the main thread simply writes a command to the write end of the pipe. Because the signal is left before actual processing of the events, the main thread can return from the callback function quickly without worrying about the possible long processing.

In the background thread the the true loop implemented in the android_main function will poll for events. Once an event is detected, the function calls the event handler, which reads the exact command from the read end of the pipe and handles it.

The android_native_app_glue library implements all the main thread stuff and part of the background thread stuff for us. We only need to supply the polling loop and the event handler.

The library attaches two event queues for the event loop to be created by us in the background thread, including the activity lifecycle event queue and the input event queue

如果希望onPreviewFrame被正常調用,可以藉助 HandlerThread來將回調放到一個單獨的線程裏面。HanderThread有一個自己的looper,camera投遞的onpreviewFrame會被這個線程裏面調用,因此還是可以獲取到相機數據。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章