筆者所用開發環境:Win7 x64,Android Studio3.2.1,JDK1.8,Gradle 4.6
0.編寫.proto文件、編譯.proto生成對應Java源文件,具體步驟略(參考上一篇文章https://www.cnblogs.com/areful/p/10404506.html)。
1.新建Android app項目,將上一步生成的Java源文件復制到項目根目錄。修改build.gradle:
...
buildscript {
...
dependencies {
...
classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.6'
}
}
...
2.修改app/build.gradle:
apply plugin: 'com.android.application'
apply plugin: 'com.google.protobuf'
...
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'io.grpc:grpc-netty-shaded:1.15.1'
implementation 'io.grpc:grpc-netty:1.15.1'
implementation 'io.grpc:grpc-core:1.15.1'
implementation 'io.grpc:grpc-protobuf:1.15.1'
implementation 'io.grpc:grpc-stub:1.15.1'
implementation 'io.grpc:grpc-alts:1.15.1'
implementation 'io.netty:netty-tcnative-boringssl-static:2.0.18.Final'
implementation 'com.google.protobuf:protobuf-java-util:3.0.0-beta-1'
}
3.添加app需要權限:
<uses-permission android:name="android.permission.INTERNET" />
4.app中調用GRPC:
package cn.areful.sample.grpc;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import io.grpc.examples.helloworld.HelloWorldClient;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HelloWorldClient client = new HelloWorldClient("10.102.54.2", 50051);
try {
client.greet("World!");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
client.shutdown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
5.先Java中運行Server端(參見https://www.cnblogs.com/areful/p/10404506.html),再運行app,logcat:

