安装 gomobile:
go get golang.org/x/mobile/cmd/gomobile
安装不上的可以设置国内的 Go 代理:
go env -w GOPROXY=https://goproxy.cn,direct
package hello
import "fmt"
func Hello(name string) string {
return fmt.Sprintf("Hello %s!", name)
}
21.4.7075529
,CMake 下载最新版本就可以。然后配置环境变量:
export ANDROID_HOME=~/Library/Android/sdk
export ANDROID_NDK_HOME=~/Library/Android/sdk/ndk/21.4.7075529
然后在 hello 项目的上一级目录执行以下命令:
hello 是 go 项目的目录
gomobile bind -target=android hello
hello.aar
hello-sources.jar
import hello.Hello;
public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
// 省略无关代码
fab.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// 在这里调用 hello 方法
Snackbar.make(view, Hello.hello("ray"), Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
}
同样在项目的上级目录执行下面的命令:
hello 是 go 项目的目录
gomobile bind -target=ios hello
如果出现这个错误:
gomobile: -target=ios requires XCode
到 xcode 中配置一下 Command Line Tools:
struct ContentView: View {
var body: some View {
// 在这里调用 hello 方法
Text(HelloHello("ray"))
.padding()
}
}
文 / Rayjun