Skip to content

Add Android example #137

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 8, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions examples-android/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
.gradle/
.idea/
build/
*.iml
/local.properties
/gradle.properties
1 change: 1 addition & 0 deletions examples-android/Procfile
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
web: server/build/install/server/bin/server
67 changes: 67 additions & 0 deletions examples-android/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# gRPC Kotlin Android Sample

## Run Server Locally:

Run the server:
```
./gradlew -t :server:run
```

## Deploy and Run Server on Cloud Run:

[![Run on Google Cloud](https://deploy.cloud.run/button.png)](https://deploy.cloud.run/?cloudshell_context=cloudrun-gbp)

## Run the Client:

1. [Download Android Command Line Tools](https://developer.android.com/studio)

1. Install the SDK:
```
mkdir android-sdk
cd android-sdk
unzip PATH_TO_SDK_ZIP/sdk-tools-linux-VERSION.zip
tools/bin/sdkmanager --update
tools/bin/sdkmanager "platforms;android-29" "build-tools;29.0.3" "extras;google;m2repository" "extras;android;m2repository"
tools/bin/sdkmanager --licenses
```

1. Set an env var pointing to the `android-sdk`
```
export ANDROID_HOME=PATH_TO_SDK/android-sdk
```

1. Run the build from this project's dir:
```
./gradlew :android:build
```

1. You can either run on an emulator or a physical device and you can either connect to the server running on your local machine, or connect to a server you deployed on the cloud.

* Emulator + Local Server:
* From the command line:
```
./gradlew :android:installDebug
```
* From Android Studio / IntelliJ, navigate to `android/src/main/kotlin/io/grpc/examples/helloworld` and right-click on `MainActivity` and select `Run`.

* Physical Device + Local Server:
* From the command line:
1. [Setup adb](https://developer.android.com/studio/run/device)
1. `./gradlew :android:installDebug -PserverUrl=http://YOUR_MACHINE_IP:50051/`
* From Android Studio / IntelliJ:
1. Create a `gradle.properties` file in your root project directory containing:
```
serverUrl=http://YOUR_MACHINE_IP:50051/
```
1. Navigate to `android/src/main/kotlin/io/grpc/examples/helloworld` and right-click on `MainActivity` and select `Run`.

* Emulator or Physical Device + Cloud:
* From the command line:
1. [setup adb](https://developer.android.com/studio/run/device)
1. `./gradlew :android:installDebug -PserverUrl=https://YOUR_SERVER/`
* From Android Studio / IntelliJ:
1. Create a `gradle.properties` file in your root project directory containing:
```
serverUrl=https://YOUR_SERVER/
```
1. Navigate to `android/src/main/kotlin/io/grpc/examples/helloworld` and right-click on `MainActivity` and select `Run`.
39 changes: 39 additions & 0 deletions examples-android/android/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
plugins {
id("com.android.application")
kotlin("android")
}

dependencies {
implementation(kotlin("stdlib"))
implementation("androidx.appcompat:appcompat:1.1.0")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.7")
implementation(project(":common"))
runtimeOnly("io.grpc:grpc-okhttp:${rootProject.ext["grpcVersion"]}")
}

android {
compileSdkVersion(29)
buildToolsVersion = "29.0.3"

defaultConfig {
applicationId = "io.grpc.examples.hello"
minSdkVersion(23)
targetSdkVersion(29)
versionCode = 1
versionName = "1.0"

val serverUrl: String? by project
if (serverUrl != null) {
resValue("string", "server_url", serverUrl!!)
} else {
resValue("string", "server_url", "http://10.0.2.2:50051/")
}
}

sourceSets["main"].java.srcDir("src/main/kotlin")

compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7
}
}
1 change: 1 addition & 0 deletions examples-android/android/gradle.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
android.useAndroidX=true
21 changes: 21 additions & 0 deletions examples-android/android/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="io.grpc.examples.helloworld">

<uses-permission android:name="android.permission.INTERNET"/>

<application
android:allowBackup="true"
android:fullBackupContent="true"
android:icon="@android:drawable/btn_star"
android:label="@string/app_label">
<activity
android:theme="@style/Theme.AppCompat.NoActionBar"
android:name="io.grpc.examples.helloworld.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>

</manifest>
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package io.grpc.examples.helloworld

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.KeyEvent
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import io.grpc.ManagedChannel
import io.grpc.ManagedChannelBuilder
import java.net.URL
import java.util.logging.Logger
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.asExecutor
import kotlinx.coroutines.runBlocking

// todo: suspend funs
class MainActivity : AppCompatActivity() {
private val logger = Logger.getLogger(this.javaClass.name)

private fun channel(): ManagedChannel {
val url = URL(resources.getString(R.string.server_url))
val port = if (url.port == -1) url.defaultPort else url.port

logger.info("Connecting to ${url.host}:$port")

val builder = ManagedChannelBuilder.forAddress(url.host, port)
if (url.protocol == "https") {
builder.useTransportSecurity()
} else {
builder.usePlaintext()
}

return builder.executor(Dispatchers.Default.asExecutor()).build()
}

// lazy otherwise resources is null
private val greeter by lazy { GreeterGrpcKt.GreeterCoroutineStub(channel()) }

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val button = findViewById<Button>(R.id.button)

val nameText = findViewById<EditText>(R.id.name)
nameText.addTextChangedListener(object : TextWatcher {
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
button.isEnabled = s.isNotEmpty()
}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) { }
override fun afterTextChanged(s: Editable) { }
})

val responseText = findViewById<TextView>(R.id.response)

fun sendReq() = runBlocking {
try {
val request = HelloRequest.newBuilder().setName(nameText.text.toString()).build()
val response = greeter.sayHello(request)
responseText.text = "Server says: " + response.getMessage()
} catch (e: Exception) {
responseText.text = "Server error: " + e.message
e.printStackTrace()
}
}

button.setOnClickListener {
sendReq()
}

nameText.setOnKeyListener { _, keyCode, event ->
if ((event.action == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
sendReq()
true
} else {
false
}
}
}
}
28 changes: 28 additions & 0 deletions examples-android/android/src/main/res/layout/activity_main.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center_horizontal"
tools:context="io.grpc.examples.helloworld.MainActivity">

<EditText android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:hint="@string/name_hint"
android:autofillHints="name"/>

<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/say_hello"
android:enabled="false"/>

<TextView android:id="@+id/response"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

</LinearLayout>
6 changes: 6 additions & 0 deletions examples-android/android/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="name_hint">name</string>
<string name="say_hello">say hello</string>
<string name="app_label">gRPC Kotlin Android</string>
</resources>
32 changes: 32 additions & 0 deletions examples-android/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
buildscript {
repositories {
gradlePluginPortal()
google()
}
dependencies {
classpath("com.android.tools.build:gradle:3.6.3")
}
}

plugins {
kotlin("jvm") version "1.3.72"
id("org.jlleitschuh.gradle.ktlint") version "9.2.1"
}

// todo: move to subprojects, but how?
ext["grpcVersion"] = "1.30.0"
ext["grpcKotlinVersion"] = "0.1.3"
ext["protobufVersion"] = "3.12.2"

allprojects {
repositories {
mavenLocal()
mavenCentral()
jcenter()
google()
}

apply(plugin = "org.jlleitschuh.gradle.ktlint")
}

tasks.replace("assemble").dependsOn(":server:installDist")
56 changes: 56 additions & 0 deletions examples-android/common/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import com.google.protobuf.gradle.generateProtoTasks
import com.google.protobuf.gradle.id
import com.google.protobuf.gradle.ofSourceSet
import com.google.protobuf.gradle.plugins
import com.google.protobuf.gradle.protobuf
import com.google.protobuf.gradle.protoc

plugins {
kotlin("jvm")
id("com.google.protobuf") version "0.8.12"
}

dependencies {
implementation(kotlin("stdlib"))
implementation("javax.annotation:javax.annotation-api:1.3.2")
api("io.grpc:grpc-protobuf-lite:${rootProject.ext["grpcVersion"]}")
api("io.grpc:grpc-stub:${rootProject.ext["grpcVersion"]}")
api("io.grpc:grpc-kotlin-stub:${rootProject.ext["grpcKotlinVersion"]}") {
exclude("io.grpc", "grpc-protobuf")
}
}

java {
sourceCompatibility = JavaVersion.VERSION_1_7
}

protobuf {
protoc {
artifact = "com.google.protobuf:protoc:${rootProject.ext["protobufVersion"]}"
}
plugins {
id("grpc") {
artifact = "io.grpc:protoc-gen-grpc-java:${rootProject.ext["grpcVersion"]}"
}
id("grpckt") {
artifact = "io.grpc:protoc-gen-grpc-kotlin:${rootProject.ext["grpcKotlinVersion"]}"
}
}
generateProtoTasks {
ofSourceSet("main").forEach {
it.builtins {
named("java") {
option("lite")
}
}
it.plugins {
id("grpc") {
option("lite")
}
id("grpckt") {
option("lite")
}
}
}
}
}
37 changes: 37 additions & 0 deletions examples-android/common/src/main/proto/helloworld.proto
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
syntax = "proto3";

option java_multiple_files = true;
option java_package = "io.grpc.examples.helloworld";
option java_outer_classname = "HelloWorldProto";
option objc_class_prefix = "HLW";

package helloworld;

// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {}
}

// The request message containing the user's name.
message HelloRequest {
string name = 1;
}

// The response message containing the greetings
message HelloReply {
string message = 1;
}
Binary file not shown.
5 changes: 5 additions & 0 deletions examples-android/gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Loading