golang 移動應用例子 example/basic 源碼框架分析

條件編譯

咱們在源碼中能夠看到2個文件: main.go 和 main_x.go 這兩個包名都是 package main , 都有 main 函數。 不會衝突麼?linux

答案是不會的,android

main_x.go 文件中有個註釋:git

// +build !darwin,!linux,!windowsgithub

main.go 文件中註釋以下:golang

// +build darwin linux windows
這裏來標示編譯適用的不一樣環境。只有知足條件的纔會被編譯進去, 因此這裏有2個 main 函數,編譯並不衝突。windows

參考:服務器

http://blog.csdn.net/varding/article/details/12675971 app

http://dave.cheney.net/2013/10/12/how-to-use-conditional-compilation-with-the-go-build-tool 函數

Android應用啓動入口

APK文件自己是一個壓縮包,直接用解壓工具便可打開,但裏面的文件都已被編碼爲二進制文件格式,不能直接看,好比程序描述文件AndroidManifest.xml,使用apktool工具能夠將這些文件解碼還原出來。
apktool(http://code.google.com/p/android-apktool/  如今地址是: http://ibotpeaches.github.io/Apktool/ )是一個很是著名的開源工具包,功能很強大,能夠解包APK文件並從新打包,經常使用來漢化Android應用。工具

apktool 安裝方法請看: http://ibotpeaches.github.io/Apktool/install/

參考: http://kenkao.iteye.com/blog/1890497

使用這個工具咱們能夠看到basic.apk文件的 AndroidManifest.xml 文件的內容以下:

<?xml version="1.0" encoding="utf-8"?>
<manifest package="org.golang.todo.basic" android:versionCode="1" android:versionName="1.0"
  xmlns:android="http://schemas.android.com/apk/res/android">
    <application android:label="Basic" android:debuggable="true">
        <activity android:name="org.golang.app.GoNativeActivity" android:label="Basic" android:configChanges="keyboardHidden|orientation">
            <meta-data android:name="android.app.lib_name" android:value="basic" />
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

這個就是apk文件的執行入口,而不是作服務器段開發的 main 函數入口。

這裏隱含的實現了 org.golang.app.GoNativeActivity 這個Activity。

 

具體這裏的邏輯被封裝在 golang.org/x/mobile/app 代碼中。

主要的核心代碼以下:

func main() {
    app.Main(func(a app.App) {
        for e := range a.Events() {
            switch e := a.Filter(e).(type) {
            case lifecycle.Event:
                // ...
            case size.Event:
                // ...
            case paint.Event:
                // ...
            case touch.Event:
                // ...
            }
        }
    })
}

image

不一樣的事件隨後觸發不一樣的函數。完成這些功能。

從字面理解就能夠知道這幾個事件是作啥的。

lifecycle.Event  Activity 生命週期相關的幾個事件;

size.Event  屏幕尺寸變化相關事件

paint.Event  繪畫屏幕的事件

touch.Event 觸屏或者鼠標左鍵點擊和移動事件

相關文章
相關標籤/搜索