diff options
author | Eric Gribkoff <ericgribkoff@google.com> | 2018-01-30 12:16:30 -0800 |
---|---|---|
committer | GitHub <noreply@github.com> | 2018-01-30 12:16:30 -0800 |
commit | 0373706b03e3f8620ab9a93543ee4fa11aba1687 (patch) | |
tree | 639418a366dd79e04110edc95de7979303ab6c0c /examples | |
parent | 47019325dbd6010522dc55cc31aa729d2b77d6cd (diff) | |
download | grpc-grpc-java-0373706b03e3f8620ab9a93543ee4fa11aba1687.tar.gz |
examples: update Android examples
Updates include:
* Build file and dependency updates
* Correcting the gradle wrapper for the clientcache example
* Lint fixes (including making AsyncTask subclasses static)
* Dropping the m-prefix from member variables
* Fixing the code indentation
* Fixing and enabling proguard for the routeguide example.
Diffstat (limited to 'examples')
16 files changed, 536 insertions, 479 deletions
diff --git a/examples/android/clientcache/app/build.gradle b/examples/android/clientcache/app/build.gradle index 5c0c647dc..6d4f3659d 100644 --- a/examples/android/clientcache/app/build.gradle +++ b/examples/android/clientcache/app/build.gradle @@ -2,26 +2,28 @@ apply plugin: 'com.android.application' apply plugin: 'com.google.protobuf' android { - compileSdkVersion 25 - buildToolsVersion "25.0.2" + compileSdkVersion 27 defaultConfig { applicationId "io.grpc.android.clientcacheexample" minSdkVersion 19 - targetSdkVersion 25 + targetSdkVersion 27 multiDexEnabled true versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { + debug { + minifyEnabled false + } release { minifyEnabled true proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } lintOptions { - disable 'InvalidPackage', 'HardcodedText' + disable 'GoogleAppIndexingWarning', 'HardcodedText', 'InvalidPackage' textReport true textOutput "stdout" } @@ -53,7 +55,7 @@ protobuf { } dependencies { - compile 'com.android.support:appcompat-v7:25.0.0' + compile 'com.android.support:appcompat-v7:27.0.2' // You need to build grpc-java to obtain these libraries below. compile 'io.grpc:grpc-okhttp:1.9.0-SNAPSHOT' // CURRENT_GRPC_VERSION @@ -62,6 +64,6 @@ dependencies { compile 'javax.annotation:javax.annotation-api:1.2' testCompile 'junit:junit:4.12' - testCompile 'com.google.truth:truth:0.28' + testCompile 'com.google.truth:truth:0.36' testCompile 'io.grpc:grpc-testing:1.9.0-SNAPSHOT' } diff --git a/examples/android/clientcache/app/src/main/AndroidManifest.xml b/examples/android/clientcache/app/src/main/AndroidManifest.xml index d31cbd940..6fc8e940d 100644 --- a/examples/android/clientcache/app/src/main/AndroidManifest.xml +++ b/examples/android/clientcache/app/src/main/AndroidManifest.xml @@ -5,7 +5,7 @@ <uses-permission android:name="android.permission.INTERNET" /> <application - android:allowBackup="true" + android:allowBackup="false" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/Base.V7.Theme.AppCompat.Light" > diff --git a/examples/android/clientcache/app/src/main/java/io/grpc/clientcacheexample/ClientCacheExampleActivity.java b/examples/android/clientcache/app/src/main/java/io/grpc/clientcacheexample/ClientCacheExampleActivity.java index 831c1030a..036e3019f 100644 --- a/examples/android/clientcache/app/src/main/java/io/grpc/clientcacheexample/ClientCacheExampleActivity.java +++ b/examples/android/clientcache/app/src/main/java/io/grpc/clientcacheexample/ClientCacheExampleActivity.java @@ -16,6 +16,7 @@ package io.grpc.clientcacheexample; +import android.app.Activity; import android.content.Context; import android.os.AsyncTask; import android.os.Bundle; @@ -41,16 +42,17 @@ import io.grpc.examples.helloworld.HelloRequest; import io.grpc.stub.ClientCalls; import java.io.PrintWriter; import java.io.StringWriter; +import java.lang.ref.WeakReference; import java.util.concurrent.TimeUnit; public final class ClientCacheExampleActivity extends AppCompatActivity { private static final int CACHE_SIZE_IN_BYTES = 1 * 1024 * 1024; // 1MB private static final String TAG = "grpcCacheExample"; - private Button mSendButton; - private EditText mHostEdit; - private EditText mPortEdit; - private EditText mMessageEdit; - private TextView mResultText; + private Button sendButton; + private EditText hostEdit; + private EditText portEdit; + private EditText messageEdit; + private TextView resultText; private CheckBox getCheckBox; private CheckBox noCacheCheckBox; private CheckBox onlyIfCachedCheckBox; @@ -60,70 +62,79 @@ public final class ClientCacheExampleActivity extends AppCompatActivity { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_clientcacheexample); - mSendButton = (Button) findViewById(R.id.send_button); - mHostEdit = (EditText) findViewById(R.id.host_edit_text); - mPortEdit = (EditText) findViewById(R.id.port_edit_text); - mMessageEdit = (EditText) findViewById(R.id.message_edit_text); + sendButton = (Button) findViewById(R.id.send_button); + hostEdit = (EditText) findViewById(R.id.host_edit_text); + portEdit = (EditText) findViewById(R.id.port_edit_text); + messageEdit = (EditText) findViewById(R.id.message_edit_text); getCheckBox = (CheckBox) findViewById(R.id.get_checkbox); noCacheCheckBox = (CheckBox) findViewById(R.id.no_cache_checkbox); onlyIfCachedCheckBox = (CheckBox) findViewById(R.id.only_if_cached_checkbox); - mResultText = (TextView) findViewById(R.id.grpc_response_text); - mResultText.setMovementMethod(new ScrollingMovementMethod()); - + resultText = (TextView) findViewById(R.id.grpc_response_text); + resultText.setMovementMethod(new ScrollingMovementMethod()); cache = SafeMethodCachingInterceptor.newLruCache(CACHE_SIZE_IN_BYTES); } /** Sends RPC. Invoked when app button is pressed. */ public void sendMessage(View view) { ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)) - .hideSoftInputFromWindow(mHostEdit.getWindowToken(), 0); - mSendButton.setEnabled(false); - new GrpcTask().execute(); + .hideSoftInputFromWindow(hostEdit.getWindowToken(), 0); + sendButton.setEnabled(false); + resultText.setText(""); + new GrpcTask(this, cache) + .execute( + hostEdit.getText().toString(), + messageEdit.getText().toString(), + portEdit.getText().toString(), + getCheckBox.isChecked(), + noCacheCheckBox.isChecked(), + onlyIfCachedCheckBox.isChecked()); } - private class GrpcTask extends AsyncTask<Void, Void, String> { - private String host; - private String message; - private int port; + private static class GrpcTask extends AsyncTask<Object, Void, String> { + private final WeakReference<Activity> activityReference; + private final SafeMethodCachingInterceptor.Cache cache; private ManagedChannel channel; - @Override - protected void onPreExecute() { - host = mHostEdit.getText().toString(); - message = mMessageEdit.getText().toString(); - String portStr = mPortEdit.getText().toString(); - port = TextUtils.isEmpty(portStr) ? 0 : Integer.valueOf(portStr); - mResultText.setText(""); + private GrpcTask(Activity activity, SafeMethodCachingInterceptor.Cache cache) { + this.activityReference = new WeakReference<Activity>(activity); + this.cache = cache; } @Override - protected String doInBackground(Void... nothing) { + protected String doInBackground(Object... params) { + String host = (String) params[0]; + String message = (String) params[1]; + String portStr = (String) params[2]; + boolean useGet = (boolean) params[3]; + boolean noCache = (boolean) params[4]; + boolean onlyIfCached = (boolean) params[5]; + int port = TextUtils.isEmpty(portStr) ? 0 : Integer.valueOf(portStr); try { channel = ManagedChannelBuilder.forAddress(host, port).usePlaintext(true).build(); Channel channelToUse = ClientInterceptors.intercept( channel, SafeMethodCachingInterceptor.newSafeMethodCachingInterceptor(cache)); - HelloRequest message = HelloRequest.newBuilder().setName(this.message).build(); + HelloRequest request = HelloRequest.newBuilder().setName(message).build(); HelloReply reply; - if (getCheckBox.isChecked()) { + if (useGet) { MethodDescriptor<HelloRequest, HelloReply> safeCacheableUnaryCallMethod = GreeterGrpc.getSayHelloMethod().toBuilder().setSafe(true).build(); CallOptions callOptions = CallOptions.DEFAULT; - if (noCacheCheckBox.isChecked()) { + if (noCache) { callOptions = callOptions.withOption(SafeMethodCachingInterceptor.NO_CACHE_CALL_OPTION, true); } - if (onlyIfCachedCheckBox.isChecked()) { + if (onlyIfCached) { callOptions = callOptions.withOption( SafeMethodCachingInterceptor.ONLY_IF_CACHED_CALL_OPTION, true); } reply = ClientCalls.blockingUnaryCall( - channelToUse, safeCacheableUnaryCallMethod, callOptions, message); + channelToUse, safeCacheableUnaryCallMethod, callOptions, request); } else { GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(channelToUse); - reply = stub.sayHello(message); + reply = stub.sayHello(request); } return reply.getMessage(); } catch (Exception e) { @@ -145,8 +156,14 @@ public final class ClientCacheExampleActivity extends AppCompatActivity { Thread.currentThread().interrupt(); } } - mResultText.setText(result); - mSendButton.setEnabled(true); + Activity activity = activityReference.get(); + if (activity == null) { + return; + } + TextView resultText = (TextView) activity.findViewById(R.id.grpc_response_text); + Button sendButton = (Button) activity.findViewById(R.id.send_button); + resultText.setText(result); + sendButton.setEnabled(true); } } } diff --git a/examples/android/clientcache/app/src/main/java/io/grpc/clientcacheexample/SafeMethodCachingInterceptor.java b/examples/android/clientcache/app/src/main/java/io/grpc/clientcacheexample/SafeMethodCachingInterceptor.java index 4ae0c01c5..6dfc6d48d 100644 --- a/examples/android/clientcache/app/src/main/java/io/grpc/clientcacheexample/SafeMethodCachingInterceptor.java +++ b/examples/android/clientcache/app/src/main/java/io/grpc/clientcacheexample/SafeMethodCachingInterceptor.java @@ -14,6 +14,7 @@ import io.grpc.ForwardingClientCallListener; import io.grpc.Metadata; import io.grpc.MethodDescriptor; import io.grpc.Status; +import java.util.Locale; import java.util.Objects; import java.util.concurrent.TimeUnit; @@ -199,7 +200,7 @@ final class SafeMethodCachingInterceptor implements ClientInterceptor { } else if (directive.equalsIgnoreCase("no-transform")) { cacheResponse = false; break; - } else if (directive.toLowerCase().startsWith("max-age")) { + } else if (directive.toLowerCase(Locale.US).startsWith("max-age")) { String[] parts = directive.split("="); if (parts.length == 2) { try { diff --git a/examples/android/clientcache/build.gradle b/examples/android/clientcache/build.gradle index 6f6011c3c..506cf47e7 100644 --- a/examples/android/clientcache/build.gradle +++ b/examples/android/clientcache/build.gradle @@ -2,10 +2,11 @@ buildscript { repositories { + google() jcenter() } dependencies { - classpath 'com.android.tools.build:gradle:2.3.1' + classpath 'com.android.tools.build:gradle:3.0.1' classpath "com.google.protobuf:protobuf-gradle-plugin:0.8.3" // NOTE: Do not place your application dependencies here; they belong @@ -15,6 +16,7 @@ buildscript { allprojects { repositories { + google() jcenter() mavenLocal() } diff --git a/examples/android/helloworld/app/build.gradle b/examples/android/helloworld/app/build.gradle index 19aa25668..9a3ed0c3a 100644 --- a/examples/android/helloworld/app/build.gradle +++ b/examples/android/helloworld/app/build.gradle @@ -2,25 +2,27 @@ apply plugin: 'com.android.application' apply plugin: 'com.google.protobuf' android { - compileSdkVersion 22 - buildToolsVersion "25.0.2" + compileSdkVersion 27 defaultConfig { applicationId "io.grpc.android.helloworldexample" // API level 14+ is required for TLS since Google Play Services v10.2 minSdkVersion 14 - targetSdkVersion 22 + targetSdkVersion 27 versionCode 1 versionName "1.0" } buildTypes { + debug { + minifyEnabled false + } release { minifyEnabled true proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } lintOptions { - disable 'InvalidPackage', 'HardcodedText' + disable 'GoogleAppIndexingWarning', 'HardcodedText', 'InvalidPackage' textReport true textOutput "stdout" } @@ -52,7 +54,7 @@ protobuf { } dependencies { - compile 'com.android.support:appcompat-v7:22.1.1' + compile 'com.android.support:appcompat-v7:27.0.2' // You need to build grpc-java to obtain these libraries below. compile 'io.grpc:grpc-okhttp:1.10.0-SNAPSHOT' // CURRENT_GRPC_VERSION diff --git a/examples/android/helloworld/app/src/main/AndroidManifest.xml b/examples/android/helloworld/app/src/main/AndroidManifest.xml index 8c40f1168..eee4057cd 100644 --- a/examples/android/helloworld/app/src/main/AndroidManifest.xml +++ b/examples/android/helloworld/app/src/main/AndroidManifest.xml @@ -5,7 +5,7 @@ <uses-permission android:name="android.permission.INTERNET" /> <application - android:allowBackup="true" + android:allowBackup="false" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/Base.V7.Theme.AppCompat.Light" > diff --git a/examples/android/helloworld/app/src/main/java/io/grpc/helloworldexample/HelloworldActivity.java b/examples/android/helloworld/app/src/main/java/io/grpc/helloworldexample/HelloworldActivity.java index 6a1628b69..ef730931c 100644 --- a/examples/android/helloworld/app/src/main/java/io/grpc/helloworldexample/HelloworldActivity.java +++ b/examples/android/helloworld/app/src/main/java/io/grpc/helloworldexample/HelloworldActivity.java @@ -16,6 +16,7 @@ package io.grpc.helloworldexample; +import android.app.Activity; import android.content.Context; import android.os.AsyncTask; import android.os.Bundle; @@ -27,86 +28,91 @@ import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; - import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import io.grpc.examples.helloworld.GreeterGrpc; import io.grpc.examples.helloworld.HelloReply; import io.grpc.examples.helloworld.HelloRequest; - import java.io.PrintWriter; import java.io.StringWriter; +import java.lang.ref.WeakReference; import java.util.concurrent.TimeUnit; public class HelloworldActivity extends AppCompatActivity { - private Button mSendButton; - private EditText mHostEdit; - private EditText mPortEdit; - private EditText mMessageEdit; - private TextView mResultText; + private Button sendButton; + private EditText hostEdit; + private EditText portEdit; + private EditText messageEdit; + private TextView resultText; - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_helloworld); - mSendButton = (Button) findViewById(R.id.send_button); - mHostEdit = (EditText) findViewById(R.id.host_edit_text); - mPortEdit = (EditText) findViewById(R.id.port_edit_text); - mMessageEdit = (EditText) findViewById(R.id.message_edit_text); - mResultText = (TextView) findViewById(R.id.grpc_response_text); - mResultText.setMovementMethod(new ScrollingMovementMethod()); - } + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_helloworld); + sendButton = (Button) findViewById(R.id.send_button); + hostEdit = (EditText) findViewById(R.id.host_edit_text); + portEdit = (EditText) findViewById(R.id.port_edit_text); + messageEdit = (EditText) findViewById(R.id.message_edit_text); + resultText = (TextView) findViewById(R.id.grpc_response_text); + resultText.setMovementMethod(new ScrollingMovementMethod()); + } - public void sendMessage(View view) { - ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)) - .hideSoftInputFromWindow(mHostEdit.getWindowToken(), 0); - mSendButton.setEnabled(false); - new GrpcTask().execute(); - } + public void sendMessage(View view) { + ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)) + .hideSoftInputFromWindow(hostEdit.getWindowToken(), 0); + sendButton.setEnabled(false); + resultText.setText(""); + new GrpcTask(this) + .execute( + hostEdit.getText().toString(), + messageEdit.getText().toString(), + portEdit.getText().toString()); + } - private class GrpcTask extends AsyncTask<Void, Void, String> { - private String mHost; - private String mMessage; - private int mPort; - private ManagedChannel mChannel; + private static class GrpcTask extends AsyncTask<String, Void, String> { + private final WeakReference<Activity> activityReference; + private ManagedChannel channel; - @Override - protected void onPreExecute() { - mHost = mHostEdit.getText().toString(); - mMessage = mMessageEdit.getText().toString(); - String portStr = mPortEdit.getText().toString(); - mPort = TextUtils.isEmpty(portStr) ? 0 : Integer.valueOf(portStr); - mResultText.setText(""); - } + private GrpcTask(Activity activity) { + this.activityReference = new WeakReference<Activity>(activity); + } - @Override - protected String doInBackground(Void... nothing) { - try { - mChannel = ManagedChannelBuilder.forAddress(mHost, mPort) - .usePlaintext(true) - .build(); - GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(mChannel); - HelloRequest message = HelloRequest.newBuilder().setName(mMessage).build(); - HelloReply reply = stub.sayHello(message); - return reply.getMessage(); - } catch (Exception e) { - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); - e.printStackTrace(pw); - pw.flush(); - return String.format("Failed... : %n%s", sw); - } - } + @Override + protected String doInBackground(String... params) { + String host = params[0]; + String message = params[1]; + String portStr = params[2]; + int port = TextUtils.isEmpty(portStr) ? 0 : Integer.valueOf(portStr); + try { + channel = ManagedChannelBuilder.forAddress(host, port).usePlaintext(true).build(); + GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(channel); + HelloRequest request = HelloRequest.newBuilder().setName(message).build(); + HelloReply reply = stub.sayHello(request); + return reply.getMessage(); + } catch (Exception e) { + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + e.printStackTrace(pw); + pw.flush(); + return String.format("Failed... : %n%s", sw); + } + } - @Override - protected void onPostExecute(String result) { - try { - mChannel.shutdown().awaitTermination(1, TimeUnit.SECONDS); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - mResultText.setText(result); - mSendButton.setEnabled(true); - } + @Override + protected void onPostExecute(String result) { + try { + channel.shutdown().awaitTermination(1, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + Activity activity = activityReference.get(); + if (activity == null) { + return; + } + TextView resultText = (TextView) activity.findViewById(R.id.grpc_response_text); + Button sendButton = (Button) activity.findViewById(R.id.send_button); + resultText.setText(result); + sendButton.setEnabled(true); } + } } diff --git a/examples/android/helloworld/build.gradle b/examples/android/helloworld/build.gradle index 6f6011c3c..506cf47e7 100644 --- a/examples/android/helloworld/build.gradle +++ b/examples/android/helloworld/build.gradle @@ -2,10 +2,11 @@ buildscript { repositories { + google() jcenter() } dependencies { - classpath 'com.android.tools.build:gradle:2.3.1' + classpath 'com.android.tools.build:gradle:3.0.1' classpath "com.google.protobuf:protobuf-gradle-plugin:0.8.3" // NOTE: Do not place your application dependencies here; they belong @@ -15,6 +16,7 @@ buildscript { allprojects { repositories { + google() jcenter() mavenLocal() } diff --git a/examples/android/routeguide/app/build.gradle b/examples/android/routeguide/app/build.gradle index ed64a83d6..239291399 100644 --- a/examples/android/routeguide/app/build.gradle +++ b/examples/android/routeguide/app/build.gradle @@ -2,24 +2,28 @@ apply plugin: 'com.android.application' apply plugin: 'com.google.protobuf' android { - compileSdkVersion 23 - buildToolsVersion "25.0.2" + compileSdkVersion 27 defaultConfig { applicationId "io.grpc.routeguideexample" - minSdkVersion 23 - targetSdkVersion 23 + minSdkVersion 14 + targetSdkVersion 27 versionCode 1 versionName "1.0" } buildTypes { - release { + debug { minifyEnabled false + } + release { + minifyEnabled true proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } lintOptions { - disable 'InvalidPackage' + disable 'GoogleAppIndexingWarning', 'HardcodedText', 'InvalidPackage' + textReport true + textOutput "stdout" } } @@ -49,7 +53,7 @@ protobuf { } dependencies { - compile 'com.android.support:appcompat-v7:23.+' + compile 'com.android.support:appcompat-v7:27.0.2' // You need to build grpc-java to obtain these libraries below. compile 'io.grpc:grpc-okhttp:1.10.0-SNAPSHOT' // CURRENT_GRPC_VERSION diff --git a/examples/android/routeguide/app/proguard-rules.pro b/examples/android/routeguide/app/proguard-rules.pro index e356773f2..8f066eb50 100644 --- a/examples/android/routeguide/app/proguard-rules.pro +++ b/examples/android/routeguide/app/proguard-rules.pro @@ -11,6 +11,7 @@ -dontwarn sun.misc.Unsafe -dontwarn com.google.common.** +-dontwarn javax.naming.** -dontwarn okio.** # Ignores: can't find referenced class javax.lang.model.element.Modifier -dontwarn com.google.errorprone.annotations.** diff --git a/examples/android/routeguide/app/src/main/AndroidManifest.xml b/examples/android/routeguide/app/src/main/AndroidManifest.xml index d557afc08..f7409758a 100644 --- a/examples/android/routeguide/app/src/main/AndroidManifest.xml +++ b/examples/android/routeguide/app/src/main/AndroidManifest.xml @@ -3,7 +3,7 @@ <uses-permission android:name="android.permission.INTERNET" /> - <application android:allowBackup="true" + <application android:allowBackup="false" android:label="@string/app_name" android:icon="@mipmap/ic_launcher" android:supportsRtl="true" diff --git a/examples/android/routeguide/app/src/main/java/io/grpc/routeguideexample/RouteGuideActivity.java b/examples/android/routeguide/app/src/main/java/io/grpc/routeguideexample/RouteGuideActivity.java index 8edb33fd1..0d090ac9a 100644 --- a/examples/android/routeguide/app/src/main/java/io/grpc/routeguideexample/RouteGuideActivity.java +++ b/examples/android/routeguide/app/src/main/java/io/grpc/routeguideexample/RouteGuideActivity.java @@ -27,18 +27,15 @@ import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; - import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; -import io.grpc.Status; import io.grpc.StatusRuntimeException; import io.grpc.routeguideexample.RouteGuideGrpc.RouteGuideBlockingStub; import io.grpc.routeguideexample.RouteGuideGrpc.RouteGuideStub; import io.grpc.stub.StreamObserver; - -import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; +import java.lang.ref.WeakReference; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Iterator; @@ -46,372 +43,407 @@ import java.util.List; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -import java.util.logging.Level; -import java.util.logging.Logger; public class RouteGuideActivity extends AppCompatActivity { - private static final Logger logger = Logger.getLogger(RouteGuideActivity.class.getName()); - private EditText mHostEdit; - private EditText mPortEdit; - private Button mStartRouteGuideButton; - private Button mExitRouteGuideButton; - private Button mGetFeatureButton; - private Button mListFeaturesButton; - private Button mRecordRouteButton; - private Button mRouteChatButton; - private TextView mResultText; - - private ManagedChannel mChannel; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_routeguide); - mHostEdit = (EditText) findViewById(R.id.host_edit_text); - mPortEdit = (EditText) findViewById(R.id.port_edit_text); - mStartRouteGuideButton = (Button) findViewById(R.id.start_route_guide_button); - mExitRouteGuideButton = (Button) findViewById(R.id.exit_route_guide_button); - mGetFeatureButton = (Button) findViewById(R.id.get_feature_button); - mListFeaturesButton = (Button) findViewById(R.id.list_features_button); - mRecordRouteButton = (Button) findViewById(R.id.record_route_button); - mRouteChatButton = (Button) findViewById(R.id.route_chat_button); - mResultText = (TextView) findViewById(R.id.result_text); - mResultText.setMovementMethod(new ScrollingMovementMethod()); - disableButtons(); - } - - public void startRouteGuide(View view) { - String host = mHostEdit.getText().toString(); - String portStr = mPortEdit.getText().toString(); - int port = TextUtils.isEmpty(portStr) ? 0 : Integer.valueOf(portStr); - ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)) - .hideSoftInputFromWindow(mHostEdit.getWindowToken(), 0); - mChannel = ManagedChannelBuilder.forAddress(host, port).usePlaintext(true).build(); - mHostEdit.setEnabled(false); - mPortEdit.setEnabled(false); - mStartRouteGuideButton.setEnabled(false); - enableButtons(); - } - - public void exitRouteGuide(View view) { - mChannel.shutdown(); - disableButtons(); - mHostEdit.setEnabled(true); - mPortEdit.setEnabled(true); - mStartRouteGuideButton.setEnabled(true); + private EditText hostEdit; + private EditText portEdit; + private Button startRouteGuideButton; + private Button exitRouteGuideButton; + private Button getFeatureButton; + private Button listFeaturesButton; + private Button recordRouteButton; + private Button routeChatButton; + private TextView resultText; + private ManagedChannel channel; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_routeguide); + hostEdit = (EditText) findViewById(R.id.host_edit_text); + portEdit = (EditText) findViewById(R.id.port_edit_text); + startRouteGuideButton = (Button) findViewById(R.id.start_route_guide_button); + exitRouteGuideButton = (Button) findViewById(R.id.exit_route_guide_button); + getFeatureButton = (Button) findViewById(R.id.get_feature_button); + listFeaturesButton = (Button) findViewById(R.id.list_features_button); + recordRouteButton = (Button) findViewById(R.id.record_route_button); + routeChatButton = (Button) findViewById(R.id.route_chat_button); + resultText = (TextView) findViewById(R.id.result_text); + resultText.setMovementMethod(new ScrollingMovementMethod()); + disableButtons(); + } + + public void startRouteGuide(View view) { + String host = hostEdit.getText().toString(); + String portStr = portEdit.getText().toString(); + int port = TextUtils.isEmpty(portStr) ? 0 : Integer.valueOf(portStr); + ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)) + .hideSoftInputFromWindow(hostEdit.getWindowToken(), 0); + channel = ManagedChannelBuilder.forAddress(host, port).usePlaintext(true).build(); + hostEdit.setEnabled(false); + portEdit.setEnabled(false); + startRouteGuideButton.setEnabled(false); + enableButtons(); + } + + public void exitRouteGuide(View view) { + channel.shutdown(); + disableButtons(); + hostEdit.setEnabled(true); + portEdit.setEnabled(true); + startRouteGuideButton.setEnabled(true); + } + + public void getFeature(View view) { + setResultText(""); + disableButtons(); + new GrpcTask(new GetFeatureRunnable(), channel, this).execute(); + } + + public void listFeatures(View view) { + setResultText(""); + disableButtons(); + new GrpcTask(new ListFeaturesRunnable(), channel, this).execute(); + } + + public void recordRoute(View view) { + setResultText(""); + disableButtons(); + new GrpcTask(new RecordRouteRunnable(), channel, this).execute(); + } + + public void routeChat(View view) { + setResultText(""); + disableButtons(); + new GrpcTask(new RouteChatRunnable(), channel, this).execute(); + } + + private void setResultText(String text) { + resultText.setText(text); + } + + private void disableButtons() { + getFeatureButton.setEnabled(false); + listFeaturesButton.setEnabled(false); + recordRouteButton.setEnabled(false); + routeChatButton.setEnabled(false); + exitRouteGuideButton.setEnabled(false); + } + + private void enableButtons() { + exitRouteGuideButton.setEnabled(true); + getFeatureButton.setEnabled(true); + listFeaturesButton.setEnabled(true); + recordRouteButton.setEnabled(true); + routeChatButton.setEnabled(true); + } + + private static class GrpcTask extends AsyncTask<Void, Void, String> { + private final GrpcRunnable grpcRunnable; + private final ManagedChannel channel; + private final WeakReference<RouteGuideActivity> activityReference; + + GrpcTask(GrpcRunnable grpcRunnable, ManagedChannel channel, RouteGuideActivity activity) { + this.grpcRunnable = grpcRunnable; + this.channel = channel; + this.activityReference = new WeakReference<RouteGuideActivity>(activity); } - public void getFeature(View view) { - new GrpcTask(new GetFeatureRunnable()).execute(); + @Override + protected String doInBackground(Void... nothing) { + try { + String logs = + grpcRunnable.run( + RouteGuideGrpc.newBlockingStub(channel), RouteGuideGrpc.newStub(channel)); + return "Success!\n" + logs; + } catch (Exception e) { + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + e.printStackTrace(pw); + pw.flush(); + return "Failed... :\n" + sw; + } } - public void listFeatures(View view) { - new GrpcTask(new ListFeaturesRunnable()).execute(); + @Override + protected void onPostExecute(String result) { + RouteGuideActivity activity = activityReference.get(); + if (activity == null) { + return; + } + activity.setResultText(result); + activity.enableButtons(); } + } - public void recordRoute(View view) { - new GrpcTask(new RecordRouteRunnable()).execute(); + private interface GrpcRunnable { + /** Perform a grpcRunnable and return all the logs. */ + String run(RouteGuideBlockingStub blockingStub, RouteGuideStub asyncStub) throws Exception; + } + + private static class GetFeatureRunnable implements GrpcRunnable { + @Override + public String run(RouteGuideBlockingStub blockingStub, RouteGuideStub asyncStub) + throws Exception { + return getFeature(409146138, -746188906, blockingStub); } - public void routeChat(View view) { - new GrpcTask(new RouteChatRunnable()).execute(); + /** Blocking unary call example. Calls getFeature and prints the response. */ + private String getFeature(int lat, int lon, RouteGuideBlockingStub blockingStub) + throws StatusRuntimeException { + StringBuffer logs = new StringBuffer(); + appendLogs(logs, "*** GetFeature: lat={0} lon={1}", lat, lon); + + Point request = Point.newBuilder().setLatitude(lat).setLongitude(lon).build(); + + Feature feature; + feature = blockingStub.getFeature(request); + if (RouteGuideUtil.exists(feature)) { + appendLogs( + logs, + "Found feature called \"{0}\" at {1}, {2}", + feature.getName(), + RouteGuideUtil.getLatitude(feature.getLocation()), + RouteGuideUtil.getLongitude(feature.getLocation())); + } else { + appendLogs( + logs, + "Found no feature at {0}, {1}", + RouteGuideUtil.getLatitude(feature.getLocation()), + RouteGuideUtil.getLongitude(feature.getLocation())); + } + return logs.toString(); } - - private void disableButtons() { - mGetFeatureButton.setEnabled(false); - mListFeaturesButton.setEnabled(false); - mRecordRouteButton.setEnabled(false); - mRouteChatButton.setEnabled(false); - mExitRouteGuideButton.setEnabled(false); + } + + private static class ListFeaturesRunnable implements GrpcRunnable { + @Override + public String run(RouteGuideBlockingStub blockingStub, RouteGuideStub asyncStub) + throws Exception { + return listFeatures(400000000, -750000000, 420000000, -730000000, blockingStub); } - - private void enableButtons() { - mExitRouteGuideButton.setEnabled(true); - mGetFeatureButton.setEnabled(true); - mListFeaturesButton.setEnabled(true); - mRecordRouteButton.setEnabled(true); - mRouteChatButton.setEnabled(true); + + /** + * Blocking server-streaming example. Calls listFeatures with a rectangle of interest. Prints + * each response feature as it arrives. + */ + private String listFeatures( + int lowLat, int lowLon, int hiLat, int hiLon, RouteGuideBlockingStub blockingStub) + throws StatusRuntimeException { + StringBuffer logs = new StringBuffer("Result: "); + appendLogs( + logs, + "*** ListFeatures: lowLat={0} lowLon={1} hiLat={2} hiLon={3}", + lowLat, + lowLon, + hiLat, + hiLon); + + Rectangle request = + Rectangle.newBuilder() + .setLo(Point.newBuilder().setLatitude(lowLat).setLongitude(lowLon).build()) + .setHi(Point.newBuilder().setLatitude(hiLat).setLongitude(hiLon).build()) + .build(); + Iterator<Feature> features; + features = blockingStub.listFeatures(request); + + while (features.hasNext()) { + Feature feature = features.next(); + appendLogs(logs, feature.toString()); + } + return logs.toString(); } + } - private class GrpcTask extends AsyncTask<Void, Void, String> { - private final GrpcRunnable mGrpc; + private static class RecordRouteRunnable implements GrpcRunnable { + private Throwable failed; - GrpcTask(GrpcRunnable grpc) { - this.mGrpc = grpc; - } + @Override + public String run(RouteGuideBlockingStub blockingStub, RouteGuideStub asyncStub) + throws Exception { + List<Point> points = new ArrayList<Point>(); + points.add(Point.newBuilder().setLatitude(407838351).setLongitude(-746143763).build()); + points.add(Point.newBuilder().setLatitude(408122808).setLongitude(-743999179).build()); + points.add(Point.newBuilder().setLatitude(413628156).setLongitude(-749015468).build()); + return recordRoute(points, 5, asyncStub); + } - @Override - protected void onPreExecute() { - mResultText.setText(""); - disableButtons(); - } + /** + * Async client-streaming example. Sends {@code numPoints} randomly chosen points from {@code + * features} with a variable delay in between. Prints the statistics when they are sent from the + * server. + */ + private String recordRoute(List<Point> points, int numPoints, RouteGuideStub asyncStub) + throws InterruptedException, RuntimeException { + final StringBuffer logs = new StringBuffer(); + appendLogs(logs, "*** RecordRoute"); + + final CountDownLatch finishLatch = new CountDownLatch(1); + StreamObserver<RouteSummary> responseObserver = + new StreamObserver<RouteSummary>() { + @Override + public void onNext(RouteSummary summary) { + appendLogs( + logs, + "Finished trip with {0} points. Passed {1} features. " + + "Travelled {2} meters. It took {3} seconds.", + summary.getPointCount(), + summary.getFeatureCount(), + summary.getDistance(), + summary.getElapsedTime()); + } - @Override - protected String doInBackground(Void... nothing) { - try { - String logs = mGrpc.run(RouteGuideGrpc.newBlockingStub(mChannel), - RouteGuideGrpc.newStub(mChannel)); - return "Success!" + System.lineSeparator() + logs; - } catch (Exception e) { - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); - e.printStackTrace(pw); - pw.flush(); - return "Failed... : " + System.lineSeparator() + sw; + @Override + public void onError(Throwable t) { + failed = t; + finishLatch.countDown(); } - } - @Override - protected void onPostExecute(String result) { - mResultText.setText(result); - enableButtons(); + @Override + public void onCompleted() { + appendLogs(logs, "Finished RecordRoute"); + finishLatch.countDown(); + } + }; + + StreamObserver<Point> requestObserver = asyncStub.recordRoute(responseObserver); + try { + // Send numPoints points randomly selected from the points list. + Random rand = new Random(); + for (int i = 0; i < numPoints; ++i) { + int index = rand.nextInt(points.size()); + Point point = points.get(index); + appendLogs( + logs, + "Visiting point {0}, {1}", + RouteGuideUtil.getLatitude(point), + RouteGuideUtil.getLongitude(point)); + requestObserver.onNext(point); + // Sleep for a bit before sending the next one. + Thread.sleep(rand.nextInt(1000) + 500); + if (finishLatch.getCount() == 0) { + // RPC completed or errored before we finished sending. + // Sending further requests won't error, but they will just be thrown away. + break; + } } + } catch (RuntimeException e) { + // Cancel RPC + requestObserver.onError(e); + throw e; + } + // Mark the end of requests + requestObserver.onCompleted(); + + // Receiving happens asynchronously + if (!finishLatch.await(1, TimeUnit.MINUTES)) { + throw new RuntimeException( + "Could not finish rpc within 1 minute, the server is likely down"); + } + + if (failed != null) { + throw new RuntimeException(failed); + } + return logs.toString(); } + } - private interface GrpcRunnable { - /** - * Perform a grpc and return all the logs. - */ - String run(RouteGuideBlockingStub blockingStub, RouteGuideStub asyncStub) throws Exception; - } - - private class GetFeatureRunnable implements GrpcRunnable { - @Override - public String run(RouteGuideBlockingStub blockingStub, RouteGuideStub asyncStub) - throws Exception { - return getFeature(409146138, -746188906, blockingStub); - } - - /** - * Blocking unary call example. Calls getFeature and prints the response. - */ - private String getFeature(int lat, int lon, RouteGuideBlockingStub blockingStub) - throws StatusRuntimeException { - StringBuffer logs = new StringBuffer(); - appendLogs(logs, "*** GetFeature: lat={0} lon={1}", lat, lon); - - Point request = Point.newBuilder().setLatitude(lat).setLongitude(lon).build(); - - Feature feature; - feature = blockingStub.getFeature(request); - if (RouteGuideUtil.exists(feature)) { - appendLogs(logs, "Found feature called \"{0}\" at {1}, {2}", - feature.getName(), - RouteGuideUtil.getLatitude(feature.getLocation()), - RouteGuideUtil.getLongitude(feature.getLocation())); - } else { - appendLogs(logs, "Found no feature at {0}, {1}", - RouteGuideUtil.getLatitude(feature.getLocation()), - RouteGuideUtil.getLongitude(feature.getLocation())); - } - return logs.toString(); - } - } + private static class RouteChatRunnable implements GrpcRunnable { + private Throwable failed; - private class ListFeaturesRunnable implements GrpcRunnable { - @Override - public String run(RouteGuideBlockingStub blockingStub, RouteGuideStub asyncStub) - throws Exception { - return listFeatures(400000000, -750000000, 420000000, -730000000, blockingStub); - } - - /** - * Blocking server-streaming example. Calls listFeatures with a rectangle of interest. - * Prints each response feature as it arrives. - */ - private String listFeatures(int lowLat, int lowLon, int hiLat, int hiLon, - RouteGuideBlockingStub blockingStub) throws StatusRuntimeException { - StringBuffer logs = new StringBuffer("Result: "); - appendLogs(logs, "*** ListFeatures: lowLat={0} lowLon={1} hiLat={2} hiLon={3}", - lowLat, lowLon, hiLat, hiLon); - - Rectangle request = Rectangle.newBuilder() - .setLo(Point.newBuilder().setLatitude(lowLat).setLongitude(lowLon).build()) - .setHi(Point.newBuilder().setLatitude(hiLat).setLongitude(hiLon).build()) - .build(); - Iterator<Feature> features; - features = blockingStub.listFeatures(request); - - while (features.hasNext()) { - Feature feature = features.next(); - appendLogs(logs, feature.toString()); - } - return logs.toString(); - } + @Override + public String run(RouteGuideBlockingStub blockingStub, RouteGuideStub asyncStub) + throws Exception { + return routeChat(asyncStub); } - private class RecordRouteRunnable implements GrpcRunnable { - private Throwable failed; - - @Override - public String run(RouteGuideBlockingStub blockingStub, RouteGuideStub asyncStub) - throws Exception { - List<Point> points = new ArrayList<Point>(); - points.add(Point.newBuilder() - .setLatitude(407838351).setLongitude(-746143763).build()); - points.add(Point.newBuilder() - .setLatitude(408122808).setLongitude(-743999179).build()); - points.add(Point.newBuilder() - .setLatitude(413628156).setLongitude(-749015468).build()); - return recordRoute(points, 5, asyncStub); - } - - /** - * Async client-streaming example. Sends {@code numPoints} randomly chosen points from - * {@code features} with a variable delay in between. Prints the statistics when they are - * sent from the server. - */ - private String recordRoute(List<Point> points, int numPoints, RouteGuideStub asyncStub) - throws InterruptedException, RuntimeException { - final StringBuffer logs = new StringBuffer(); - appendLogs(logs, "*** RecordRoute"); - - final CountDownLatch finishLatch = new CountDownLatch(1); - StreamObserver<RouteSummary> responseObserver = new StreamObserver<RouteSummary>() { + /** + * Bi-directional example, which can only be asynchronous. Send some chat messages, and print + * any chat messages that are sent from the server. + */ + private String routeChat(RouteGuideStub asyncStub) + throws InterruptedException, RuntimeException { + final StringBuffer logs = new StringBuffer(); + appendLogs(logs, "*** RouteChat"); + final CountDownLatch finishLatch = new CountDownLatch(1); + StreamObserver<RouteNote> requestObserver = + asyncStub.routeChat( + new StreamObserver<RouteNote>() { @Override - public void onNext(RouteSummary summary) { - appendLogs(logs, "Finished trip with {0} points. Passed {1} features. " - + "Travelled {2} meters. It took {3} seconds.", summary.getPointCount(), - summary.getFeatureCount(), summary.getDistance(), - summary.getElapsedTime()); + public void onNext(RouteNote note) { + appendLogs( + logs, + "Got message \"{0}\" at {1}, {2}", + note.getMessage(), + note.getLocation().getLatitude(), + note.getLocation().getLongitude()); } @Override public void onError(Throwable t) { - failed = t; - finishLatch.countDown(); + failed = t; + finishLatch.countDown(); } @Override public void onCompleted() { - appendLogs(logs, "Finished RecordRoute"); - finishLatch.countDown(); - } - }; - - StreamObserver<Point> requestObserver = asyncStub.recordRoute(responseObserver); - try { - // Send numPoints points randomly selected from the points list. - Random rand = new Random(); - for (int i = 0; i < numPoints; ++i) { - int index = rand.nextInt(points.size()); - Point point = points.get(index); - appendLogs(logs, "Visiting point {0}, {1}", RouteGuideUtil.getLatitude(point), - RouteGuideUtil.getLongitude(point)); - requestObserver.onNext(point); - // Sleep for a bit before sending the next one. - Thread.sleep(rand.nextInt(1000) + 500); - if (finishLatch.getCount() == 0) { - // RPC completed or errored before we finished sending. - // Sending further requests won't error, but they will just be thrown away. - break; - } - } - } catch (RuntimeException e) { - // Cancel RPC - requestObserver.onError(e); - throw e; - } - // Mark the end of requests - requestObserver.onCompleted(); - - // Receiving happens asynchronously - if (!finishLatch.await(1, TimeUnit.MINUTES)) { - throw new RuntimeException( - "Could not finish rpc within 1 minute, the server is likely down"); - } - - if (failed != null) { - throw new RuntimeException(failed); - } - return logs.toString(); - } - } - - private class RouteChatRunnable implements GrpcRunnable { - private Throwable failed; - - @Override - public String run(RouteGuideBlockingStub blockingStub, RouteGuideStub asyncStub) - throws Exception { - return routeChat(asyncStub); - } - - /** - * Bi-directional example, which can only be asynchronous. Send some chat messages, and - * print any chat messages that are sent from the server. - */ - private String routeChat(RouteGuideStub asyncStub) throws InterruptedException, - RuntimeException { - final StringBuffer logs = new StringBuffer(); - appendLogs(logs, "*** RouteChat"); - final CountDownLatch finishLatch = new CountDownLatch(1); - StreamObserver<RouteNote> requestObserver = - asyncStub.routeChat(new StreamObserver<RouteNote>() { - @Override - public void onNext(RouteNote note) { - appendLogs(logs, "Got message \"{0}\" at {1}, {2}", note.getMessage(), - note.getLocation().getLatitude(), - note.getLocation().getLongitude()); - } - - @Override - public void onError(Throwable t) { - failed = t; - finishLatch.countDown(); - } - - @Override - public void onCompleted() { - appendLogs(logs,"Finished RouteChat"); - finishLatch.countDown(); - } - }); - - try { - RouteNote[] requests = - {newNote("First message", 0, 0), newNote("Second message", 0, 1), - newNote("Third message", 1, 0), newNote("Fourth message", 1, 1)}; - - for (RouteNote request : requests) { - appendLogs(logs, "Sending message \"{0}\" at {1}, {2}", request.getMessage(), - request.getLocation().getLatitude(), - request.getLocation().getLongitude()); - requestObserver.onNext(request); + appendLogs(logs, "Finished RouteChat"); + finishLatch.countDown(); } - } catch (RuntimeException e) { - // Cancel RPC - requestObserver.onError(e); - throw e; - } - // Mark the end of requests - requestObserver.onCompleted(); - - // Receiving happens asynchronously - if (!finishLatch.await(1, TimeUnit.MINUTES)) { - throw new RuntimeException( - "Could not finish rpc within 1 minute, the server is likely down"); - } - - if (failed != null) { - throw new RuntimeException(failed); - } - - return logs.toString(); - } - } - - private static void appendLogs(StringBuffer logs, String msg, Object... params) { - if (params.length > 0) { - logs.append(MessageFormat.format(msg, params)); - } else { - logs.append(msg); + }); + + try { + RouteNote[] requests = { + newNote("First message", 0, 0), + newNote("Second message", 0, 1), + newNote("Third message", 1, 0), + newNote("Fourth message", 1, 1) + }; + + for (RouteNote request : requests) { + appendLogs( + logs, + "Sending message \"{0}\" at {1}, {2}", + request.getMessage(), + request.getLocation().getLatitude(), + request.getLocation().getLongitude()); + requestObserver.onNext(request); } - logs.append(System.lineSeparator()); + } catch (RuntimeException e) { + // Cancel RPC + requestObserver.onError(e); + throw e; + } + // Mark the end of requests + requestObserver.onCompleted(); + + // Receiving happens asynchronously + if (!finishLatch.await(1, TimeUnit.MINUTES)) { + throw new RuntimeException( + "Could not finish rpc within 1 minute, the server is likely down"); + } + + if (failed != null) { + throw new RuntimeException(failed); + } + + return logs.toString(); } + } - private static RouteNote newNote(String message, int lat, int lon) { - return RouteNote.newBuilder().setMessage(message) - .setLocation(Point.newBuilder().setLatitude(lat).setLongitude(lon).build()).build(); + private static void appendLogs(StringBuffer logs, String msg, Object... params) { + if (params.length > 0) { + logs.append(MessageFormat.format(msg, params)); + } else { + logs.append(msg); } + logs.append("\n"); + } + + private static RouteNote newNote(String message, int lat, int lon) { + return RouteNote.newBuilder() + .setMessage(message) + .setLocation(Point.newBuilder().setLatitude(lat).setLongitude(lon).build()) + .build(); + } } diff --git a/examples/android/routeguide/app/src/main/java/io/grpc/routeguideexample/RouteGuideUtil.java b/examples/android/routeguide/app/src/main/java/io/grpc/routeguideexample/RouteGuideUtil.java index 6ad13f479..3ef0e5f17 100644 --- a/examples/android/routeguide/app/src/main/java/io/grpc/routeguideexample/RouteGuideUtil.java +++ b/examples/android/routeguide/app/src/main/java/io/grpc/routeguideexample/RouteGuideUtil.java @@ -16,36 +16,22 @@ package io.grpc.routeguideexample; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.net.URL; -import java.util.List; -/** - * Common utilities for the RouteGuide demo. - */ +/** Common utilities for the RouteGuide demo. */ public class RouteGuideUtil { private static final double COORD_FACTOR = 1e7; - /** - * Gets the latitude for the given point. - */ + /** Gets the latitude for the given point. */ public static double getLatitude(Point location) { return location.getLatitude() / COORD_FACTOR; } - /** - * Gets the longitude for the given point. - */ + /** Gets the longitude for the given point. */ public static double getLongitude(Point location) { return location.getLongitude() / COORD_FACTOR; } - /** - * Indicates whether the given feature exists (i.e. has a valid name). - */ + /** Indicates whether the given feature exists (i.e. has a valid name). */ public static boolean exists(Feature feature) { return feature != null && !feature.getName().isEmpty(); } diff --git a/examples/android/routeguide/app/src/main/res/layout/activity_routeguide.xml b/examples/android/routeguide/app/src/main/res/layout/activity_routeguide.xml index 4b73bf34a..b76a7a301 100644 --- a/examples/android/routeguide/app/src/main/res/layout/activity_routeguide.xml +++ b/examples/android/routeguide/app/src/main/res/layout/activity_routeguide.xml @@ -23,18 +23,18 @@ android:hint="Enter Port" /> </LinearLayout> - <LinearLayout + <LinearLayout style="?android:buttonBarStyle" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> - <Button + <Button style="?android:buttonBarButtonStyle" android:id="@+id/start_route_guide_button" android:layout_weight="1" android:layout_width="0dp" android:layout_height="wrap_content" android:onClick="startRouteGuide" android:text="Start Route Guide" /> - <Button + <Button style="?android:buttonBarButtonStyle" android:id="@+id/exit_route_guide_button" android:layout_weight="1" android:layout_width="0dp" diff --git a/examples/android/routeguide/build.gradle b/examples/android/routeguide/build.gradle index 316dc9dbb..7b299d637 100644 --- a/examples/android/routeguide/build.gradle +++ b/examples/android/routeguide/build.gradle @@ -2,10 +2,11 @@ buildscript { repositories { + google() jcenter() } dependencies { - classpath 'com.android.tools.build:gradle:2.3.1' + classpath 'com.android.tools.build:gradle:3.0.1' classpath "com.google.protobuf:protobuf-gradle-plugin:0.8.3" // NOTE: Do not place your application dependencies here; they belong @@ -15,6 +16,7 @@ buildscript { allprojects { repositories { + google() jcenter() mavenLocal() } |