Android中使用GRPC

笔者所用开发环境:Win7 x64,Android Studio3.2.1,JDK1.8,Gradle 4.6

0.编写.proto文件、编译.proto生成对应Java源文件,具体步骤略,请参考上一篇文章https://www.cnblogs.com/areful/p/10404506.html

1.修改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.support.v7.app.AppCompatActivity;
import android.os.Bundle;

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);

        try {
            HelloWorldClient.main(new String[]{});
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

  注:HelloWorldClient中初始化IP地址需修改为对应Server地址,在笔者机器上如下:

HelloWorldClient client = new HelloWorldClient("10.102.54.2", 50051);

  

5.先Java中运行Server端(参见https://www.cnblogs.com/areful/p/10404506.html),再运行app,logcat:

猜你喜欢

转载自www.cnblogs.com/areful/p/10405266.html