用Go语言写Android应用 (1) - 用Go写本地应用

简介: 如何用Go语言写跨平台的用于手机上的应用,我们以Android为例分析本地应用的写法。

用Go语言写Android应用 (1) - 从看个小例子开始

下载安装gomobile工具

首先安装1.5以上版本的Go语言环境,这个大家都应该有了。
然后需要通过科学上网方法去下载gomobile命令:

go get golang.org/x/mobile/cmd/gomobile

接着需要通过gomobile init去下载Android NDK的部分toolchain,执行下面的命令:

gomobile init

可以去android网站上下载一份最新的NDK以备用,将来遇上缺什么文件的话,就从NDK里面复制就是了。
下载地址在:https://developer.android.com/ndk/downloads/index.html

一切就绪了之后,先运行个例子试一试吧:

gomobile build -target=android golang.org/x/mobile/example/basic

成功之后,就生成了basic.apk。
可以通过gomobile install命令安装这个apk:

gomobile install golang.org/x/mobile/example/basic

当然啦,apk都生成了,直接用adb install就是了。
basic例子的功能很简单,红底上画一个绿色渐变的三角形,随着手指的点击事件,三角形的直角顶点的位置跟着一起走。

basic例子分析

纯用Go写的Android代码,与Android NDK用C++写的代码异曲同工,都是用OpenGL/ES的命令直接作画的方式。
我们来看下这个不长的例子,涉及到Go语言相关或者是OpenGL相关的不理解的不要紧,后面我们都会介绍,我们先过几个例子找找感觉:

引用包

第一步是引用了一堆要用的包,跟app相关,event相关,openGL相关。

package main

import (
    "encoding/binary"
    "log"

    "golang.org/x/mobile/app"
    "golang.org/x/mobile/event/lifecycle"
    "golang.org/x/mobile/event/paint"
    "golang.org/x/mobile/event/size"
    "golang.org/x/mobile/event/touch"
    "golang.org/x/mobile/exp/app/debug"
    "golang.org/x/mobile/exp/f32"
    "golang.org/x/mobile/exp/gl/glutil"
    "golang.org/x/mobile/gl"
)

定义变量

基本是OpenGL相关的几个值,还有颜色,X和Y的位置。

var (
    images   *glutil.Images
    fps      *debug.FPS
    program  gl.Program
    position gl.Attrib
    offset   gl.Uniform
    color    gl.Uniform
    buf      gl.Buffer

    green  float32
    touchX float32
    touchY float32
)

主函数

先向app.Main中注册我们的主函数。

func main() {
    app.Main(func(a app.App) {
        var glctx gl.Context
        var sz size.Event

下面就是一个典型的消息驱动的循环,app将事件传给我们的主函数,我们根据事件来处理。GUI系统的代码的框架都差不多哈。

        for e := range a.Events() {
            switch e := a.Filter(e).(type) {
            case lifecycle.Event:
                switch e.Crosses(lifecycle.StageVisible) {
                case lifecycle.CrossOn:
                    glctx, _ = e.DrawContext.(gl.Context)
                    onStart(glctx)
                    a.Send(paint.Event{})
                case lifecycle.CrossOff:
                    onStop(glctx)
                    glctx = nil
                }
            case size.Event:
                sz = e
                touchX = float32(sz.WidthPx / 2)
                touchY = float32(sz.HeightPx / 2)
            case paint.Event:
                if glctx == nil || e.External {
                    // As we are actively painting as fast as
                    // we can (usually 60 FPS), skip any paint
                    // events sent by the system.
                    continue
                }

                onPaint(glctx, sz)
                a.Publish()
                // Drive the animation by preparing to paint the next frame
                // after this one is shown.
                a.Send(paint.Event{})
            case touch.Event:
                touchX = e.X
                touchY = e.Y
            }
        }
    })
}

后面基本上就需要一些OpenGL的知识了

func onStart(glctx gl.Context) {
    var err error

通过glutil.CreateProgram创建一个程序,OpenGL里程序是将顶点着色器和片段着色器绑定在一起的实体。

    program, err = glutil.CreateProgram(glctx, vertexShader, fragmentShader)
    if err != nil {
        log.Printf("error creating GL program: %v", err)
        return
    }

    buf = glctx.CreateBuffer()
    glctx.BindBuffer(gl.ARRAY_BUFFER, buf)
    glctx.BufferData(gl.ARRAY_BUFFER, triangleData, gl.STATIC_DRAW)

    position = glctx.GetAttribLocation(program, "position")
    color = glctx.GetUniformLocation(program, "color")
    offset = glctx.GetUniformLocation(program, "offset")

    images = glutil.NewImages(glctx)
    fps = debug.NewFPS(images)
}

func onStop(glctx gl.Context) {
    glctx.DeleteProgram(program)
    glctx.DeleteBuffer(buf)
    fps.Release()
    images.Release()
}

onPaint的过程,是个标准的OpenGL绘制三角形的流程:

func onPaint(glctx gl.Context, sz size.Event) {
    glctx.ClearColor(1, 0, 0, 1)
    glctx.Clear(gl.COLOR_BUFFER_BIT)

    glctx.UseProgram(program)

    green += 0.01
    if green > 1 {
        green = 0
    }
    glctx.Uniform4f(color, 0, green, 0, 1)

    glctx.Uniform2f(offset, touchX/float32(sz.WidthPx), touchY/float32(sz.HeightPx))

    glctx.BindBuffer(gl.ARRAY_BUFFER, buf)
    glctx.EnableVertexAttribArray(position)
    glctx.VertexAttribPointer(position, coordsPerVertex, gl.FLOAT, false, 0, 0)
    glctx.DrawArrays(gl.TRIANGLES, 0, vertexCount)
    glctx.DisableVertexAttribArray(position)

    fps.Draw(sz)
}

下面是三角形的三个顶点的坐标:

var triangleData = f32.Bytes(binary.LittleEndian,
    0.0, 0.4, 0.0, // top left
    0.0, 0.0, 0.0, // bottom left
    0.4, 0.0, 0.0, // bottom right
)

const (
    coordsPerVertex = 3
    vertexCount     = 3
)

最后是我们创建顶点着色器时所使用的GLSL:

const vertexShader = `#version 100
uniform vec2 offset;

attribute vec4 position;
void main() {
    // offset comes in with x/y values between 0 and 1.
    // position bounds are -1 to 1.
    vec4 offset4 = vec4(2.0*offset.x-1.0, 1.0-2.0*offset.y, 0, 0);
    gl_Position = position + offset4;
}`
const fragmentShader = `#version 100
precision mediump float;
uniform vec4 color;
void main() {
    gl_FragColor = color;
}`

对照下C++所写的native activity

我们来对照下,Android用NDK来写这种native的activity都需要做什么吧。总的代码比Go版本的还是长不少,我们就挑个Android的主函数看一下:

void android_main(struct android_app* state) {
    struct engine engine;

    // Make sure glue isn't stripped.
    app_dummy();

    memset(&engine, 0, sizeof(engine));
    state->userData = &engine;
    state->onAppCmd = engine_handle_cmd;
    state->onInputEvent = engine_handle_input;
    engine.app = state;

...

    if (state->savedState != NULL) {
        // We are starting with a previous saved state; restore from it.
        engine.state = *(struct saved_state*)state->savedState;
    }

    // loop waiting for stuff to do.

    while (1) {
        // Read all pending events.
        int ident;
        int events;
        struct android_poll_source* source;

        // If not animating, we will block forever waiting for events.
        // If animating, we loop until all events are read, then continue
        // to draw the next frame of animation.
        while ((ident=ALooper_pollAll(engine.animating ? 0 : -1, NULL, &events,
                (void**)&source)) >= 0) {

            // Process this event.
            if (source != NULL) {
                source->process(state, source);
            }

...

            // Check if we are exiting.
            if (state->destroyRequested != 0) {
                engine_term_display(&engine);
                return;
            }
        }

        if (engine.animating) {
            // Done with events; draw next animation frame.
            engine.state.angle += .01f;
            if (engine.state.angle > 1) {
                engine.state.angle = 0;
            }

            // Drawing is throttled to the screen update rate, so there
            // is no need to do timing here.
            engine_draw_frame(&engine);
        }
    }
}
//END_INCLUDE(all)

Android例子中用的OpenGL比上面Go的例子要简单一些:

static void engine_draw_frame(struct engine* engine) {
    if (engine->display == NULL) {
        // No display.
        return;
    }

    // Just fill the screen with a color.
    glClearColor(((float)engine->state.x)/engine->width, engine->state.angle,
            ((float)engine->state.y)/engine->height, 1);
    glClear(GL_COLOR_BUFFER_BIT);

    eglSwapBuffers(engine->display, engine->surface);
}

小结一下

上面的例子,除去了OpenGL的知识以外,我们不需要知道任何跟Android系统相关的知识。
别小看了这段小小的代码,在gomobile的支持下,它可是跨平台的哟。

下一期,我们讨论更加激动人心的话题,如何从Android的Java代码调用Go的代码。

目录
相关文章
|
存储 Android开发
如何查看Flutter应用在Android设备上已被撤销的权限?
如何查看Flutter应用在Android设备上已被撤销的权限?
983 64
|
人工智能 监控 安全
Go通道机制与应用详解
本文全面解析了Go语言中的通道(Channel),从基础概念到高级应用,涵盖创建、操作、垃圾回收及实际场景使用。通道作为Go并发模型的核心,支持协程间安全高效的数据通信与同步。文章介绍了无缓冲和有缓冲通道的特性,以及发送、接收、关闭等操作,并探讨了`select`语句、超时处理、遍历通道等高级用法。此外,还深入分析了通道的垃圾回收机制,包括引用计数、生命周期管理和循环引用问题。最后通过数据流处理、任务调度和状态监控等实例,展示了通道在实际开发中的广泛应用。理解通道不仅有助于构建高并发系统,还能优化资源管理,提升程序性能。
552 31
|
消息中间件 缓存 NoSQL
Redis各类数据结构详细介绍及其在Go语言Gin框架下实践应用
这只是利用Go语言和Gin框架与Redis交互最基础部分展示;根据具体业务需求可能需要更复杂查询、事务处理或订阅发布功能实现更多高级特性应用场景。
722 86
|
运维 监控 算法
监控局域网其他电脑:Go 语言迪杰斯特拉算法的高效应用
在信息化时代,监控局域网成为网络管理与安全防护的关键需求。本文探讨了迪杰斯特拉(Dijkstra)算法在监控局域网中的应用,通过计算最短路径优化数据传输和故障检测。文中提供了使用Go语言实现的代码例程,展示了如何高效地进行网络监控,确保局域网的稳定运行和数据安全。迪杰斯特拉算法能减少传输延迟和带宽消耗,及时发现并处理网络故障,适用于复杂网络环境下的管理和维护。
|
监控 Java Go
无感改造,完美监控:Docker 多阶段构建 Go 应用无侵入观测
本文将介绍一种基于 Docker 多阶段构建的无侵入 Golang 应用观测方法,通过此方法用户无需对 Golang 应用源代码或者编译指令做任何改造,即可零成本为 Golang 应用注入可观测能力。
860 85
|
Java Shell Maven
【Azure Container App】构建Java应用镜像时候遇无法编译错误:ERROR [build 10/10] RUN ./mvnw.cmd dependency:go-offline -B -Dproduction package
在部署Java应用到Azure Container App时,构建镜像过程中出现错误:“./mvnw.cmd: No such file or directory”。尽管项目根目录包含mvnw和mvnw.cmd文件,但依然报错。问题出现在Dockerfile构建阶段执行`./mvnw dependency:go-offline`命令时,系统提示找不到可执行文件。经过排查,确认是mvnw文件内容异常所致。最终通过重新生成mvnw文件解决该问题,镜像成功构建。
865 1
|
人工智能 Go
GO语言之泛型应用
本文介绍了Go语言中泛型的使用,包括为何引入泛型、泛型语法详解以及如何自定义约束。通过实例展示了泛型在简化代码、提高复用性方面的优势,并演示了泛型在slice、指针、map等数据类型中的应用。
348 1
|
存储 监控 算法
公司员工泄密防护体系中跳表数据结构及其 Go 语言算法的应用研究
在数字化办公中,企业面临员工泄密风险。本文探讨使用跳表(Skip List)数据结构优化泄密防护系统,提升敏感数据监测效率。跳表以其高效的动态数据处理能力,为企业信息安全管理提供了可靠技术支持。
321 0
|
存储 缓存 监控
企业监控软件中 Go 语言哈希表算法的应用研究与分析
在数字化时代,企业监控软件对企业的稳定运营至关重要。哈希表(散列表)作为高效的数据结构,广泛应用于企业监控中,如设备状态管理、数据分类和缓存机制。Go 语言中的 map 实现了哈希表,能快速处理海量监控数据,确保实时准确反映设备状态,提升系统性能,助力企业实现智能化管理。
405 3
|
监控 前端开发 编译器
1 行命令引发的 Go 应用崩溃
1 行命令引发的 Go 应用崩溃
342 0
1 行命令引发的 Go 应用崩溃

热门文章

最新文章