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.新建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:

 

转载于:https://www.cnblogs.com/areful/p/10405266.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值